Session Management
The SDK automatically manages user sessions based on configurable inactivity and termination timeouts. Sessions are tracked using browser storage APIs and include a unique session ID with all telemetry data.
Critical Session Behavior:
- Sessions are created automatically on first page load
- Session state is evaluated on each page load, not continuously
- Session expiration is based on stored timestamps, not real-time monitoring
- Session ID is included in all telemetry signals automatically
- Session state is shared across tabs on the same domain (via storage)
- Session state may not be immediately synchronized across tabs
Capabilities
Terminate Session
Manually terminates the current user session. This takes effect on the next physical page load.
/**
* Manually terminates the current user session
* Takes effect on the next physical page load
* @throws No errors thrown; operation is best-effort
*/
function terminateSession(): void;
Usage Examples:
import { terminateSession } from "@dash0/sdk-web";
// Terminate session on user logout
function handleLogout() {
// Terminate the session
terminateSession();
// Clear user attributes
// (See user-identification.md)
// Perform logout logic
clearAuthToken();
redirectToLogin();
}
For IIFE (script tag) usage:
dash0("terminateSession");
Critical Behavior:
- Termination takes effect on the next physical page load, not immediately
- Current page continues to use the existing session ID
- Termination flag is stored in browser storage
- If storage is unavailable, termination may not persist
- Calling
terminateSession() multiple times has no additional effect
- Termination does not clear user identification attributes (must be cleared separately)
- Termination does not clear signal attributes (must be cleared separately)
- Termination flag is checked during initialization on next page load
- If storage is cleared between calls, termination may not persist
Automatic Session Management
The SDK automatically manages sessions based on configuration options set during initialization:
Session Inactivity Timeout
The maximum allowed time between page loads before a session expires.
Default: 10800000 ms (3 hours)
Maximum: 86400000 ms (24 hours)
import { init } from "@dash0/sdk-web";
init({
serviceName: "my-website",
endpoint: { url: "...", authToken: "..." },
sessionInactivityTimeoutMillis: 1800000, // 30 minutes
});
Critical Behavior:
- Timeout is measured from the last page load timestamp
- If user navigates within the timeout period, session continues
- If timeout is exceeded, a new session is created on next page load
- Timeout values exceeding 24 hours are clamped to 24 hours
- Timeout is stored in browser storage and persists across page loads
- Timeout evaluation occurs on page load, not continuously
- Very short timeouts (< 1 minute) may cause frequent session resets
- Clock changes may affect timeout accuracy
Session Termination Timeout
The maximum allowed time since session start before a session expires.
Default: 21600000 ms (6 hours)
Maximum: 86400000 ms (24 hours)
init({
serviceName: "my-website",
endpoint: { url: "...", authToken: "..." },
sessionTerminationTimeoutMillis: 43200000, // 12 hours
});
Critical Behavior:
- Timeout is measured from session start timestamp
- Even if user is active, session expires after termination timeout
- Timeout values exceeding 24 hours are clamped to 24 hours
- Timeout is stored in browser storage and persists across page loads
- Termination timeout is independent of inactivity timeout
- Session expires if either timeout is exceeded
- Clock changes may affect timeout accuracy
- Very short timeouts may cause premature session expiration
Session Tracking
Session ID
Every telemetry signal includes a session.id attribute that identifies the current user session. The session ID:
- Is automatically generated on the first page load
- Persists across page loads within the same session
- Is stored in browser storage (localStorage/sessionStorage)
- Changes when a session expires or is manually terminated
Critical Behavior:
- Session ID is a unique string identifier
- Session ID format is implementation-specific and may change
- Session ID is included in all telemetry signals automatically
- Session ID cannot be manually set or modified
- Session ID generation uses cryptographically secure random values when available
- Session ID is generated synchronously during initialization
- Duplicate session IDs are extremely unlikely but theoretically possible
Session Lifecycle
-
Session Start: A new session is created when:
- A user first visits the site
- The previous session expired due to inactivity
- The previous session reached the termination timeout
- The session was manually terminated
-
Session Continue: A session continues when:
- The user navigates to a new page within the inactivity timeout
- The user reloads the page within the inactivity timeout
- The session hasn't reached the termination timeout
-
Session End: A session ends when:
- The inactivity timeout is exceeded
- The termination timeout is exceeded
terminateSession() is called (takes effect on next page load)
Critical Behavior:
- Session start/end is determined on each page load
- Session state is checked synchronously during initialization
- Session expiration is evaluated based on stored timestamps
- If storage is unavailable, a new session is created on each page load
- Session state evaluation occurs before telemetry collection begins
- Session expiration timing may be affected by clock changes
- Very rapid page loads may cause session state evaluation issues
Common Use Cases
User Logout
Terminate the session when a user explicitly logs out:
import { terminateSession, removeSignalAttribute } from "@dash0/sdk-web";
async function handleUserLogout() {
// Clear user identification
removeSignalAttribute("user.id");
removeSignalAttribute("user.name");
removeSignalAttribute("user.email");
// Terminate the session
terminateSession();
// Perform logout
await logoutAPI();
// Redirect to login page
window.location.href = "/login";
}
Account Switching
Terminate the session when switching between accounts:
import { terminateSession, identify } from "@dash0/sdk-web";
async function switchAccount(newAccountId) {
// Terminate current session
terminateSession();
// Switch account in backend
await switchAccountAPI(newAccountId);
// Identify new user
const newUser = await fetchUserData(newAccountId);
identify(newUser.id, {
name: newUser.name,
email: newUser.email,
});
// Reload page to start new session
window.location.reload();
}
Privacy Mode
Terminate session when entering privacy/incognito mode:
function enterPrivacyMode() {
terminateSession();
// Clear user identification
removeSignalAttribute("user.id");
// Reload to start anonymous session
window.location.reload();
}
Session Reset After Sensitive Operations
Reset the session after sensitive operations:
async function changePassword(oldPassword, newPassword) {
await updatePasswordAPI(oldPassword, newPassword);
// Terminate session for security
terminateSession();
// Force re-authentication
redirectToLogin();
}
Session Storage
The SDK uses browser storage APIs to persist session information:
- Checks for storage availability before attempting to use it
- Falls back to generating a session ID without persistence if storage is unavailable
- Stores session data including: session ID, start time, last activity time
Storage Key
The session data is stored with the key: d0_session
Critical Behavior:
- Storage key is prefixed with
d0_ to avoid conflicts
- Key is consistent across all pages on the same domain
- Key is domain-specific (different domains have separate storage)
- Key format may change in future SDK versions
- Key conflicts with other applications are unlikely but possible
Storage Format
Session data is stored as a string with the format:
{sessionId}#{startTime}#{lastActivityTime}
Critical Behavior:
- Format is implementation-specific and may change
- Timestamps are stored as milliseconds since epoch
- Invalid storage format may cause session reset
- Storage format is not part of the public API
- Corrupted storage data may cause session reset
- Very long session IDs may cause storage issues
Browser Storage Compatibility
The SDK automatically detects storage availability and handles scenarios where:
- Cookies are disabled
- LocalStorage is not available
- Storage quota is exceeded
- Storage access is denied
If storage is unavailable, the SDK still generates a session ID but cannot persist it across page loads, resulting in a new session on each page load.
Critical Behavior:
- Storage availability is checked during initialization
- If storage is unavailable, session tracking continues in-memory only
- In-memory sessions do not persist across page loads
- Storage errors are handled gracefully (no exceptions thrown)
- Private browsing mode may disable storage, causing session reset on each page load
- Storage quota exceeded may cause session data to not be saved
- Storage access denied may cause session data to not be saved
- Storage corruption may cause session reset
Session Duration Examples
Short Sessions (E-commerce)
For e-commerce sites where users typically complete tasks quickly:
init({
serviceName: "my-store",
endpoint: { url: "...", authToken: "..." },
sessionInactivityTimeoutMillis: 900000, // 15 minutes
sessionTerminationTimeoutMillis: 3600000, // 1 hour
});
Medium Sessions (SaaS Applications)
For SaaS applications where users work for extended periods:
init({
serviceName: "my-app",
endpoint: { url: "...", authToken: "..." },
sessionInactivityTimeoutMillis: 3600000, // 1 hour
sessionTerminationTimeoutMillis: 28800000, // 8 hours
});
Long Sessions (Content Sites)
For content sites where users may return throughout the day:
init({
serviceName: "my-content-site",
endpoint: { url: "...", authToken: "..." },
sessionInactivityTimeoutMillis: 10800000, // 3 hours
sessionTerminationTimeoutMillis: 86400000, // 24 hours (maximum)
});
Edge Cases and Error Conditions
Storage Edge Cases
- Storage Unavailable: If localStorage/sessionStorage is unavailable, sessions do not persist across page loads
- Storage Quota Exceeded: If storage quota is exceeded, session data may not be saved, causing session reset
- Storage Access Denied: If storage access is denied (e.g., by browser policy), sessions do not persist
- Storage Corruption: If stored session data is corrupted, SDK may reset the session
- Storage Clearing: If user clears browser storage, all session data is lost
- Storage Race Conditions: Concurrent storage operations from multiple tabs may cause race conditions
- Storage Performance: Very slow storage operations may impact initialization performance
Timing Edge Cases
- Clock Skew: If system clock changes significantly, session timeouts may behave unexpectedly
- Negative Timeouts: Negative timeout values are invalid and may cause errors or use defaults
- Extremely Large Timeouts: Timeouts exceeding 24 hours are clamped to 24 hours
- Concurrent Page Loads: Multiple tabs may have different session states if storage is shared
- Very Rapid Page Loads: Very rapid page loads may cause session state evaluation issues
- Clock Changes: System clock changes may affect timeout accuracy
- Timezone Changes: Timezone changes may affect timestamp accuracy
Browser Behavior
- Private Browsing: Private browsing mode may disable storage, causing session reset on each page load
- Incognito Mode: Similar to private browsing, storage may be unavailable
- Browser Restart: Browser restart may clear storage, causing session reset
- Storage Clearing: If user clears browser storage, sessions are reset
- Browser Updates: Browser updates may change storage behavior
- Browser Extensions: Browser extensions may interfere with storage access
Multiple Tabs
- Shared Storage: Multiple tabs on the same domain share storage, so they share session state
- Tab Isolation: Some browsers isolate storage per tab, causing separate sessions per tab
- Tab Closing: Closing a tab does not affect session state in other tabs
- Tab Synchronization: Session state may not be immediately synchronized across tabs
- Concurrent Operations: Concurrent operations across tabs may cause race conditions
- Tab Focus: Tab focus changes do not affect session state
- Tab Visibility: Tab visibility changes do not affect session state
Network and Transmission
- Offline Mode: Sessions continue to be tracked even when offline
- Network Failures: Network failures do not affect session tracking
- Transmission Delays: Session ID is included in telemetry even if transmission is delayed
- Transmission Failures: Transmission failures do not affect session tracking
- Multiple Endpoints: Session ID is sent to all configured endpoints
Session ID Edge Cases
- ID Collision: Session ID collisions are extremely unlikely but theoretically possible
- ID Format Changes: Session ID format may change in future SDK versions
- ID Length: Very long session IDs may cause storage or transmission issues
- ID Generation Failures: If session ID generation fails, SDK may fall back to alternative methods
- ID Persistence: Session ID persistence depends on storage availability
Performance Edge Cases
- Storage Operations: Storage operations are synchronous and may block if storage is slow
- Session Evaluation: Session state evaluation occurs during initialization and may impact load time
- Memory Usage: Session data in memory is minimal but may accumulate with many sessions
- CPU Usage: Session state evaluation has minimal CPU impact
Notes
terminateSession() only takes effect on the next physical page load, not immediately
- Sessions are automatically terminated and new sessions created based on timeout configuration
- The session ID is included in all telemetry signals via the
session.id attribute
- Session tracking requires browser storage API support for cross-page persistence
- If storage is unavailable, sessions reset on each page load
- Session timeouts are evaluated on each page load, not continuously
- Session state is shared across tabs on the same domain (via storage)
- Session expiration timing may be affected by clock changes
- Very rapid page loads may cause session state evaluation issues