React & Node.js Quickstart
This is a quickstart guide to help you integrate Descope with your React & Node.js application. Follow the steps below to get started.
Install React SDK
Install the SDK with the following command:
npm i --save @descope/react-sdkyarn add @descope/react-sdkpnpm add @descope/react-sdkbun i @descope/react-sdkImport and Wrap Application with AuthProvider
Wrap the entire application with <AuthProvider />. You need your Project ID for this step, which you can find on the project page of your Descope console.
Note
You can also add the optional baseUrl parameter if you're utilizing a custom domain within your Descope project (ex: https://auth.company.com).
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider } from '@descope/react-sdk';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<AuthProvider projectId='__ProjectID__'>
<App />
</AuthProvider>
</React.StrictMode>
);Optional Client Auth Settings
You can customize client-side token behavior using optional parameters like persistTokens, and sessionTokenViaCookie. Learn more in the Auth Helpers documentation.
Import Descope Functions and Add Flows Component
To trigger the Descope Flow, you will need to add this component. The screens you've customized in your Flow will appear here. You can also customize the component with the following:
flowId: ID of the flow you wish to useonSuccessandonError: functions that execute when authentication succeeds or fails
Note
For the full list of component customization options, refer to our Descope Components Doc.
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
const App = () => {
return (
<Descope
flowId="sign-up-or-in"
onSuccess={(e) => console.log(e.detail.user)}
onError={(e) => console.log('Could not log in!')}
/>
);
};Utilize the React SDK Hooks and Functions
Descope provides many different hooks to check if the user is authenticated, session is loading etc. You can use these to customize the user experience:
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.useUser: Returns information about the currently authenticated user.sessionToken: The JWT for the current session.
Note
For the full list of available hooks and functions, refer to the Auth Helpers Doc.
import { useCallback } from 'react'
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
const App = () => {
const { isAuthenticated, isSessionLoading } = useSession()
const { user, isUserLoading } = useUser()
const exampleFetchCall = async () => {
const sessionToken = getSessionToken();
// Example Fetch Call with HTTP Authentication Header
fetch('your_application_server_url', {
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + sessionToken,
}
})
}
return <>
{!isAuthenticated &&
(
<Descope
flowId="sign-up-or-in"
onSuccess={(e) => console.log(e.detail.user)}
onError={(e) => console.log('Could not log in!')}
/>
)
}
{
(isSessionLoading || isUserLoading) && <p>Loading...</p>
}
{!isUserLoading && isAuthenticated &&
(
<>
<p>Hello {user.name}</p>
<div>My Private Component</div>
</>
)
}
</>;
}
export default App;Add Logout Functionality
You can use the React useCallback hook to create your logout function.
useDescope(): Returns further operations related to authentication including logout.
import { useCallback } from 'react'
import { useDescope, useSession, useUser } from '@descope/react-sdk'
import { Descope } from '@descope/react-sdk'
import { getSessionToken } from '@descope/react-sdk';
const App = () => {
const { isAuthenticated, isSessionLoading } = useSession()
const { user, isUserLoading } = useUser()
const { logout } = useDescope()
const exampleFetchCall = async () => {
const sessionToken = getSessionToken();
// example fetch call with authentication header
fetch('your_application_server_url', {
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + sessionToken,
}
})
}
const handleLogout = useCallback(() => {
logout()
}, [logout])
return <>
{!isAuthenticated &&
(
<Descope
flowId="sign-up-or-in"
onSuccess={(e) => console.log(e.detail.user)}
onError={(e) => console.log('Could not log in!')}
/>
)
}
{
(isSessionLoading || isUserLoading) && <p>Loading...</p>
}
{!isUserLoading && isAuthenticated &&
(
<>
<p>Hello {user.name}</p>
<div>My Private Component</div>
<button onClick={handleLogout}>Logout</button>
</>
)
}
</>;
}
export default App;At this point, you're done with the frontend. If you would like to also handle Session Management in your backend, keep on reading!
Install Backend SDK
Install the SDK with the following command:
npm i --save @descope/node-sdkyarn add @descope/node-sdkpnpm add @descope/node-sdkbun i @descope/node-sdkImport and Setup Backend SDK
You'll need import and setup all of the packages from the SDK.
If you're using a custom domain with your Descope project, make sure to include baseUrl in the parameters (e.g. {baseUrl : 'https://api.descope.com'}) when you initialize DescopeClient.
import DescopeClient from '@descope/node-sdk';
try {
const descopeClient = DescopeClient({ projectId: '__ProjectID__' });
} catch (error) {
console.log("failed to initialize: " + error)
}Implement Session Validation
The frontend SDK will store the session token in either a cookie or your browser's local storage. If using a cookie, the token will be sent to your app server automatically with every request.
You will need to then fetch the session token from the Authorization header of each request, and use the SDK to validate the token.
Note
You can optionally validate the aud claim by passing an audience parameter. This ensures the token was issued for your specific application and prevents token reuse across different applications. The audience parameter accepts either a string or an array of strings.
// Fetch session token from HTTP Authorization Header
const sessionToken = "xxxx";
try {
// Basic validation without audience checking
const authInfo = await descopeClient.validateSession(sessionToken);
// Or validate with a single audience (string)
const authInfoWithAudience = await descopeClient.validateSession(sessionToken, {
audience: '__ProjectID__'
});
// Or validate with multiple audiences (array)
const authInfoWithMultipleAudiences = await descopeClient.validateSession(sessionToken, {
audience: ['__ProjectID__', 'my-custom-audience']
});
console.log("Successfully validated user session:");
console.log(authInfo);
} catch (error) {
console.log("Could not validate user session " + error);
}Congratulations
Now that you've got the authentication down, go focus on building out the rest of your app!
Checkpoint
Your application is now integrated with Descope. Please test with sign-up or sign-in use case.
Customize
Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.