How to Use Organizations With the React SDK and Maintain User Sessions

Overview

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.

Applies To
  • Auth0 React SDK

  • Organizations

  • Silent Authentication

Cause

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.

Solution

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 organization to the parameters in the Auth0Provider passing in the org_id
  • The org_id is 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_id when a user first logs in, save it to localStorage, and then pass it into the Auth0Provider when it re-renders.

  • In App.js, grab the org_id of 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_id and pass it into the Auth0Provider:
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.

Related References

Recommended content

No recommended content found...