Skip to content

Session Monitoring

Overview

For applications that need to react to session changes in real time — such as logging out when the IdP session ends, or synchronizing auth state across browser tabs — @authrim/web provides several monitoring mechanisms.

FeaturePurposeBrowser Support
Tab SyncSynchronize auth state across browser tabsAll modern browsers
Session MonitorPeriodic session validation pollingAll browsers
Front-Channel LogoutReceive logout notifications via iframeLimited (see note)
Check Session IframeDetect IdP session changes via postMessageLimited (see note)

Tab Sync

Tab Sync synchronizes authentication state across browser tabs using the BroadcastChannel API. When a user logs in or out in one tab, all other tabs update their state.

Usage

import { TabSyncManager } from '@authrim/web';
const tabSync = new TabSyncManager({
channelName: 'authrim-sync', // default
onLogin: (payload) => {
console.log('Logged in (from another tab):', payload.user);
// Update UI to show authenticated state
refreshPage();
},
onLogout: () => {
console.log('Logged out (from another tab)');
// Clear UI and show login
window.location.href = '/login';
},
});
// Start listening
tabSync.start();
// Broadcast events (called automatically by SDK when auth state changes)
tabSync.broadcastLogin({ user, session });
tabSync.broadcastLogout();
// Stop listening
tabSync.stop();

How It Works

sequenceDiagram
    participant Tab1 as Tab 1
    participant BC as BroadcastChannel
    participant Tab2 as Tab 2
    participant Tab3 as Tab 3

    Tab1->>BC: broadcastLogin({ user, session })
    BC->>Tab2: onLogin({ user, session })
    BC->>Tab3: onLogin({ user, session })
    Tab2->>Tab2: Update UI
    Tab3->>Tab3: Update UI

Parameters

ParameterTypeDefaultDescription
channelNamestring'authrim-sync'BroadcastChannel name
onLogin(payload) => voidCallback when login detected in another tab
onLogout() => voidCallback when logout detected in another tab

Session Monitor

The Session Monitor validates the session against the Authrim server at regular intervals. Unlike Check Session Iframe (which checks IdP-level session state), this validates the app-level session.

Usage

import { SessionMonitor } from '@authrim/web';
const monitor = new SessionMonitor({
auth, // Authrim client instance
interval: 60000, // Check every 60 seconds
onExpired: () => {
console.log('Session expired');
window.location.href = '/login';
},
onError: (error) => {
console.warn('Session check failed:', error);
},
});
// Start monitoring
monitor.start();
// Stop monitoring
monitor.stop();

Parameters

ParameterTypeDefaultDescription
authAuthrimSDK client instance
intervalnumber60000Polling interval in milliseconds
onExpired() => voidCallback when session is no longer valid
onError(error) => voidCallback on check failure

Front-Channel Logout

Front-Channel Logout allows the IdP to notify your application when the user logs out. The IdP loads a hidden iframe pointing to your app’s logout endpoint, which clears the local session.

Setup

Register a front-channel logout URI in the Authrim Admin panel:

SettingValue
Front-Channel Logout URIhttps://myapp.com/logout
Front-Channel Logout Session Requiredtrue (recommended)

Handler

import { FrontChannelLogoutHandler } from '@authrim/web';
const handler = new FrontChannelLogoutHandler({
auth, // Authrim client instance
onLogout: () => {
console.log('Logged out by IdP');
window.location.href = '/';
},
});
// Initialize (listens for logout iframe loads)
handler.init();

How It Works

  1. User logs out at the IdP (or in another application)
  2. IdP sends a GET request to your front-channel logout URI (in a hidden iframe)
  3. Your page’s FrontChannelLogoutHandler receives the notification
  4. Local session is cleared and onLogout callback is invoked

Check Session Iframe

The Check Session Iframe detects when the user’s IdP session changes (e.g., the user logged out in another app, or the session expired at the IdP).

It works by loading a hidden iframe from the IdP’s check_session_iframe endpoint and exchanging messages via postMessage.

How It Works

sequenceDiagram
    participant App as Your App
    participant Iframe as Check Session Iframe
    participant IdP as Authrim IdP

    App->>Iframe: Start monitoring
    loop Every N seconds
        Iframe->>IdP: postMessage(client_id + session_state)
        IdP-->>Iframe: "changed" | "unchanged"
        alt Session changed
            Iframe->>App: Callback: session changed
            App->>App: Re-authenticate or logout
        end
    end

Usage

import { CheckSessionIframeManager } from '@authrim/web';
const manager = new CheckSessionIframeManager({
clientId: 'my-app',
checkSessionIframeUri: 'https://auth.example.com/check-session',
interval: 5000, // Check every 5 seconds (default: 3000)
});
// Start monitoring
manager.start({
sessionState: currentSessionState,
onChanged: () => {
console.log('IdP session changed — re-authenticating...');
// Try silent auth or redirect to login
},
});
// Stop monitoring (e.g., on page unmount)
manager.stop();

Parameters

ParameterTypeDefaultDescription
clientIdstringOAuth client ID
checkSessionIframeUristringIdP’s check_session_iframe URL
intervalnumber3000Polling interval in milliseconds

Combining Monitors

For a robust production setup, combine Tab Sync and Session Monitor:

const auth = await createAuthrim({
issuer: 'https://auth.example.com',
clientId: 'my-app',
enableOAuth: true,
});
// 1. Tab Sync — immediate cross-tab updates
const tabSync = new TabSyncManager({
onLogin: () => location.reload(),
onLogout: () => { window.location.href = '/login'; },
});
tabSync.start();
// 2. Session Monitor — periodic server-side validation
const monitor = new SessionMonitor({
auth,
interval: 60000,
onExpired: () => { window.location.href = '/login'; },
});
monitor.start();
// Clean up on page unload
window.addEventListener('beforeunload', () => {
tabSync.stop();
monitor.stop();
});

Next Steps