> ## Documentation Index
> Fetch the complete documentation index at: https://docs.suprsend.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Integration

> Integrate the SuprSend JavaScript Web SDK to enable WebPush, preferences, and In-app feed across React, Vue, Next.js, and other modern web frameworks.

<Info>
  📘 **Upgrading major version of SDK:**

  We have changed the web SDK authentication from workspace key-secret to public key and JWT based authentication. This is done to improve security in frontend applications.

  * Refer the v1 SDK [documentation](https://github.com/suprsend/suprsend-browser-sdk/tree/main/docs)

  * For migrating to v2, follow this [guide](/docs/migration-guide-from-v1)
</Info>

This is the client JavaScript SDK used to integrate SuprSend features like Webpush, Preferences in JavaScript websites like React, Next.js, Angular, Vue.js etc.

<CardGroup cols="2">
  <Card title="NPM Link" icon="link" iconType="solid" href="https://www.npmjs.com/package/@suprsend/web-sdk" />

  <Card title="GitHub Link" icon="github" iconType="solid" href="https://github.com/suprsend/suprsend-web-sdk" />
</CardGroup>

## Installation

<CodeGroup>
  ```shell npm theme={"system"}
  npm install @suprsend/web-sdk@latest
  ```

  ```shell yarn theme={"system"}
  yarn add @suprsend/web-sdk@latest
  ```
</CodeGroup>

## Integration

<Steps>
  <Step title="Create Client">
    Create suprSendClient instance and use same instance to access all the methods of SuprSend library.&#x20;

    <CodeGroup>
      ```typescript syntax theme={"system"}
      import SuprSend from '@suprsend/web-sdk';

      export const suprSendClient = new SuprSend(publicApiKey: string);
      ```
    </CodeGroup>

    | Params         | Description                                                                                                                    |
    | -------------- | ------------------------------------------------------------------------------------------------------------------------------ |
    | publicApiKey\* | This is public Key used to authenticate API calls to SuprSend. Get it in SuprSend dashboard **ApiKeys -> Public Keys** section |
  </Step>

  <Step title="Authenticate User">
    Authenticate user so that all the actions performed after authenticating will be w\.r.t that user. This is mandatory step and need to be called before using any other method. This is usually performed after successful login and on reload of page to re-authenticate user.

    <CodeGroup>
      ```typescript syntax theme={"system"}
      const authResponse = await suprSendClient.identify(
        distinctId: any,
        userToken?: string, // only needed in production environments for security
        {
          tenantId?: string, // only needed in multi-tenant workspaces
          refreshUserToken: (oldUserToken: string, tokenPayload: Dictionary) => Promise<string>
        }
      );
      ```
    </CodeGroup>

    | Properties       | Description                                                                                                                                                                                                                                                             |
    | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | distinctId\*     | Unique identifier to identify a user across platform.                                                                                                                                                                                                                   |
    | userToken        | Mandatory when enhanced security mode is on. This is ES256 JWT token generated in your server-side. Refer [docs](/docs/client-authentication#enhanced-security-mode-with-signed-user-token) to create userToken.                                                        |
    | tenantId         | Needed only when your workspace has multiple tenants. Scopes the identified user's activity to that tenant, and is inherited by events, preferences and in-app feed. Its value must match `scope.tenant_id` in the `userToken` payload, else it raises a scoping error. |
    | refreshUserToken | This function is called by SDK internally to get new userToken before existing token is expired. The returned string is used as the new userToken.                                                                                                                      |

    **Returns:** `Promise<ApiResponse>`

    #### 2.1 Check if user is authenticated

    This method will check if user is authenticated i.e. `distinctId` is attached to SuprSend instance. To check for userToken also pass checkUserToken flag true.

    <CodeGroup>
      ```typescript syntax theme={"system"}
      suprSendClient.isIdentified(checkUserToken?: boolean): boolean
      ```
    </CodeGroup>
  </Step>

  <Step title="Reset user">
    This will remove user data from SuprSend instance. This is usually called on logout action.

    <CodeGroup>
      ```typescript syntax theme={"system"}
      await suprSendClient.reset();
      ```
    </CodeGroup>

    **Returns:** `Promise<ApiResponse>`
  </Step>
</Steps>

## Change active tenant

Once a tenant is set in `identify`, all SDK calls (events, preferences, in-app feed) are scoped to the active tenant. Use this method to switch the active tenant of an identified user. This is meant for users whose `userToken` scopes multiple tenants (`scope.tenant_id` as an array) — identify once and switch between tenants without resetting the session.

<CodeGroup>
  ```typescript syntax theme={"system"}
  const response = suprSendClient.changeTenant(tenantId: string);
  ```
</CodeGroup>

| Properties | Description                                                                                                                                           |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| tenantId\* | Tenant to switch to. Used by subsequent events and newly initialized preferences and feed requests. Must be one of the tenants scoped in `userToken`. |

**Returns:** `ApiResponse`

<Note>
  Already running feed instances and previously fetched preferences keep the tenant they were initialized with when `changeTenant` is called. Re-initialize the feed and call `getPreferences` again to load data for the new tenant.
</Note>

## Response structure

Almost all the methods in this SDK return response type `Promise<ApiResponse>`

<CodeGroup>
  ```typescript syntax theme={"system"}
  interface ApiResponse {
    status: 'success' | 'error';
    statusCode?: number;
    error?: { type?: string; message?: string };
    body?: any;
  }

  // success response
  {
    status: "success",
    body?: any,
    statusCode?: number
  }

  // error response
  {
    status: "error",
    error: {
      type: string,
      message: string
    }
  }
  ```
</CodeGroup>

***
