5 min read

How to Calculate Session Duration in PostHog

PostHog automatically tracks when users arrive and leave, but understanding session duration—how long someone actually spends in your product—is critical for measuring engagement and spotting drop-off points. We'll show you how to pull session duration data using PostHog's built-in features and custom calculations.

View Session Duration in Your Dashboard

PostHog calculates session duration automatically. The fastest way to see this data is through the Insights dashboard.

Navigate to Session Duration Metric

Go to Insights and create a new insight. In the event or metric selector, look for the Session Duration metric under the standard metrics. This shows average session length across your users.

javascript
// PostHog SDK automatically tracks sessions when initialized
import PostHog from 'posthog-js';

PostHog.init('YOUR_PROJECT_KEY', {
  api_host: 'https://app.posthog.com',
  session_recording: {
    sample_rate: 0.5 // Capture recordings for 50% of sessions
  }
});

// Sessions start automatically on page load
Initialize PostHog to begin automatic session tracking

Filter by User Properties

Click Add filter and select user properties like plan, signup date, or location. This reveals whether certain user segments have longer or shorter sessions. For example, paid users often have longer sessions than free users.

javascript
// Identify users with properties to segment session duration
PostHog.identify('user-123', {
  email: '[email protected]',
  plan: 'pro',
  signup_date: '2024-01-15'
});

// PostHog automatically segments all session data by these properties
// Now you can filter sessions by plan or other user attributes in Insights
Set user properties so PostHog can segment sessions by cohort or attribute
Tip: Use the Breakdown by dropdown to split session duration by feature, URL, or user property. This helps pinpoint which parts of your product are engaging.

Calculate Session Duration with Custom Events

For more control, track specific lifecycle events and calculate duration yourself.

Track Session Start and End

Send a session_start event when the user authenticates and a session_end event when they log out or navigate away. PostHog automatically includes the session ID in the $session_id property of both events.

javascript
// Log session start when user logs in
PostHog.capture('session_start', {
  plan: 'pro',
  referrer: document.referrer
});

// Later, when user logs out
PostHog.capture('session_end', {
  pages_visited: 8,
  features_used: ['dashboard', 'reports']
});

// PostHog includes $session_id automatically in both events
// allowing you to correlate them later by session ID
Capture lifecycle events with context for session analysis

Query Duration with SQL

Use PostHog's SQL insight to calculate session duration. Write a query that finds the time elapsed between session_start and session_end for each session ID.

javascript
// Example SQL query (run in PostHog Insights > SQL tab)
const sqlQuery = `
  SELECT
    properties.$session_id as session_id,
    MIN(timestamp) as session_start,
    MAX(timestamp) as session_end,
    EXTRACT(EPOCH FROM (MAX(timestamp) - MIN(timestamp))) as duration_seconds
  FROM events
  WHERE event IN ('session_start', 'session_end')
  GROUP BY properties.$session_id
  LIMIT 1000
`;

// Fetch results via PostHog API
const response = await fetch(
  `https://app.posthog.com/api/projects/YOUR_PROJECT_ID/insights/`,
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer YOUR_PERSONAL_API_TOKEN`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: { kind: 'SQLQuery', query: sqlQuery },
      name: 'Session Duration Calculation'
    })
  }
);

const results = await response.json();
Query session duration using SQL and fetch results programmatically
Watch out: PostHog's default 30-minute idle timeout still applies. Very long idle sessions may be truncated silently, so add custom events for app-specific session logic.

Build Cohorts and Watch Behavior

Use session duration to identify and test with your most engaged users.

Create an Engaged User Cohort

Go to Cohorts > New cohort and add a filter for session duration > 5 minutes. Name it 'Engaged Users'. PostHog will automatically enroll users whose average session duration exceeds your threshold.

javascript
// Track session duration as a user property after each session
PostHog.identify('user-123', {
  avg_session_duration_seconds: 450, // 7.5 minutes
  is_power_user: 450 > 300 // true if > 5 minutes
});

// In PostHog UI, create a cohort with filter:
// User property 'avg_session_duration_seconds' > 300
// This cohort auto-updates as users' session data changes
Set session duration as a user property for cohort membership

Watch Session Recordings

Click Recordings and filter by your 'Engaged Users' cohort. Watch how these users actually interact with your product. Look for patterns: do they spend time on onboarding, dive straight to analytics, or explore multiple features?

javascript
// Enable session recording to capture user behavior
PostHog.init('YOUR_PROJECT_KEY', {
  api_host: 'https://app.posthog.com',
  session_recording: {
    sample_rate: 1.0, // Record all sessions
    capture_console: true // Capture console for debugging
  }
});

// In PostHog UI:
// Recordings > Duration filter > '5 minutes or more'
// Now watch how long-session users move through your app
Configure recording capture and filter recordings by session length
Tip: Combine session duration cohorts with feature flags to A/B test changes. Do flagged users have different session durations than control? That signals engagement impact.

Common Pitfalls

  • Confusing session duration with page load time or time-on-page. PostHog measures from session start to end, not individual page views.
  • Forgetting the 30-minute idle timeout. By default, PostHog ends sessions after 30 minutes without activity, so very long sessions may actually represent multiple interactions.
  • Double-counting if you capture both automatic sessions and manual session_start/session_end events. PostHog tracks sessions natively—only add custom events if you need app-specific logic.
  • Ignoring bot traffic. Bots often skew averages. Enable the Bot filter on your Insights dashboard to exclude them.

Wrapping Up

PostHog's built-in session tracking gives you immediate visibility into engagement. Start with the dashboard, move to SQL queries for custom analysis, then use recordings to understand user behavior. 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