Skip to main content

Choose where tokens are stored

Compare the four token stores of the browser SDK, and keep several tabs in step.

RecipeReadyView source
Works with
JavaScript / TypeScriptReact

What it shows​

  1. The provider takes a store in its storage prop: sessionStorageAdapter (the default), localStorageAdapter or memoryStorageAdapter, all from @lumoauth/client.
  2. The app signs in through the hosted page. The provider exchanges the code on the page itself, without a reload, so the memory store keeps the tokens.
  3. The page shows what a script can read from web storage, and the end of the access token that this tab holds.
  4. With crossTab on (the default), a sign-in, a refresh and a sign-out in one tab reach the other open tabs. One tab refreshes, and the others receive the new token.

The fourth store keeps the tokens in an httpOnly cookie on your server. The recipe Next.js server session shows it, and the table below compares it.

Before you start​

You need an application for a browser app: a public client with a redirect URI and an allowed origin. The Starter App of a new organization accepts http://localhost:5173/auth/callback. Open Applications in the portal and copy its client ID. To create an application of your own, follow the steps of Sign in through the hosted page.

VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_CLIENT_IDThe client ID of a browser application, for example the Starter App. A browser app has no client secret.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. A browser ran each store with three tabs: the tab that signed in, a tab that was open before, and a tab opened later. The table under the output shows what happened in each.

sign-in/token-storage/js/src/main.jsx
// Choose where the browser SDK keeps the tokens, and whether the tabs of the
// app share one session.
//
// cd sign-in/token-storage/js && npm install && npm run dev
//
// Then open http://localhost:5173 in two tabs.
import { createRoot } from 'react-dom/client';
import { LumoAuthProvider } from '@lumoauth/react';
import { localStorageAdapter, memoryStorageAdapter, sessionStorageAdapter } from '@lumoauth/client';
import App from './App.jsx';

// The three stores that need no server of your own.
const stores = {
sessionStorage: sessionStorageAdapter,
localStorage: localStorageAdapter,
memory: memoryStorageAdapter,
};

// The choice is a setting of this demo, not of the SDK. It is kept under its
// own key, so that every tab of the app uses the same store.
const saved = JSON.parse(localStorage.getItem('demo-token-store') ?? '{}');
const choice = { store: stores[saved.store] ? saved.store : 'sessionStorage', crossTab: saved.crossTab ?? true };
const change = (next) => {
localStorage.setItem('demo-token-store', JSON.stringify({ ...choice, ...next }));
window.location.reload();
};

createRoot(document.getElementById('root')).render(
<LumoAuthProvider
domain={import.meta.env.LUMOAUTH_URL}
orgId={import.meta.env.LUMOAUTH_ORG_ID}
clientId={import.meta.env.LUMOAUTH_CLIENT_ID}
redirectUri={window.location.origin + '/auth/callback'}
// Where the tokens are kept. The default is sessionStorage.
storage={stores[choice.store]()}
// With crossTab on (the default), a sign-in, a refresh or a sign-out in
// one tab reaches the other open tabs, and only one tab refreshes at a time.
crossTab={choice.crossTab}
>
{/* The app renders on the callback path too. The provider exchanges the
code on any page, without a reload, so the memory store keeps the
tokens. AuthCallback would reload the page and empty that store. */}
<App choice={choice} onChange={change} />
</LumoAuthProvider>,
);
sign-in/token-storage/js/src/App.jsx
// One page: the choice of store, the session, and what a script on the page
// can read from web storage.
import { useEffect, useState } from 'react';
import { SignedIn, SignedOut, SignInButton, SignOutButton, useLumoAuth, useSession, useUser } from '@lumoauth/react';

export default function App({ choice, onChange }) {
return (
<main>
<h1>Choose where tokens are stored</h1>
<p>
<label>
Tokens kept in{' '}
<select value={choice.store} onChange={(e) => onChange({ store: e.target.value })}>
<option value="sessionStorage">sessionStorage</option>
<option value="localStorage">localStorage</option>
<option value="memory">memory</option>
</select>
</label>{' '}
<label>
<input type="checkbox" checked={choice.crossTab} onChange={(e) => onChange({ crossTab: e.target.checked })} />
Share the session between tabs (crossTab)
</label>
</p>
<SignedOut>
<p>Nobody is signed in.</p>
<SignInButton />
</SignedOut>
<SignedIn>
<Session />
</SignedIn>
<WebStorage />
</main>
);
}

function Session() {
const user = useUser();
const { getToken } = useSession();
const client = useLumoAuth();
const [tail, setTail] = useState('');
const [answer, setAnswer] = useState('');

useEffect(() => {
// getToken() returns the access token of this tab, renewed first when it
// is about to expire. The end of it shows when another tab renewed it.
const timer = setInterval(async () => setTail((await getToken())?.slice(-6) ?? ''), 1000);
return () => clearInterval(timer);
}, [getToken]);

async function callApi() {
const info = await client.auth.getUserInfo(await getToken());
setAnswer(`UserInfo answered for ${info.email}`);
}

return (
<>
<p>Signed in as {user?.email ?? '…'}</p>
<p>Access token: …{tail}</p>
<button type="button" onClick={callApi}>Call the API</button> <SignOutButton />
<p>{answer}</p>
</>
);
}

// What any script on this origin can read, an injected one included.
function WebStorage() {
const [found, setFound] = useState('');
useEffect(() => {
const read = () => {
const has = (store) => (store.getItem('lumoauth_tokens') ? 'the tokens' : 'nothing');
setFound(`sessionStorage: ${has(sessionStorage)} · localStorage: ${has(localStorage)}`);
};
read();
const timer = setInterval(read, 1000);
return () => clearInterval(timer);
}, []);
return <p>In web storage: {found}</p>;
}
sign-in/token-storage/js/vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// The browser gets these three values and nothing else from the environment.
// None of them is a secret: a browser app has no client secret and no API key.
export default defineConfig({
plugins: [react()],
define: {
'import.meta.env.LUMOAUTH_URL': JSON.stringify(process.env.LUMOAUTH_URL ?? 'https://app.lumoauth.dev'),
'import.meta.env.LUMOAUTH_ORG_ID': JSON.stringify(process.env.LUMOAUTH_ORG_ID ?? ''),
'import.meta.env.LUMOAUTH_CLIENT_ID': JSON.stringify(process.env.LUMOAUTH_CLIENT_ID ?? ''),
},
});
cd sign-in/token-storage/js && npm install && npm run dev

Open http://localhost:5173 in two tabs.

Check the result​

Open http://localhost:5173 in two tabs. Choose a store in the first tab, which then reloads, and reload the second tab too. Sign in in the first tab, and watch the second one.

Output
Tokens kept in [memory] [x] Share the session between tabs (crossTab)
Signed in as maya.chen@example.com
Access token: …N2lwxg
UserInfo answered for maya.chen@example.com
In web storage: sessionStorage: nothing · localStorage: nothing

What each store kept, in the run of this recipe:

StoreReload of the tabA tab opened laterTabs that were open, with crossTab onIn web storage
sessionStorageAdapter (default)Signed inSigned outReceive the sign-in, each refresh and the sign-outThe tokens, in the sessionStorage of the tab that signed in
localStorageAdapterSigned inSigned inReceive the sign-in, each refresh and the sign-outThe tokens, in localStorage
memoryStorageAdapterSigned outSigned outReceive the sign-in and the sign-outNothing
httpOnly cookie, with @lumoauth/nextjsSigned inSigned inEach page load reads the session from the serverNothing
  • With crossTab off and the memory store, the second tab stays signed out when the first one signs in.
  • A tab that receives a sign-in keeps the tokens in memory only. With sessionStorageAdapter, it is signed out again after a reload.
  • Call the API sends the access token of the tab to the UserInfo endpoint. Send it to your own API in the same way.

Limits​

  • Any script that runs on your origin can read web storage. With crossTab on, such a script can also receive the tokens: the SDK sends the access token and the refresh token to the other tabs at each sign-in and refresh. The memory store keeps tokens out of web storage, not out of reach of an injected script.
  • Only the cookie store keeps the refresh token away from the page. A script can still fetch the access token and the ID token from the session route of @lumoauth/nextjs (/api/auth/session), as the provider does.
  • cookieStorageAdapter needs a server on the same origin with a session route and a logout route. Among the published packages, the route handler of @lumoauth/nextjs provides both. @lumoauth/express has no session route.
  • AuthCallback opens the next page with a full page load. With the memory store, the tokens would be lost on the way, so this app renders itself on the callback path instead.
  • The store holds the tokens only. During a sign-in, the SDK keeps the PKCE verifier in sessionStorage with every store.