Session Management
Overview
Section titled “Overview”After a user authenticates (via Passkey, Email Code, Social Login, or OAuth), the SDK creates a session. The auth.session namespace provides methods to query, validate, refresh, and manage that session.
Getting the Current Session
Section titled “Getting the Current Session”Retrieve the current session and user data:
const { data, error } = await auth.session.get();
if (error) { console.error('Session error:', error.message); return;}
if (data === null) { console.log('Not authenticated'); return;}
console.log('User:', data.user);console.log('Session:', data.session);Response Types
Section titled “Response Types”interface AuthSessionData { session?: Session; user?: User;}
interface Session { id: string; userId: string; createdAt: string; expiresAt: string;}
interface User { id: string; // or sub email?: string; name?: string; nickname?: string; emailVerified?: boolean; // ...additional claims}Checking Authentication Status
Section titled “Checking Authentication Status”A token-aware check that verifies the current token-backed session:
const isLoggedIn = await auth.session.isAuthenticated();
if (isLoggedIn) { // Show authenticated UI} else { // Show login button}This first checks for stored token material, then calls session.get() to confirm the session with the server. For UI that already needs user data, call session.get() directly.
Getting User Information
Section titled “Getting User Information”Fetch the current user’s profile:
const user = await auth.session.getUser();
if (user) { console.log('Email:', user.email); console.log('Name:', user.name); console.log('Verified:', user.emailVerified);} else { console.log('Not authenticated');}Validating the Session
Section titled “Validating the Session”Check if the current session is still valid on the server:
const isValid = await auth.session.validate();
if (!isValid) { // Session expired or revoked — redirect to login window.location.href = '/login';}validate() makes a server call, so use it when you need to confirm session validity (e.g., before a sensitive operation). For routine checks, isAuthenticated() is sufficient.
Refreshing the Session
Section titled “Refreshing the Session”Clear the cached session and fetch a fresh session from the server:
const session = await auth.session.refresh();
if (session) { console.log('Fresh session loaded. Expiry:', session.expiresAt);} else { console.log('No active session');}auth.session.refresh() does not perform an OAuth refresh_token grant by itself. Browser-token access-token refresh is used internally by auth.fetch() when a replay-safe request receives a 401 and a refresh token is available.
Clearing the Cache
Section titled “Clearing the Cache”The SDK caches session and user data in memory. Clear the cache to force a fresh fetch:
auth.session.clearCache();
// Next call to get() or isAuthenticated() will hit the serverconst { data } = await auth.session.get();Signing Out
Section titled “Signing Out”End the user’s session:
await auth.signOut();This calls the Authrim server’s logout endpoint and clears local session state. The auth:logout event is emitted after sign-out completes.
Sign Out Options
Section titled “Sign Out Options”interface SignOutOptions { /** Redirect after logout (RP-initiated logout) */ redirectUri?: string; /** Ask Authrim to revoke token material */ revokeTokens?: boolean; /** Logout current app, application group, or all sessions */ logoutScope?: 'local' | 'group' | 'global';}
// Redirect to a specific page after logoutawait auth.signOut({ redirectUri: 'https://myapp.com/goodbye', revokeTokens: true,});For broader logout scopes, use the convenience helpers:
await auth.signOutApplicationGroup();await auth.signOutAll({ revokeTokens: true });Page Load Pattern
Section titled “Page Load Pattern”A common pattern for page initialization:
const auth = await createAuthrim({ issuer: 'https://auth.example.com', clientId: 'my-app',});
async function initPage() { const { data } = await auth.session.get();
if (!data) { // Not authenticated — show login UI showLoginButton(); return; }
// Authenticated — show user content showUserDashboard(data.user, data.session);}
initPage();Protected Page Pattern
Section titled “Protected Page Pattern”Redirect unauthenticated users to login:
async function requireAuth() { const isLoggedIn = await auth.session.isAuthenticated();
if (!isLoggedIn) { window.location.href = '/login'; return null; }
const { data } = await auth.session.get(); return data;}
// Use in your pageconst sessionData = await requireAuth();if (!sessionData) return; // Redirect happening
// Proceed with authenticated logicshowProfile(sessionData.user);Next Steps
Section titled “Next Steps”- Session Monitoring — Real-time session status monitoring
- Events — Listen for session changes and auth events
- Sign Out & Logout — Session termination options
- Error Handling — Handle session errors gracefully