Skip to main content

Installation

npm install @encorekit/web-sdk

Complete Setup Example

Create a React app with Vite and integrate the Encore SDK:
App.tsx
import { useState, useEffect } from 'react';
import Encore from '@encorekit/web-sdk';

function App() {
  const [isInitialized, setIsInitialized] = useState(false);
  const [userId, setUserId] = useState<string>('');
  const [status, setStatus] = useState<{
    message: string;
    type: 'info' | 'success' | 'error';
  } | null>(null);

  // Initialize SDK on mount
  useEffect(() => {
    try {
      // Generate or retrieve userId from localStorage
      const storageKey = 'encore_user_id';
      let storedUserId = localStorage.getItem(storageKey);
      
      if (!storedUserId) {
        storedUserId = 'user_' + Math.random().toString(36).substring(2, 15);
        localStorage.setItem(storageKey, storedUserId);
      }
      
      Encore.configure({
        apiKey: process.env.REACT_APP_ENCORE_API_KEY || 'YOUR_API_KEY',
        userId: storedUserId,
        environment: 'production',
        logLevel: 'debug',
      });
      
      const currentUserId = Encore.getCurrentUserId();
      setUserId(currentUserId || '');
      setIsInitialized(true);
      setStatus({
        message: 'Encore SDK initialized successfully!',
        type: 'success',
      });
    } catch (error) {
      setStatus({
        message: `Failed to initialize SDK: ${error instanceof Error ? error.message : 'Unknown error'}`,
        type: 'error',
      });
    }
  }, []);

  const handleIdentifyUser = (userId: string) => {
    try {
      Encore.identify(userId, {
        email: 'user@example.com',
        subscriptionTier: 'free'
      });
      setUserId(userId);
      setStatus({
        message: `User identified as: ${userId}`,
        type: 'success',
      });
    } catch (error) {
      setStatus({
        message: `Failed to identify user: ${error instanceof Error ? error.message : 'Unknown error'}`,
        type: 'error',
      });
    }
  };

  const handlePresentOffer = async () => {
    setStatus({
      message: 'Presenting offer...',
      type: 'info',
    });

    try {
      const result = await Encore.presentOffer();
      
      if (result.granted) {
        setStatus({
          message: 'Offer granted successfully!',
          type: 'success',
        });
      } else {
        setStatus({
          message: `Offer not granted`,
          type: 'info',
        });
      }
    } catch (error) {
      setStatus({
        message: `Failed to present offer: ${error instanceof Error ? error.message : 'Unknown error'}`,
        type: 'error',
      });
    }
  };

  return (
    <div>
      <h1>Encore SDK - React</h1>
      <p>Status: {isInitialized ? '✓ Initialized' : '✗ Not Initialized'}</p>
      <p>User ID: {userId || 'Not set'}</p>
      
      {status && <div className={`status-${status.type}`}>{status.message}</div>}
      
      <button onClick={handlePresentOffer} disabled={!isInitialized}>
        🎁 Present Offer
      </button>
    </div>
  );
}

export default App;

Environment Variables

Create a .env file in your project root:
REACT_APP_ENCORE_API_KEY=your-api-key-here

React Patterns

Custom Hook for Encore

hooks/useEncore.ts
import { useState, useEffect } from 'react';
import Encore from '@encorekit/web-sdk';

export function useEncore(apiKey: string) {
  const [isInitialized, setIsInitialized] = useState(false);
  const [userId, setUserId] = useState<string>('');

  useEffect(() => {
    const storageKey = 'encore_user_id';
    let storedUserId = localStorage.getItem(storageKey);
    
    if (!storedUserId) {
      storedUserId = 'user_' + Math.random().toString(36).substring(2, 15);
      localStorage.setItem(storageKey, storedUserId);
    }

    Encore.configure({
      apiKey,
      userId: storedUserId,
      environment: 'production',
    });

    setUserId(storedUserId);
    setIsInitialized(true);
  }, [apiKey]);

  return { isInitialized, userId };
}

Working Example

Full working example: encore-web-sdk/examples/react

Next Steps