6 min read

How to Track Session Length in Amplitude

Amplitude automatically tracks session length the moment you initialize the SDK. A session represents a continuous period of user activity, separated by your configured timeout period. Understanding session length tells you how engaged users are—whether they're spending 2 minutes or 30 minutes in your product.

How Amplitude Tracks Sessions Automatically

Sessions start when the SDK initializes and continue as long as events fire within the timeout window. Once that window closes, the next event begins a new session.

Step 1: Initialize the SDK with default session tracking

Install the Amplitude SDK and call init(). By default, Amplitude creates a session with a 30-minute timeout—if 30 minutes pass without an event, the next event starts a new session. Every event automatically includes the session_id property.

javascript
import * as amplitude from '@amplitude/analytics-browser';

// Initialize SDK - sessions are tracked automatically
amplitude.init('YOUR_API_KEY');
Sessions begin on init with a 30-minute default timeout.

Step 2: Track events—session_id is included automatically

Every time you call track(), Amplitude automatically attaches the current session_id. You don't manually capture or manage session IDs—they're handled behind the scenes.

javascript
// Track an event - session_id is automatically included
amplitude.track('button_clicked');
amplitude.track('page_viewed', { page_name: 'pricing' });
amplitude.track('subscription_started', { plan: 'pro' });

// In Amplitude, each event has session_id attached
The session_id is added to every event automatically.
Tip: A session extends if an event fires within the timeout. If your timeout is 30 minutes and an event fires at minute 29, the session continues. At minute 31, a new session begins.

Customize Session Timeout to Match Your Product

The default 30-minute timeout works for many products, but fast-moving SaaS tools may need shorter timeouts (5–10 minutes), while asynchronous workflows might benefit from longer ones (60 minutes).

Step 1: Set a custom session timeout in init()

Pass a configuration object to init() with your desired sessionTimeout in milliseconds. For a 5-minute timeout, use 300000 (5 × 60 × 1000). For 10 minutes, use 600000.

javascript
// 5-minute session timeout
amplitude.init('YOUR_API_KEY', {
  sessionTimeout: 300000
});

// 10-minute session timeout
amplitude.init('YOUR_API_KEY', {
  sessionTimeout: 600000
});

// 60-minute session timeout for long workflows
amplitude.init('YOUR_API_KEY', {
  sessionTimeout: 3600000
});
sessionTimeout is in milliseconds. 60000 ms = 1 minute.

Step 2: Access the current session ID when needed

If your code needs to reference the active session ID, call getSessionId(). This returns the current session ID as a number. Use this for debugging, logging, or integrating with other tools.

javascript
const sessionId = amplitude.getSessionId();
console.log('Current session:', sessionId);

// Useful for custom integrations
if (sessionId) {
  analytics.logSession(sessionId);
  localStorage.setItem('amp_session_id', sessionId);
}
getSessionId() is useful for custom session tracking integrations.
Watch out: Session timeout is per-browser instance. A user with multiple tabs open won't have a synchronized session across tabs—each tab gets its own session. If you need cross-tab awareness, handle it with custom logic or shared storage.

Analyze Session Length in Amplitude's UI

Once sessions are tracked, view and segment by session length in the Amplitude dashboard to understand engagement patterns.

Step 1: Navigate to Sessions in the Events dashboard

Go to Analyze > Events. Create a chart with Sessions as your metric. Amplitude automatically calculates session length (time from first to last event in a session). You'll see how many sessions occur and their average length.

javascript
// No SDK code needed—use the Amplitude UI.
// But if you want to export session data programmatically via the REST API:

const apiKey = 'YOUR_API_KEY';
const response = await fetch(
  'https://api.amplitude.com/api/2/events?start=20240101T00&end=20240201T00&limit=10000',
  {
    headers: {
      Authorization: `Basic ${btoa(apiKey + ':')}`
    }
  }
);
const data = await response.json();
data.data.events.forEach(event => {
  console.log(`Event: ${event.event_type}, Session: ${event.session_id}`);
});
Use the Events REST API to export session data for analysis.

Step 2: Filter by session length to find patterns

In Segmentation, add a filter for Session Duration (e.g., sessions longer than 5 minutes). Create a cohort of long-session users to understand what features drive engagement. Compare session length across user segments, devices, or regions.

javascript
// Optionally track custom session completion events with length:

const sessionStart = Date.now();

// ... user interacts with product ...

// When session ends (e.g., on logout or timeout):
const sessionLengthSeconds = Math.floor((Date.now() - sessionStart) / 1000);
amplitude.track('session_completed', {
  session_length_seconds: sessionLengthSeconds,
  session_id: amplitude.getSessionId(),
  user_segment: 'premium'
});
Optional: track custom session-end events for additional context.
Tip: Session length reflects *active* time, not wall-clock time. If a user opens your app, goes idle for 10 minutes, then clicks a button, the session duration is based on event timestamps, not the 10-minute gap.

Common Pitfalls

  • Setting timeout too long masks engagement. A 24-hour timeout merges a 2-minute morning session and a 5-minute afternoon session into one long session.
  • Forgetting that background activity (API calls, webhooks, polling) can keep sessions alive indefinitely—users may appear more engaged than they actually are.
  • Confusing session_id with user_id. A user has one user_id but many sessions. Always clarify which you're measuring.
  • Mobile-specific issue: mobile users frequently minimize and return to your app. Short timeout values can fragment sessions artificially on mobile devices.

Wrapping Up

Session length is one of the clearest signals of user engagement. Amplitude captures it automatically out of the box, but tuning the timeout to your product's usage rhythm will give you more actionable insights. If you want to track this automatically across tools, Product Analyst can help.

Track these metrics automatically

Product Analyst connects to your stack and surfaces the insights that matter.

Try Product Analyst — Free