Choose where tokens are stored
Compare the four token stores of the browser SDK, and keep several tabs in step.
What it shows
- The provider takes a store in its
storageprop:sessionStorageAdapter(the default),localStorageAdapterormemoryStorageAdapter, all from@lumoauth/client. - 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.
- The page shows what a script can read from web storage, and the end of the access token that this tab holds.
- With
crossTabon (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.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_CLIENT_ID | The 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.
- React
// 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>,
);
// 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>;
}
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.
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:
| Store | Reload of the tab | A tab opened later | Tabs that were open, with crossTab on | In web storage |
|---|---|---|---|---|
sessionStorageAdapter (default) | Signed in | Signed out | Receive the sign-in, each refresh and the sign-out | The tokens, in the sessionStorage of the tab that signed in |
localStorageAdapter | Signed in | Signed in | Receive the sign-in, each refresh and the sign-out | The tokens, in localStorage |
memoryStorageAdapter | Signed out | Signed out | Receive the sign-in and the sign-out | Nothing |
httpOnly cookie, with @lumoauth/nextjs | Signed in | Signed in | Each page load reads the session from the server | Nothing |
- With
crossTaboff 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
crossTabon, 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. cookieStorageAdapterneeds a server on the same origin with a session route and a logout route. Among the published packages, the route handler of@lumoauth/nextjsprovides both.@lumoauth/expresshas no session route.AuthCallbackopens 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
sessionStoragewith every store.