# Descope SDK for React

The Descope SDK for React provides convenient access to the Descope for an application written on top of React. You can read more on the [Descope Website](https://descope.com).

## Requirements

- The SDK supports React version 16 and above.
- The SDK also runs on [Preact](#preact-support) 10.11+ via `preact/compat`.
- A Descope `Project ID` is required for using the SDK. Find it on the [project page in the Descope Console](https://app.descope.com/settings/project).

## Installing the SDK

Install the package with:

```bash
npm i --save @descope/react-sdk
```

## Usage

### Wrap your app with Auth Provider

```js
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
  return (
    <AuthProvider
      projectId="my-project-id"
      // If the Descope project manages the token response in cookies, a custom domain
      // must be configured (e.g., https://auth.app.example.com)
      // and should be set as the baseUrl property.
      // baseUrl = "https://auth.app.example.com"

      // Optional: Hooks object for SDK lifecycle events
      // hooks={{
      //   beforeRequest: (req) => {
      //     console.log('Before request', {
      //       method: req.method,
      //       path: req.path,
      //       queryParams: req.queryParams,
      //     });
      //     // Modify the request as needed
      //     return req;
      //   },
      //   afterRequest: async (req, res) => {
      //     console.log('After request', {
      //       reqMethod: req.method,
      //       reqPath: req.path,
      //       resStatus: res.status,
      //     });
      //   },
      // }}
    >
      <App />
    </AuthProvider>
  );
};
```

### Use Descope to render specific flow

You can use **default flows** or **provide flow id** directly to the Descope component

#### 1. Default flows

```js
import { SignInFlow } from '@descope/react-sdk'
// you can choose flow to run from the following
// import { SignUpFlow } from '@descope/react-sdk'
// import { SignUpOrInFlow } from '@descope/react-sdk'

const App = () => {
    return (
        {...}
        <SignInFlow
            onSuccess={(e) => console.log('Logged in!')}
            onError={(e) => console.log('Could not logged in!')}
        />
    )
}
```

#### 2. Provide flow id

```js
import { Descope } from '@descope/react-sdk'

const App = () => {
    return (
        {...}
        <Descope
            flowId="my-flow-id"
            onSuccess={(e) => console.log('Logged in!')}
            onError={(e) => console.log('Could not logged in')}
            // onReady={() => {
            //   This event is triggered when the flow is ready to be displayed
            //   Its useful for showing a loading indication before the page ready
            //   console.log('Flow is ready');
            // }}

            // theme can be "light", "dark" or "os", which auto select a theme based on the OS theme. Default is "light"
            // theme="dark"

            // locale can be any supported locale which the flow's screen translated to, if not provided, the locale is taken from the browser's locale.
            // locale="en"

            // debug can be set to true to enable debug mode
            // debug={true}

            // tenant ID for SSO (SAML) login. If not provided, Descope will use the domain of available email to choose the tenant
            // tenant=<tenantId>

            // Redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user)
            // redirectUrl=<redirectUrl>

            // autoFocus can be true, false or "skipFirstScreen". Default is true.
            // - true: automatically focus on the first input of each screen
            // - false: do not automatically focus on screen's inputs
            // - "skipFirstScreen": automatically focus on the first input of each screen, except first screen
            // autoFocus="skipFirstScreen"

            // validateOnBlur: set it to true will show input validation errors on blur, in addition to on submit

            // restartOnError: if set to true, in case of flow version mismatch, will restart the flow if the components version was not changed. Default is false

            // sendSessionToken: if set to true, flow start/next requests include the current session JWT, exposing its validated claims to the flow via the sessionJwtClaims context key. Default is false

            // errorTransformer is a function that receives an error object and returns a string. The returned string will be displayed to the user.
            // NOTE: errorTransformer is not required. If not provided, the error object will be displayed as is.
            // Example:
            // const errorTransformer = useCallback(
            // 	(error: { text: string; type: string }) => {
            // 		const translationMap = {
            // 			SAMLStartFailed: 'Failed to start SAML flow'
            // 		};
            // 		return translationMap[error.type] || error.text;
            // 	},
            // 	[]
            // );
            // ...
            // errorTransformer={errorTransformer}
            // ...


            // form is an object the initial form context that is used in screens inputs in the flow execution.
            // Used to inject predefined input values on flow start such as custom inputs, custom attributes and other inputs.
            // Keys passed can be accessed in flows actions, conditions and screens prefixed with "form.".
            // NOTE: form is not required. If not provided, 'form' context key will be empty before user input.
            // Example:
            // ...
            // form={{ email: "predefinedname@domain.com",  firstName: "test", "customAttribute.test": "aaaa", "myCustomInput": 12 }}
            // ...


            // client is an object the initial client context in the flow execution.
            // Keys passed can be accessed in flows actions and conditions prefixed with "client.".
            // NOTE: client is not required. If not provided, context key will be empty.
            // Example:
            // ...
            // client={{ version: "1.2.0" }}
            // ...


            // logger is an object describing how to log info, warn and errors.
            // NOTE: logger is not required. If not provided, the logs will be printed to the console.
            // Example:
            // const logger = {
            // 	info: (title: string, description: string, state: any) => {
            //      console.log(title, description, JSON.stringify(state));
            //  },
            // 	warn: (title: string, description: string) => {
            //      console.warn(title);
            //  },
            // 	error: (title: string, description: string) => {
            //      console.error('OH NOO');
            //  },
            // }
            // ...
            // logger={logger}
            // ...


            // Use a custom style name or keep empty to use the default style.
            // styleId="my-awesome-style"
            // Set a CSP nonce that will be used for style and script tags
            //nonce="rAnd0m"

            // popupOrigin: sets the expected origin for OAuth popup communication when redirect URL is on different origin than the main application. Required for cross-origin OAuth popup flows
            //popupOrigin="https://auth.example.com"

            // Clear screen error message on user input
            //dismissScreenErrorOnInput={true}

            // Outbound application ID to use for connecting to external services
            // outboundAppId="my-outbound-app-id"

            // Array of scopes to request from the outbound application
            // outboundAppScopes={["email", "profile"]}
        />
    )
}
```

### `onScreenUpdate`

A function that is called whenever there is a new screen state and after every next call. It receives the following parameters:

- `screenName`: The name of the screen that is about to be rendered
- `context`: An object containing the upcoming screen state. All server-produced screen data lives under `context.data`.
- `next`: A function that, when called, continues the flow execution
- `ref`: A reference to the descope-wc node

The function can be sync or async, and should return a boolean indicating whether a custom screen should be rendered:

- `true`: Render a custom screen
- `false`: Render the default flow screen

> **Breaking change (v3.0.0):** server-produced screen data that used to sit directly on
> `context` now lives under **`context.data`** — e.g. `context.totp` → `context.data.totp`,
> `context.inboundAppApproveScopes` → `context.data.inboundAppApproveScopes`. Status,
> `form`, and identity fields (`user` / `project` / `lastAuth`) stay at the top level.
> See the [@descope/web-component README](https://www.npmjs.com/package/@descope/web-component#the-context-object)
> for the full list of `context.data` fields.

This function allows rendering custom screens instead of the default flow screens.
It can be useful for highly customized UIs or specific logic not covered by the default screens

To render a custom screen, its elements should be appended as children of the `Descope` component

Usage example:

```javascript
const CustomScreen = ({onClick, setForm}) => {
  const onChange = (e) => setForm({ email: e.target.value })

  return (
    <>
      <input
        type="email"
        placeholder="Email"
        onChange={onChange}
      />
      <button
        type="button"
        onClick={onClick}
      >
        Submit
      </button>
    </>
)}

const Login = () => {
  const [state, setState] = useState();
  const [form, setForm] = useState();

  const onScreenUpdate = (screenName, context, next) => {
    setState({screenName, context, next})

    if (screenName === 'My Custom Screen') {
      return true;
    }

    return false;
  };

  return <Descope
  ...
  onScreenUpdate={onScreenUpdate}
  >{state.screenName === 'My Custom Screen' && <CustomScreen
    onClick={() => {
      // replace with the button interaction id
      state.next('interactionId', form)
    }}
    setForm={setForm}/>}
  </Descope>
}

```

### Use the `useDescope`, `useSession` and `useUser` hooks in your components in order to get authentication state, user details and utilities

This can be helpful to implement application-specific logic. Examples:

- Render different components if current session is authenticated
- Render user's content
- Logout button

```js
import { useDescope, useSession, useUser } from '@descope/react-sdk';
import { useCallback } from 'react';

const App = () => {
  // NOTE - `useDescope`, `useSession`, `useUser` should be used inside `AuthProvider` context,
  // and will throw an exception if this requirement is not met
  // useSession retrieves authentication state, session loading status, useful claims, and the session token
  // Use `isAuthenticated` to check whether there is an active session - not `sessionToken`
  const { isAuthenticated, isSessionLoading, sessionToken, claims } = useSession();
  // useUser retrieves the logged in user information
  const { user, isUserLoading } = useUser();
  // useDescope retrieves Descope SDK for further operations related to authentication
  // such as logout
  const sdk = useDescope();

  if (isSessionLoading || isUserLoading) {
    return <p>Loading...</p>;
  }

  const handleLogout = useCallback(() => {
    sdk.logout();
  }, [sdk]);

  if (isAuthenticated) {
    return (
      <>
        <p>Hello {user.name}</p>
        <button onClick={handleLogout}>Logout</button>
      </>
    );
  }

  return <p>You are not logged in</p>;
};
```

> **Important:** always use `isAuthenticated` to determine whether there is an active session - never `sessionToken`.
>
> `sessionToken` is empty whenever the session token is not accessible to client-side code, for example when the Descope project is [configured to manage the session token in cookies](#3-configure-descope-project-to-manage-session-token-in-cookies) (`Secure` + `HttpOnly` `DS` cookie), or when `persistTokens={false}` is set. In those setups the user is fully authenticated while `sessionToken` is an empty string, so guarding logic on it silently skips that logic:
>
> ```js
> // WRONG - skipped for authenticated users when the session token lives in an HttpOnly cookie
> if (!sessionToken && !isSessionLoading) {
>   return; // e.g. bailing out before calling sdk.logout()
> }
>
> // CORRECT
> if (!isAuthenticated && !isSessionLoading) {
>   return;
> }
> ```
>
> `isAuthenticated` is derived from the session's expiration, which the SDK receives in every token-storage mode. Read `sessionToken` only when you actually need the raw JWT (for example to attach it to an API request), and use `claims` to read claims out of the session.

### Trigger Auto Refresh

`useSession` triggers a single request to the Descope backend to attempt to refresh the session. If you **don't** `useSession` in your app, the session will not be refreshed automatically. If your app does not require `useSession`, you can trigger the refresh manually by calling `refresh` from `useDescope` hook. Example:

```js
const { refresh } = useDescope();
useEffect(() => {
  refresh();
}, [refresh]);
```

### Auto refresh session token

Descope SDK automatically refreshes the session token when it is about to expire. This is done in the background using the refresh token, without any additional configuration.
If you want to disable this behavior, you can pass `autoRefresh={false}` to the `AuthProvider` component. This will prevent the SDK from automatically refreshing the session token.

### Activity-Based Session Refresh

Pass `autoRefresh={{ customActivityTracking: true }}` to skip refresh calls for idle users. The SDK will only refresh when `sdk.markUserActive()` has been called since the last refresh. This reduces unnecessary API calls and enables accurate server-side session inactivity tracking.

**Step 1:** Enable it in `AuthProvider`:

```jsx
<AuthProvider projectId="my-project-id" autoRefresh={{ customActivityTracking: true }}>
  <App />
</AuthProvider>
```

**Step 2:** Create a `useActivityTracking` hook that calls `markUserActive()` on user interactions:

```jsx
import { useEffect } from 'react';
import { useDescope } from '@descope/react-sdk';

function useActivityTracking() {
  const sdk = useDescope();

  useEffect(() => {
    const { markUserActive } = sdk;

    document.addEventListener('click', markUserActive);
    document.addEventListener('keydown', markUserActive);
    document.addEventListener('touchstart', markUserActive);

    // Mark active when the user switches back to this tab
    const onVisibility = () => {
      if (document.visibilityState === 'visible') markUserActive();
    };
    document.addEventListener('visibilitychange', onVisibility);

    return () => {
      document.removeEventListener('click', markUserActive);
      document.removeEventListener('keydown', markUserActive);
      document.removeEventListener('touchstart', markUserActive);
      document.removeEventListener('visibilitychange', onVisibility);
    };
  }, [sdk]);
}
```

Call `useActivityTracking()` inside a component that is rendered within `<AuthProvider>` so `useDescope()` has access to the context:

```jsx
function Layout() {
  useActivityTracking();
  return <Outlet />;
}

<AuthProvider projectId="my-project-id" autoRefresh={{ customActivityTracking: true }}>
  <Layout />
</AuthProvider>;
```

**For more SDK usage examples refer to [docs](https://docs.descope.com/build/guides/client_sdks/)**

### Session token server validation (pass session token to server API)

When developing a full-stack application, it is common to have private server API which requires a valid session token:

![session-token-validation-diagram](https://docs.descope.com/static/SessionValidation-cf7b2d5d26594f96421d894273a713d8.png)

Note: Descope also provides server-side SDKs in various languages (NodeJS, Go, Python, etc). Descope's server SDKs have out-of-the-box session validation API that supports the options described bellow. To read more about session validation, Read [this section](https://docs.descope.com/build/guides/gettingstarted/#session-validation) in Descope documentation.

There are 2 ways to achieve that:

1. Using `getSessionToken` to get the token, and pass it on the `Authorization` Header (Recommended)
2. Passing `sessionTokenViaCookie` boolean prop to the `AuthProvider` component (Use cautiously, session token may grow, especially in cases of using authorization, or adding custom claim)

#### 1. Using `getSessionToken` to get the token

An example for api function, and passing the token on the `Authorization` header:

```js
import { getSessionToken } from '@descope/react-sdk';

// fetch data using back
// Note: Descope backend SDKs support extracting session token from the Authorization header
export const fetchData = async () => {
  const sessionToken = getSessionToken();
  const res = await fetch('/path/to/server/api', {
    headers: {
      Authorization: `Bearer ${sessionToken}`,
    },
  });
  // ... use res
};
```

An example for component that uses `fetchData` function from above

```js
// Component code
import { fetchData } from 'path/to/api/file'
import { useCallback } from 'react'

const Component = () => {
    const onClick = useCallback(() => {
        fetchData()
    },[])
    return (
        {...}
        {
            // button that triggers an API that may use session token
            <button onClick={onClick}>Click Me</button>
        }
    )
}
```

Note that ff Descope project settings are configured to manage session token in cookies, the `getSessionToken` function will return an empty string.

#### 2. Passing `sessionTokenViaCookie` boolean prop to the `AuthProvider`

Passing `sessionTokenViaCookie` prop to `AuthProvider` component. Descope SDK will automatically store session token on the `DS` cookie.

Note: Use this option if session token will stay small (less than 1k). Session token can grow, especially in cases of using authorization, or adding custom claims

Example:

```js
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
  return (
    <AuthProvider projectId="my-project-id" sessionTokenViaCookie>
      <App />
    </AuthProvider>
  );
};
```

Now, whenever you call `fetch`, the cookie will automatically be sent with the request. Descope backend SDKs also support extracting the token from the `DS` cookie.

Note:
The session token cookie is set as a [`Secure`](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.5) cookie. It will be sent only over HTTPS connections.
In addition, some browsers (e.g. Safari) may not store `Secure` cookie if the hosted page is running on an HTTP protocol.

The session token cookie is set to [`SameSite=Strict; Secure;`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) by default.
If you need to customize this, you can set `sessionTokenViaCookie={{sameSite: 'Lax', secure: false, cookieName: 'MY_COOKIE'}}`.

- `sameSite` (default: `Strict`) – Controls the SameSite attribute of the session cookie.
- `secure` (default: `true`) – If true, sets the cookie as Secure (sent only over HTTPS).
- `cookieName` (default: `DS`) – The name of the session token cookie. Useful for avoiding conflicts when running multiple Descope projects on the same domain.
- `domain` (default: auto-detected) – The domain for the session token cookie. If not specified, uses the domain from Descope project settings or current domain.

#### 3. Configure Descope project to manage session token in cookies

If project settings are configured to manage session token in cookies, Descope services will automatically set the session token in the `DS` cookie as a `Secure` and `HttpOnly` cookie. In this case, the session token will not be stored in the browser's and will not be accessible to the client-side code using `useSession` or `getSessionToken`.

However, `useSession`'s returned `isAuthenticated` and `claims` fields are always available - `isAuthenticated` still reflects the active session, and `claims` still exposes custom claims & common Descope claims from the token. Make sure your app checks authentication state with `isAuthenticated` and not with `sessionToken`, which will be empty in this mode.

### Helper Functions

You can also use the following functions to assist with various actions managing your JWT.

`getSessionToken()` - Get current session token.
`getRefreshToken()` - Get current refresh token. Note: Relevant only if the refresh token is stored in local storage. If the refresh token is stored in an `httpOnly` cookie, it will return an empty string.
`refresh(token = getRefreshToken())` - Force a refresh on current session token using an existing valid refresh token.
`isSessionTokenExpired(token = getSessionToken())` - Check whether the current session token is expired. Provide a session token if is not persisted (see [token persistence](#token-persistence)).
`isRefreshTokenExpired(token = getRefreshToken())` - Check whether the current refresh token is expired. Provide a refresh token if is not persisted (see [token persistence](#token-persistence)).
`getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
`getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.
`getCurrentTenant(token = getSessionToken())` - Get current tenant id from an existing session token (from the `dct` claim).

### Refresh token lifecycle

Descope SDK is automatically refreshes the session token when it is about to expire. This is done in the background using the refresh token, without any additional configuration.

If the Descope project settings are configured to manage tokens in cookies.
you must also configure a custom domain, and set it as the `baseUrl` prop in the `AuthProvider` component. See the above [`AuthProvider` usage](#wrap-your-app-with-auth-provider) for usage example.

### Token Persistence

Descope stores two tokens: the session token and the refresh token.

- The refresh token is either stored in local storage or an `httpOnly` cookie. This is configurable in the Descope console.
- The session token is stored in either local storage or a JS cookie. This behavior is configurable via the `sessionTokenViaCookie` prop in the `AuthProvider` component.

However, for security reasons, you may choose not to store tokens in the browser. In this case, you can pass `persistTokens={false}` to the `AuthProvider` component. This prevents the SDK from storing the tokens in the browser.

Notes:

- You must configure the refresh token to be stored in an `httpOnly` cookie in the Descope console. Otherwise, the refresh token will not be stored, and when the page is refreshed, the user will be logged out.
- You can still retrieve the session token using the `useSession` hook.

### Custom Refresh Cookie Name

When managing multiple Descope projects on the same domain, you can avoid refresh cookie conflicts by assigning a custom cookie name to your refresh token during the login process (for example, using Descope Flows). However, you must also configure the SDK to recognize this unique name by passing the `refreshCookieName` prop to the `AuthProvider` component.

This will signal Descope API to use the custom cookie name as the refresh token.

Note that this option is only available when the refresh token managed on cookies.

```js
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
  // pass the custom cookie name to the AuthProvider
  return (
    <AuthProvider projectId="my-project-id" refreshCookieName="MY_DSR">
      <App />
    </AuthProvider>
  );
};
```

### Custom Storage

By default the SDK reads and writes to `window.localStorage` for state that needs to outlive a single page load (last-authenticated user, tokens when they aren't stored in cookies, etc.). If `localStorage` is unavailable or you want to back these keys with something else — `sessionStorage`, an in-memory store, an encrypted wrapper — pass a `customStorage` prop to the `AuthProvider`.

```js
import { AuthProvider } from '@descope/react-sdk';

const inMemoryStorage = (() => {
  const map = new Map();
  return {
    getItem: (key) => (map.has(key) ? map.get(key) : null),
    setItem: (key, value) => {
      map.set(key, value);
    },
    removeItem: (key) => {
      map.delete(key);
    },
  };
})();

const AppRoot = () => (
  <AuthProvider projectId="my-project-id" customStorage={inMemoryStorage}>
    <App />
  </AuthProvider>
);
```

The object must implement the `CustomStorage` interface:

```ts
type CustomStorage = {
  getItem: (key: string) => string | null;
  setItem: (key: string, value: string) => void;
  removeItem: (key: string) => void;
};
```

> **Note:** `customStorage` backs the keys the SDK persists on your behalf (tokens, last-authenticated user). Make sure your implementation round-trips these keys cleanly — `getItem(key)` should return the same string that was last passed to `setItem(key, value)`. If your storage drops, filters, or namespaces keys so that they don't survive a round-trip, the features that rely on them may degrade.
>
> The internal, non-PII markers for the client-side session-refresh optimization (`DSLI` / `DSLI_DISABLED`) are the exception: the SDK always keeps them in real `window.localStorage`, independent of `customStorage`. This is what makes the optimization behave correctly even when you back the other keys with `sessionStorage` or an in-memory store.
>
> The same goes for the web component's SSO login entries (`dls_sso_run_*`), which let a page opened from a magic link recover the login after a refresh. They hold no personal data (no login hint or username), and they stay in real `window.localStorage` so that expired ones can be removed, which a `customStorage` without key listing cannot support. Each is kept for up to 10 minutes, or up to a day for an OIDC login that carries the app's error redirect, and is removed earlier when an OIDC login redirects back to the app.

### Last User Persistence

Descope stores the last user information in local storage. If you wish to disable this feature, you can pass `storeLastAuthenticatedUser={false}` to the `AuthProvider` component. Please note that some features related to the last authenticated user may not function as expected if this behavior is disabled. Local storage is being cleared when the user logs out, if you want the avoid clearing the local storage, you can pass `keepLastAuthenticatedUserAfterLogout={true}` to the `AuthProvider` component.

The last-user key also serves as a signal for the SDK's session initialization optimization: on mount, the `AuthProvider` skips the initial `/try-refresh` network call when it finds no prior session indicator — neither the `DSLI` key (written to real `window.localStorage` on every successful authentication, independent of `customStorage`) nor the last-user key. This means anonymous visitors never pay a round-trip at startup. If `storeLastAuthenticatedUser={false}`, only the `DSLI` key is used as the indicator.

### Seamless Session Migration

If you are migrating from an external authentication provider to Descope, you can use the `getExternalToken` prop in the `AuthProvider` component. This function should return a valid token from the external provider. The SDK will then use this token to authenticate the user with Descope.

```js
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
  const externalToken = useCallback(async () => {
    // Bring token from external provider (e.g. get access token from another auth provider)
    return 'my-external-token';
  }, []);

  return (
    <AuthProvider projectId="my-project-id" getExternalToken={externalToken}>
      <App />
    </AuthProvider>
  );
};
```

### Widgets

Widgets are components that allow you to expose management features for tenant-based implementation. In certain scenarios, your customers may require the capability to perform managerial actions independently, alleviating the necessity to contact you. Widgets serve as a feature enabling you to delegate these capabilities to your customers in a modular manner.

Important Note:

- For the user to be able to use the widget, they need to be assigned the `Tenant Admin` Role.

All widget components accept an optional `locale` prop. It can be any supported locale the widget's screens are translated to; if not provided, the locale is taken from the browser's locale.

```jsx
<UserManagement widgetId="user-management-widget" tenant="tenant-id" locale="en" />
```

#### User Management

The `UserManagement` widget lets you embed a user table in your site to view and take action.

The widget lets you:

- Create a new user
- Edit an existing user
- Activate / disable an existing user
- Reset an existing user's password
- Remove an existing user's passkey
- Delete an existing user

Note:

- Custom fields also appear in the table.

###### Usage

```js
import { UserManagement } from '@descope/react-sdk';
...
  <UserManagement
    widgetId="user-management-widget"
    tenant="tenant-id"
  />
```

Example:
[Manage Users](./examples/app/ManageUsers.tsx)

#### Role Management

The `RoleManagement` widget lets you embed a role table in your site to view and take action.

The widget lets you:

- Create a new role
- Change an existing role's fields
- Delete an existing role

Note:

- The `Editable` field is determined by the user's access to the role - meaning that project-level roles are not editable by tenant level users.
- You need to pre-define the permissions that the user can use, which are not editable in the widget.

###### Usage

```js
import { RoleManagement } from '@descope/react-sdk';
...
  <RoleManagement
    widgetId="role-management-widget"
    tenant="tenant-id"
  />
```

Example:
[Manage Roles](./examples/app/ManageRoles.tsx)

#### Access Key Management

The `AccessKeyManagement` widget lets you embed an access key table in your site to view and take action.

The widget lets you:

- Create a new access key
- Activate / deactivate an existing access key
- Delete an exising access key

###### Usage

```js
import { AccessKeyManagement } from '@descope/react-sdk';
...
  {
	  /* admin view: manage all tenant users' access keys */
  }
  <AccessKeyManagement
    widgetId="access-key-management-widget"
    tenant="tenant-id"
  />

  {
    /* user view: mange access key for the logged-in tenant's user */
  }
  <AccessKeyManagement
    widgetId="user-access-key-management-widget"
    tenant="tenant-id"
  />
```

Example:
[Manage Access Keys](./examples/app/ManageAccessKeys.tsx)

#### Audit Management

The `AuditManagement` widget lets you embed an audit table in your site.

###### Usage

```js
import { AuditManagement } from '@descope/react-sdk';
...
  <AuditManagement
    widgetId="audit-management-widget"
    tenant="tenant-id"
  />
```

Example:
[Manage Audit](./examples/app/ManageAudit.tsx)

#### User Profile

The `UserProfile` widget lets you embed a user profile component in your app and let the logged in user update his profile.

The widget lets you:

- Update user profile picture
- Update user personal information
- Update authentication methods
- Logout

###### Usage

```js
import { UserProfile } from '@descope/react-sdk';
...
  <UserProfile
    widgetId="user-profile-widget"
    onLogout={() => {
      // add here you own logout callback
      window.location.href = '/login';
    }}
  />
```

Example:
[User Profile](./examples/app/MyUserProfile.tsx)

#### Applications Portal

The `ApplicationsPortal` lets you embed an applications portal component in your app and allows the logged-in user to open applications they are assigned to.

###### Usage

```js
import { ApplicationsPortal } from '@descope/react-sdk';
...
  <ApplicationsPortal
    widgetId="applications-portal-widget"
  />
```

Example:
[Applications Portal](./examples/app/MyApplicationsPortal.tsx)

## Code Example

You can find an example react app in the [examples folder](./examples), and a
Preact one in [examples/preact-app](./examples/preact-app) (see
[Preact Support](#preact-support)).

### Setup

To run the examples, set your `Project ID` by setting the `DESCOPE_PROJECT_ID` env var or directly
in the sample code.
Find your Project ID in the [Descope console](https://app.descope.com/settings/project).

```bash
export DESCOPE_PROJECT_ID=<Project-ID>
```

Alternatively, put the environment variable in `.env` file in the project root directory.
See the `.env.example` file for a reference.

### Run Example

Note: Due to an issue with react-sdk tsconfig, you need to remove `"examples"` from the `exclude` field in the `tsconfig.json` file in the root of the project before running the example.

Run the following command in the root of the project to build and run the example:

```bash
npm i && npm start
```

### Example Optional Env Variables

See the following table for customization environment variables for the example app:

| Env Variable                | Description                                                                                                   | Default value                    |
| --------------------------- | ------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| DESCOPE_FLOW_ID             | Which flow ID to use in the login page                                                                        | **sign-up-or-in**                |
| DESCOPE_BASE_URL            | Custom Descope base URL                                                                                       | None                             |
| DESCOPE_BASE_STATIC_URL     | Allows to override the base URL that is used to fetch static files                                            | https://static.descope.com/pages |
| DESCOPE_THEME               | Flow theme                                                                                                    | None                             |
| DESCOPE_LOCALE              | Flow locale                                                                                                   | Browser's locale                 |
| DESCOPE_REDIRECT_URL        | Flow redirect URL for OAuth/SSO/Magic Link/Enchanted Link                                                     | None                             |
| DESCOPE_TENANT_ID           | Flow tenant ID for SSO/SAML                                                                                   | None                             |
| DESCOPE_DEBUG_MODE          | **"true"** - Enable debugger</br>**"false"** - Disable flow debugger                                          | None                             |
| DESCOPE_STEP_UP_FLOW_ID     | Step up flow ID to show to logged in user (via button). e.g. "step-up". Button will be hidden if not provided | None                             |
| DESCOPE_TELEMETRY_KEY       | **String** - Telemetry public key provided by Descope Inc                                                     | None                             |
|                             |                                                                                                               |                                  |
| DESCOPE_OIDC_ENABLED        | **"true"** - Use OIDC login                                                                                   | None                             |
| DESCOPE_OIDC_APPLICATION_ID | Descope OIDC Application ID, In case OIDC login is used                                                       | None                             |

## Preact Support

The SDK runs unmodified on Preact 10.11+ through `preact/compat` - the same
package, the same API, no Preact-specific entry point. Its test suite is
executed twice in CI: once against React and once with `react` aliased to
`preact/compat` (`npm run test:preact`), so hooks, `<Descope />`, and the
widgets are covered under both.

### Setup

Alias `react` and `react-dom` to `preact/compat` in your bundler. Most Preact
setups already do this:

```js
// vite.config.js
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';

export default defineConfig({
  plugins: [preact()], // aliases react/react-dom -> preact/compat
});
```

```js
// webpack.config.js
module.exports = {
  resolve: {
    alias: {
      react: 'preact/compat',
      'react-dom': 'preact/compat',
      'react-dom/test-utils': 'preact/compat/test-utils',
      'react/jsx-runtime': 'preact/compat/jsx-runtime',
    },
  },
};
```

The SDK declares `react` as a peer dependency. Point it at `preact/compat` so
installs stay quiet without pulling React in:

```json
{
  "dependencies": {
    "react": "npm:@preact/compat",
    "react-dom": "npm:@preact/compat"
  }
}
```

For TypeScript, map the types as well - the SDK's declarations reference
`React.FC`, `React.Ref` and `DOMAttributes`:

```json
{
  "compilerOptions": {
    "paths": {
      "react": ["./node_modules/preact/compat/"],
      "react-dom": ["./node_modules/preact/compat/"]
    }
  }
}
```

Then use the SDK exactly as documented above:

```jsx
import { render } from 'preact';
import { AuthProvider, Descope, useSession } from '@descope/react-sdk';

render(
  <AuthProvider projectId="my-project-id">
    <App />
  </AuthProvider>,
  document.getElementById('root'),
);
```

A complete working app is in [examples/preact-app](./examples/preact-app) -
run it with `npm run start:preact`.

### Behavioural differences to be aware of

Two things differ from React. Neither blocks any SDK feature, but both can
surface in tests or on the server:

1. **Effects run after paint.** Preact schedules `useEffect` on the next
   frame, while React flushes it before the browser paints. `<Descope />`
   attaches its `success` / `error` / `ready` listeners from an effect, so an
   event dispatched in the same tick as mount can be missed. Real flows emit
   these events long after mount, so this only tends to matter in tests - wait
   for the listener rather than assuming it is attached:

   ```js
   await waitFor(() => {
     fireEvent(container.querySelector('descope-wc'), new CustomEvent('error'));
     expect(document.querySelector('.error')).not.toBeNull();
   });
   ```

2. **SSR needs the async renderer.** `<Descope />` and the widgets lazy-load
   their web component, so the first server render suspends.
   `preact-render-to-string`'s synchronous `renderToString` throws on a
   suspended subtree instead of emitting the `<Suspense>` fallback - use
   `renderToStringAsync` (v6+):

   ```js
   import { renderToStringAsync } from 'preact-render-to-string';

   const html = await renderToStringAsync(<App />);
   ```

If you would rather not pull in a compat layer at all,
[`@descope/web-component`](https://www.npmjs.com/package/@descope/web-component)
is a framework-agnostic custom element - but it does not provide the
`useSession` / `useUser` / `useDescope` hooks or the `AuthProvider` session
management this SDK adds.

## Performance / Bundle Size

To improve modularity and reduce bundle size, all flow-related utilities are available also under `@descope/react-sdk/flows` subpath. Example:

```
import { Descope, useSession, ... } from '@descope/react-sdk/flows';
```

## FAQ

### I updated the user in my backend, but the user / session token are not updated in the frontend

The Descope SDK caches the user and session token in the frontend. If you update the user in your backend (using Descope Management SDK/API for example), you can call `me` / `refresh` from `useDescope` hook to refresh the user and session token. Example:

```js
const sdk = useDescope();

const handleUpdateUser = useCallback(() => {
  myBackendUpdateUser().then(() => {
    sdk.me();
    // or
    sdk.refresh();
  });
}, [sdk]);
```

## Learn More

To learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).

## OIDC Login

Descope also supports OIDC login. To enable OIDC login, pass `oidcConfig` prop to the `AuthProvider` component. Example:

### AuthProvider setup with OIDC

```js
import { AuthProvider } from '@descope/react-sdk';

const AppRoot = () => {
  return (
    <AuthProvider
      projectId="my-project-id" // also serves as the client ID
      oidcConfig={true}

      /* alternatively, you can pass the oidcConfig object
      oidcConfig={{
        applicationId: 'my-application-id', // optional, if not provided, the default OIDC application will be used
          
        redirectUri: 'https://my-app.com/redirect', // optional, if not provided, the default redirect URI will be used
        
        
        scope: 'openid profile email', // optional, if not provided, default is openid email offline_access roles descope.custom_claims
      }}
      */
    >
      <App />
    </AuthProvider>
  );
};
```

#### Using Inbound Apps as OIDC Provider

To use an inbound app as an OIDC provider, you must provide both the `issuer` and `clientId` configuration options. The `issuer` is the OIDC authority URL, and the `clientId` is the client ID for your inbound app.

> **Note:** When configuring an inbound app as an OIDC provider, you must obtain the issuer URL directly from the inbound app settings page in the Descope console. The issuer URL is specific to your inbound app configuration and cannot be constructed manually. In addition, you'll need to provide the client ID from the same inbound app settings.

```js
<AuthProvider
  projectId="my-project-id"
  oidcConfig={{
    // Required: Get this from your inbound app settings page
    issuer: 'https://api.descope.com/v1/apps/<Project ID>',
    // Required: Client ID from your inbound app settings
    clientId: 'your-inbound-app-client-id',
    // Optional: Custom redirect URI (defaults to current URL)
    redirectUri: 'https://my-app.com/redirect',
    // Optional: Custom scope (defaults to 'openid' when issuer is provided)
    scope: 'openid profile email',
  }}
>
  <App />
</AuthProvider>
```

When using a custom `issuer` (including inbound apps), the default scope is `'openid'` instead of the full Descope scope. You can override this by providing a custom `scope` value.

### Login

Use the `oidc.loginWithRedirect` method from the `useDescope` hook to trigger the OIDC login. Example:

```js
const MyComponent = () => {
  const sdk = useDescope();

  return (
    // ...
    <button
      onClick={() => {
        sdk.oidc.loginWithRedirect({
          // By default, the login will redirect the user to the current URL
          // If you want to redirect the user to a different URL, you can specify it here
          redirect_uri: window.location.origin,
        });
      }}
    >
      Login with OIDC
    </button>
  );
};
```

### Redirect back from OIDC provider

The `AuthProvider` will automatically handle the redirect back from the OIDC provider. The user will be redirected to the `redirect_uri` specified in the `oidc.login` method.

### Logout

You can call `sdk.logout` to logout the user. Example:

```js
const MyComponent = () => {
  const sdk = useDescope();

  return (
    // ...
    <button
      onClick={() => {
        sdk.logout();
      }}
    >
      Logout
    </button>
  );
};
```

If you want to redirect the user to a different URL after logout, you can use `oidc.logout` method. Example:

```js
const MyComponent = () => {
  const sdk = useDescope();

  return (
    // ...
    <button
      onClick={() => {
        sdk.oidc.logout({
          // by default, the logout will redirect the user to the current URL
          // if you want to redirect the user to a different URL, you can specify it here
          post_logout_redirect_uri: window.location.origin + '/after-logout',
        });
      }}
    >
      Logout
    </button>
  );
};
```

## Contact Us

If you need help you can email [Descope Support](mailto:support@descope.com)

## License

The Descope SDK for React is licensed for use under the terms and conditions of the [MIT license Agreement](./LICENSE).
