UNPKG

lightswitch-js

Version:

A minimal SDK for subscription management, entitlements, and paywalls

222 lines (173 loc) • 6.49 kB
# lightswitch-js [![npm version](https://badge.fury.io/js/lightswitch-js.svg)](https://badge.fury.io/js/lightswitch-js) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) A minimal SDK for subscription management, entitlements, and paywalls. ## šŸ“¦ Installation ```bash npm install lightswitch-js ``` ```bash yarn add lightswitch-js ``` ```bash pnpm add lightswitch-js ``` ## šŸ“ Project Structure ``` lightswitch-sdk-js/ ā”œā”€ā”€ index.js # Main entry point ā”œā”€ā”€ README.md # This file │ ā”œā”€ā”€ components/ # React Components │ ā”œā”€ā”€ LightswitchProvider.jsx # Main provider component │ └── ProtectedRoute.jsx # Route protection component │ ā”œā”€ā”€ hooks/ # React Hooks │ ā”œā”€ā”€ useLightswitch.js # Main SDK hook │ ā”œā”€ā”€ useAuth.js # Authentication hook │ └── useEntitlement.js # Entitlement checking hook │ ā”œā”€ā”€ core/ # Core Vanilla JS │ ā”œā”€ā”€ index.js # Core SDK entry │ ā”œā”€ā”€ api.js # API communication │ ā”œā”€ā”€ auth.js # Authentication logic │ ā”œā”€ā”€ config.js # Configuration │ ā”œā”€ā”€ entitlement.js # Entitlement checking │ ā”œā”€ā”€ paywall.js # Paywall rendering │ └── tracking.js # Analytics │ └── examples/ # Usage Examples ā”œā”€ā”€ basic-setup.js # Minimal setup ā”œā”€ā”€ advanced-usage.js # Advanced features └── test-without-supabase.js # Core testing ``` ## šŸš€ Quick Start ### 1. Basic Setup (Recommended) ```jsx import React from 'react'; import { LightswitchProvider, ProtectedRoute } from 'lightswitch-js'; import { supabase } from './your-supabase-client'; const App = () => ( <LightswitchProvider publishableKey="pk_your-app_your-key" appSlug="your-app" supabaseClient={supabase} autoShowPaywall={true} > <BrowserRouter> <Routes> <Route path="/" element={<Landing />} /> <Route path="/app" element={ <ProtectedRoute> <Dashboard /> </ProtectedRoute> } /> </Routes> </BrowserRouter> </LightswitchProvider> ); ``` ### 2. Advanced Usage ```jsx import { useLightswitch, useEntitlement } from 'lightswitch-js'; const MyComponent = () => { const { showPaywall, redirectToLogin } = useLightswitch(); const { entitled, loading } = useEntitlement('has_access'); if (!entitled) { return <button onClick={showPaywall}>Upgrade</button>; } return <div>Premium content!</div>; }; ``` ## šŸ“š API Reference ### Components #### `LightswitchProvider` Main provider that wraps your app and handles SDK initialization. **Props:** - `publishableKey` (string) - Your app's publishable key - `appSlug` (string) - Your app slug - `supabaseClient` (optional) - Supabase client for auth integration - `autoShowPaywall` (boolean) - Auto-show paywall when not entitled #### `ProtectedRoute` Component that protects routes based on entitlements. **Props:** - `children` (ReactNode) - Content to show when entitled - `feature` (string) - Feature to check (defaults to "has_access") ### Hooks #### `useLightswitch()` Main hook for SDK functionality. **Returns:** - `showPaywall()` - Show paywall modal - `redirectToLogin()` - Redirect to login - `redirectToSignup()` - Redirect to signup - `isInitialized` - SDK initialization status #### `useEntitlement(feature, options)` Hook for checking entitlements. **Parameters:** - `feature` (string) - Feature to check - `options.checkOnMount` (boolean) - Check on component mount **Returns:** - `entitled` (boolean) - Whether user is entitled - `loading` (boolean) - Loading state - `error` (string) - Error message if any #### `useLightswitchAuth()` Hook for authentication state. **Returns:** - `isAuthenticated` (boolean) - Auth status - `user` (object) - User info - `logout()` - Logout function - `setSupabaseSession(token)` - Set Supabase session from external token ## šŸ”§ Core Features ### āœ… 7 Key Functionalities: 1. **Redirecting for sign up** - `useLightswitch().redirectToSignup()` 2. **Redirecting to Login** - `useLightswitch().redirectToLogin()` 3. **Auth token sets supabase session** - Automatic via `useAuth.js` 4. **Initialization** - Via `LightswitchProvider` 5. **Check for entitlement** - Via `useEntitlement` hook 6. **Rendering Paywall** - Via `showPaywall()` function 7. **Analytics** - Via `trackEvent()` function ## šŸ“– Examples See the `/examples` folder for complete usage examples: - `basic-setup.js` - Minimal integration - `advanced-usage.js` - Using hooks for control - `external-auth-flow.js` - Handle external auth flows (funnels) - `test-without-supabase.js` - Core functionality testing ## šŸ”— External Auth Integration ### ✨ **Automatic (Recommended)** The SDK automatically handles external auth tokens (like from funnels) with **zero additional code**: ```javascript // That's it! The SDK handles everything automatically <LightswitchProvider publishableKey="pk_your-key" appSlug="your-app" supabaseClient={supabaseClient} autoExternalAuth={true} // šŸ‘ˆ Default: true > <YourApp /> </LightswitchProvider> ``` **What happens automatically:** 1. User returns from funnel with `?token=SUPABASE_TOKEN` 2. SDK detects token during initialization 3. Sets Supabase session and updates auth state 4. Cleans up URL parameters 5. User sees authenticated app immediately ### šŸ› ļø **Manual (If Needed)** If you need custom control: ```javascript // Method 1: Using the hook const { setSupabaseSession } = useLightswitch(); await setSupabaseSession(token); // Method 2: Direct import import { setSupabaseSession } from 'lightswitch-js'; await setSupabaseSession(token); // Method 3: Complete control import { handleExternalAuthReturn } from 'lightswitch-js'; await handleExternalAuthReturn({ redirectPath: '/dashboard' }); ``` ## šŸ—ļø Architecture The SDK is organized into three layers: 1. **Components** - React components for easy integration 2. **Hooks** - React hooks for advanced control 3. **Core** - Vanilla JS functionality that works anywhere This structure makes it easy to understand, maintain, and extend the SDK while keeping the integration footprint minimal.