Web Client Sessions
After a user signs in with Descope, your web app holds a session token and refresh token. The Client SDK stores them (typically in memory or a secure cookie) and refreshes the session token when it expires.
Your web app does not validate the session for API authorization — your backend does. The client's job is to:
- Retrieve the session token from the SDK after authentication
- Send it to your application server on each API request (usually as a
Bearertoken) - Manage logout and optional UI checks (expiry, roles for display)
See Session Validation for backend and gateway validation. See Sessions for the session and refresh token model.
If you're building APIs without a Descope backend SDK, you still need to validate every incoming token — see Backend validation.
Client SDK
Install SDK
npm i --save @descope/react-sdkImport and initialize SDK
For more information about the baseUrl, baseStaticUrl, and baseCdnUrl parameters, refer to the Base URL Configuration section.
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.baseCdnUrl: Custom domain to override the base URL used to load external script assets (e.g., SDKs or widgets) dynamically at runtime.persistTokens: Controls whether session tokens are stored in browser localStorage. Enabled by default and accessible viagetToken(). Set tofalseto avoid client-side storage of tokens to reduce XSS risk.autoRefresh: Controls whether the session is automatically refreshed when the token is expired. Enabled by default. Set tofalseto disable automatic refresh of the session.sessionTokenViaCookie: Controls whether the session token is stored in a cookie instead of localStorage. IfpersistTokensis true, then by default, the token is stored in localStorage. Set this totrueto 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 viagetUser(). Set tofalseto disable this behavior.keepLastAuthenticatedUserAfterLogout: Controls whether user info is kept after logout. Disabled by default. Set totrueto store user data on logout.
Note
sessionTokenViaCookie only applies if you're storing the session as a client-side (non HttpOnly) cookie.
When the session token is managed as a backend cookie via project settings, this prop will be ignored.
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"
baseCdnUrl="https://assets.app.example.com" // specify a custom CDN URL for fetching external scripts and resources
persistTokens={true} // set to `false` to disable token storage in browser to prevent XSS
autoRefresh={true} // set to `false` to disable automatic refresh of the session
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 ApplicationredirectUri: 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'
Sending session token to application server
If you are using Client SDK or using Descope Flows, then your application client must send the session token to you application server.
The getSessionToken() function gets the sessionToken from local storage via JS which you can then include in your request.
Note
NextAuth does not use Descope's Client SDK but does use JWTs for session management.
import { getSessionToken } from '@descope/react-sdk';
const sessionToken = getSessionToken();
// example fetch call with authentication header
fetch('your_application_server_url', {
headers: {
Accept: 'application/json',
Authorization: 'Bearer '+ sessionToken,
}
})At any time, your web client should send only the session token to your application server. Your server validates it with the Descope Backend SDK (or an API gateway JWT authorizer) before serving protected data.
Logout using Client SDK
If you are integrating using the Descope Client SDK, then you must use the Client SDK to logout. If you are using Descope Flows with React SDK, refer to the Quick Start for details. If you are Descope Client SDK without flows, then refer to the sample code below for logout.
Note
If you're using NextAuth and Next.js, you'll need to also make sure that you're handling the logout using the federated IdP revocation endpoint. You can see this working in a sample app here.
import DescopeSdk from '@descope/web-js-sdk';
const descopeSdk = Descope({projectId: "__ProjectID__"});
// Logout from the current session
const resp = await descopeSdk.logout();
// Logout from all the sessions
const resp = await descopeSdk.logoutAll();Checking token expiration (UI only)
Your web app can read session expiration in the browser to drive UI — a countdown, a "your session is about to expire" modal, or an early redirect to the login screen. This is a client-side convenience — it does not replace backend validation.
There are two different questions you can answer in the browser:
| What you need | Use |
|---|---|
| Whether a token has already expired | isSessionTokenExpired() / isRefreshTokenExpired() — see Is the token expired |
| When the session expires | The exp and rexp claims returned by useSession() — see Reading the expiration time |
Is the token expired
import { isSessionTokenExpired } from '@descope/react-sdk';
// With no argument, the helper reads the current session token from storage
if (isSessionTokenExpired()) {
console.log('Session token has expired.');
} else {
console.log('Session token is valid.');
}Reading the expiration time
The useSession() hook returns a claims object containing the exp (session token) and rexp (refresh token) expiration timestamps. For the exact data types and payload structure, see Claims returned by the Client SDK.
import { useSession } from '@descope/react-sdk';
const SessionInfo = () => {
const { claims } = useSession();
// `exp` is UNIX epoch seconds — multiply by 1000 for a JavaScript Date
const sessionTokenExpiresAt = claims?.exp ? new Date(claims.exp * 1000) : null;
// `rexp` is an ISO 8601 string — pass it to Date directly
const signOutAt = claims?.rexp ? new Date(claims.rexp) : null;
return (
<ul>
<li>Session token expires at: {sessionTokenExpiresAt?.toLocaleString()}</li>
<li>You will be signed out at: {signOutAt?.toLocaleString()}</li>
</ul>
);
};Warning the user before the session ends
Drive the countdown off rexp, not exp. The SDK refreshes the session token silently in the background, so a countdown built on exp appears to reset every few minutes; rexp is when the user is actually signed out.
import { useEffect, useState } from 'react';
import { useSession } from '@descope/react-sdk';
const WARN_BEFORE_MS = 30 * 60 * 1000; // warn 30 minutes ahead
const SessionTimeoutWarning = () => {
const { claims, isAuthenticated } = useSession();
const [showWarning, setShowWarning] = useState(false);
useEffect(() => {
if (!isAuthenticated || !claims?.rexp) return;
const signOutAt = new Date(claims.rexp).getTime();
// Poll rather than schedule a single timeout: setTimeout cannot span more
// than ~24.8 days, and refresh token timeouts are often longer than that.
const check = () => setShowWarning(signOutAt - Date.now() <= WARN_BEFORE_MS);
check();
const interval = setInterval(check, 30_000);
return () => clearInterval(interval);
}, [claims?.rexp, isAuthenticated]);
if (!showWarning) return null;
return <div role="alert">Your session is about to expire. Save your work.</div>;
};The rexp value is derived from your project's Refresh Token Timeout, and exp from the Session Token Timeout.
Roles and permissions (UI only)
You can read roles and permissions from the session token to drive UI (show/hide menus, etc.). Do not rely on these values for authorization — your backend must validate the token and enforce access on every API request.
import { getSessionToken, getJwtRoles } from '@descope/react-sdk'
const sessionToken = getSessionToken();
const roles = getJwtRoles(sessionToken);
console.log('User roles:', roles);Permissions (UI only)
Permissions can also be read from the session token for display purposes using getJwtPermissions. Enforce permissions on your server, not in the browser.
import { getSessionToken, getJwtPermissions } from '@descope/react-sdk'
const sessionToken = getSessionToken();
const permissions = getJwtPermissions(sessionToken);
console.log('User permissions:', permissions);