How to Use Organizations With the React SDK and Maintain User Sessions
This article explains how to correctly use Auth0 Organizations with the Auth0 React Software Development Kit (SDK) to ensure that user sessions are maintained after a page refresh. This is achieved by persisting the organization's ID on the client-side and providing it to the Auth0Provider upon initialization.
-
Auth0 React SDK
-
Organizations
-
Silent Authentication
When the page is refreshed, the Auth0Provider loses in-memory context, including the organization ID (org_id). If this value is not re-supplied, the SDK's silent authentication call will fail due to the missing organization parameter, effectively logging the user out.
To maintain the user's session, the application must store the user's org_id after the initial login and provide it to the Auth0Provider every time the application loads.
Method 1: Configuring a single Organization in the React SDK
- In index.js add the
organizationto the parameters in theAuth0Providerpassing in theorg_id - The
org_idis either hardcoded in, sourced from an env/config, or passed from a parent component
<Auth0Provider
domain={config.domain}
clientId={config.clientId}
audience={config.audience}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
organization={org_id}
>
<App />
</Auth0Provider>
Method 2: Configuring multiple organizations
-
The idea behind this strategy is to save the
org_idwhen a user first logs in, save it to localStorage, and then pass it into theAuth0Providerwhen it re-renders. -
In App.js, grab the
org_idof the newly authenticated user and save it to localStorage:
//put this above the return in App.js
if ( user && user.org_id) {
localStorage.setItem('orgId', user.org_id);
}
- in index.js, add a function to get the
org_idand pass it into theAuth0Provider:
const getOrgId = () =>
{
return localStorage.getItem( 'orgId' );
};
ReactDOM.render(
<Auth0Provider
domain={config.domain}
clientId={config.clientId}
audience={config.audience}
redirectUri={window.location.origin}
onRedirectCallback={onRedirectCallback}
organization={getOrgId() === null ? undefined : getOrgId()}
>
<App />
</Auth0Provider>,
document.getElementById("root")
);
Note: Ensure that storing org_id in localStorage aligns with your app’s security and data privacy requirements. While org_id is typically not sensitive on its own, avoid persisting any confidential tokens or user data.