Client SDK Auth Helpers

The Auth class is a crucial component of the Descope SDK, handling key user authentication operations. This class is designed to execute essential functions such as fetching user details, fetching and refreshing sessions, and logging out users.

Client SDK

Install SDK

Terminal
npm i --save @descope/react-sdk

Import and initialize SDK

Parameters:

  • baseUrl: Custom domain that must be configured to manage token response in cookies. This makes sure every request to our service is through your custom domain, preventing accidental domain blockages.
  • baseStaticUrl: Custom domain to override the base URL that is used to fetch static files.
  • persistTokens: Controls whether session tokens are stored in browser localStorage. Enabled by default and accessible via getToken(). Set to false to avoid client-side storage of tokens to reduce XSS risk.
  • sessionTokenViaCookie: Controls whether the session token is stored in a cookie instead of localStorage. If persistTokens is true, then by default, the token is stored in localStorage. Set this to true to store the token in a JS cookie instead.
  • storeLastAuthenticatedUser: Determines if the last authenticated user's info is saved in localStorage. Enabled by default and accessible via getUser(). Set to false to disable this behavior.
  • keepLastAuthenticatedUserAfterLogout: Controls whether user info is kept after logout. Disabled by default. Set to true to store user data on logout.
import { AuthProvider } from '@descope/react-sdk'
import { Descope, useDescope } from '@descope/react-sdk'
 
const AppRoot = () => {
	return (
      <AuthProvider
          projectId="__ProjectID__"
          baseUrl="https://auth.app.example.com"
          persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
          sessionTokenViaCookie={false} // set to `true` to store the session token in a JS cookie instead of localStorage
          storeLastAuthenticatedUser={true} // set to `false` to disable storing last user
          keepLastAuthenticatedUserAfterLogout={false} // set to `true` to persist user info after logout
        >
        <App />
      </AuthProvider>
	);
};

OIDC Configuration

If you're using our SDK as an OIDC client with our Federated Apps, you can initialize the oidcConfig parameter with the following items:

  • applicationId: This is the application id, that can be found within the settings of your Federated Application
  • redirectUri: This is the url that will be redirected to if the user is unauthenticated. The default redirect URI will be used if not provided.
  • scope: This is a string of the scopes that the OIDC client will request from Descope. This should be one string value with spaces in between each scope. The default scopes are: 'openid email roles descope.custom_claims offline_access'

Manage Session

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 and will not be accessible to the client-side code using these session management functions.

The useSession functions retrieve information about the current user session.

They return the following details:

Objects

  • sessionToken: The JWT for the current session.

Booleans

  • isAuthenticated: Boolean for the authentication state of the current user session.
  • isSessionLoading: Boolean for the loading state of the session. Can be used to display a "loading" message while the session is still loading.

Additional helper functions

  • getSessionToken: The JWT for the current session.
  • getRefreshToken: The refresh JWT for the current session.

Limited to Non-Cookie Storage

The getRefreshMethod function will not work if refresh tokens are stored in httpOnly cookies, as they cannot be accessed from the frontend.

  • isSessionTokenExpired: Boolean for checking if a given session token is expired.
  • isRefreshTokenExpired: Boolean for checking if a refresh token is expired.
  • getJwtRoles: Get current roles from an existing session token. Provide tenant id for specific tenant roles.
  • getJwtPermissions: Get current permissions from an existing session token. Provide tenant id for specific tenant permissions.
  • getCurrentTenant: Get current tenant id from an existing session token (from the dct claim).
import { useSession, getSessionToken, getRefreshToken, isSessionTokenExpired, isRefreshTokenExpired, 
        getJwtRoles, getJwtPermissions, getCurrentTenant } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { isAuthenticated, isSessionLoading, sessionToken } = useSession();
 
  const refreshToken = getRefreshToken();
  const sessionTokenFromFunction = getSessionToken();
 
  const isRefreshTokenExpired = isRefreshTokenExpired(refreshToken);
  const isSessionTokenExpired = isSessionTokenExpired(sessionTokenFromFunction);
 
  const jwtRoles = getJwtRoles(token = sessionToken, tenant = '<tenant-id>');
  const jwtPermissions = getJwtPermissions(token = sessionToken, tenant = '<tenant-id>');
  const currentTenant = getCurrentTenant(token = sessionToken);
 
  if isAuthenticated { 
    return (
      <>
        <p>You are authenticated.</p>
      </>
    );
  }
};

Handling Authentication State Changes

Descope provides event listeners to track session and user state changes dynamically. These functions can be accessed through useDescope().

Event Functions

  • onSessionTokenChange(newSession, oldSession): Triggers when the session token changes.
  • onIsAuthenticatedChange(isAuthenticated): Fires when authentication status changes.
  • onUserChange(newUser, oldUser): Triggers when user data updates.
import { useEffect, useState } from 'react';
import { useDescope } from '@descope/react-sdk';
 
const App = () => {
  const [user, setUser] = useState<User>();
  const [session, setSession] = useState<string>();
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  
  const sdk = useDescope();
 
  useEffect(() => {
    const unsubscribeTokenChange = sdk.onSessionTokenChange(setSession);
    const unsubscribeAuthChange = sdk.onIsAuthenticatedChange(setIsAuthenticated);
    const unsubscribeUserChange = sdk.onUserChange(setUser);
 
    return () => {
      unsubscribeTokenChange();
      unsubscribeAuthChange();
      unsubscribeUserChange();
    };
  }, [sdk]);
 
  return <p>Listening for authentication changes...</p>;
};

Manage User

The useUser and me functions return information about the currently authenticated user. These methods are used when you need to fetch or display user-related data in your application.

These functions returns the following details:

Objects

  • user: object that contains the following user attributes:
    • email: Email address associated to the user.
    • name: Name associated to the user.
    • givenName: Given name associated to the user.
    • middleName: Middle name associated to the user.
    • familyName: Family name associated to the user.
    • phone: Phone number associated to the user.
    • loginIds: An array of loginIds associated to the user.
    • userId: The user's unique Descope generated userId.
    • verifiedEmail: Boolean whether the email address for the user has been verified.
    • verifiedPhone: Boolean whether the phone number for the user has been verified.
    • picture: The base64 encoded image if the user has an image associated to them.
    • roleNames: An array of roles associated to the user.
    • userTenants: An array of tenant names and IDs associated to the user.
    • createTime: The time that the user was created.
    • totp: Boolean whether the user has TOTP login associated with it.
    • saml: Boolean whether the user has SAML login associated with it.
    • oauth: Boolean whether the user has OAuth login associated with it.

Booleans

  • isUserLoading: Boolean for whether the user object is currently loading.

Note

useDescope, useSession, and useUser should be used inside AuthProvider context, and will throw an exception if this requirement is not met

import { useUser } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { user, isUserLoading } = useUser();
  return (
    <>
      <p>Hello {user.name}</p>
    </>
  );
};

Refresh Session

In the case that the browser has a valid refresh token on storage/cookie, the user should get a valid session token (i.e. user should be logged-in). For this reason, it is common to call the refresh function after sdk initialization. Refresh returns a session token, so if autoRefresh is set to true, the sdk will automatically continue to refresh the token.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the refresh operation, as shown in the React and Next.js examples below.

Note

useSession triggers a single request to the Descope backend to attempt to refresh the session. If you don't useSession on 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 the useDescope hook:

import { useSession, useUser, useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
  const { isAuthenticated, isSessionLoading } = useSession();
  const { refresh } = useDescope();
  useEffect(() => {
    refresh();
  }, [refresh]);

Logout

Logs out the currently authenticated user. This method invalidates the user's current JWT tokens and ends their session. This function is typically used when the user chooses to log out of your application.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the logout operation, as shown in the React, Next.js, and Vue examples below.

import { useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
	const { logout } = useDescope();
 
	const handleLogout = useCallback(() => {
		logout();
	}, [logout]);
 
  return (
    <>
      <button onClick={handleLogout}>Logout</button>
    </>
  );
};

Logout All

This will sign the user out of all the devices they are currently signed-in with. Successfully executing this endpoint will invalidate all user's refresh tokens. Response will include all user tokens and fields empty, so client will remove cookies as well.

useDescope is a React hook that retrieves the Descope SDK for further operations related to authentication. This includes the logoutAll operation, as shown in the React, Next.js, and Vue examples below.

import { useDescope } from '@descope/react-sdk';
import { useCallback } from 'react';
 
const App = () => {
	const { logoutAll } = useDescope();
 
	const handleLogout = useCallback(() => {
		logoutAll();
	}, [logoutAll]);
 
  return (
    <>
      <button onClick={handleLogout}>logoutAll</button>
    </>
  );
};
Was this helpful?

On this page