Session Management
Handle auth state, logout, token refresh, multi-tab sync, and cleanup
Session Management
The DOM Package stores customer session tokens, refreshes them automatically, and keeps authentication state synchronized across browser tabs.
Listening for Auth State Changes
Register a callback to be notified when the authentication state changes. This fires on login, logout, token refresh, and session updates from other tabs.
const unsubscribe = auth.onAuthStateChange((event) => {
if (event.type === 'LOGIN') {
console.log('Customer signed in');
} else if (event.type === 'LOGOUT') {
console.log('Customer signed out');
}
});
// Later, to stop listening:
unsubscribe();Logging Out
await auth.logout();This revokes the session on the server, clears stored tokens from localStorage, and broadcasts the logout event to other tabs so they can update their UI.
Token Management
The SDK manages tokens automatically:
- Storage: Access and refresh tokens are stored in
localStorage - Automatic refresh: The SDK refreshes the access token 5 minutes before it expires, using the Refresh Token endpoint
- Token rotation: Each refresh rotates both the access and refresh tokens
- Multi-tab sync: Login, logout, and token refresh events are broadcast to all open tabs via the
BroadcastChannelAPI
You generally do not need to manage tokens yourself. If you need direct access to the current access token, for example to pass it to a custom API call, the SDK provides it through the internal state.
Multi-Tab Synchronization
When enableTabSync is set to true by default, the SDK uses the BroadcastChannel API to keep all tabs in sync. The following events are broadcast:
| Event | Description |
|---|---|
LOGIN | A customer signed in on another tab |
LOGOUT | A customer signed out on another tab |
SESSION_UPDATE | Session data was updated |
TOKEN_REFRESH | Tokens were refreshed on another tab |
This means if a customer signs in on one tab, all other tabs automatically pick up the session without the customer needing to refresh the page.
Cleanup
When you are done with the SDK instance, for example on a single-page app route change, call destroy() to clean up event listeners and the BroadcastChannel:
auth.destroy();