5 min read

How to Track Session Duration in PostHog

Session duration shows how long users actually stay on your site. PostHog tracks this automatically, but you need to know where to find the data and how to use it effectively. Let's walk through setting this up.

Enable Session Tracking in PostHog

Session tracking is enabled by default in PostHog, but you need the SDK properly initialized to capture it.

Step 1: Install and initialize the PostHog SDK

Add the PostHog JS SDK to your app. This automatically starts tracking sessions and assigns each user a $session_id.

javascript
import posthog from 'posthog-js';

posthog.init('phc_YOUR_API_KEY', {
  api_host: 'https://us.posthog.com',
  session_recording: {
    enabled: true
  }
});
Initialize PostHog with session tracking enabled

Step 2: Identify users for better segmentation

Use posthog.identify() to attach user properties like plan, company, or signup date. This lets you break down session duration by user segment.

javascript
// Identify user when they log in
posthog.identify('user-123', {
  name: 'Alice Johnson',
  email: '[email protected]',
  plan: 'pro',
  company: 'acme-corp'
});
Identify users with their properties
Watch out: Session duration is calculated from the first event to the last event in a session. PostHog ends a session after 30 minutes of inactivity.

View Session Duration Data

Once the SDK is capturing sessions, you can view duration data directly in PostHog.

Step 1: Check the Sessions view

In the PostHog dashboard, go to Data Management > Sessions. This table shows every session with its duration in seconds, along with user, browser, and device info.

javascript
// Query sessions via the PostHog API
const response = await fetch(
  'https://us.posthog.com/api/projects/PROJECT_ID/sessions/',
  {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${POSTHOG_PERSONAL_API_TOKEN}`,
      'Content-Type': 'application/json'
    }
  }
);

const data = await response.json();
data.results.forEach(session => {
  console.log(`Session ${session.session_id}: ${session.duration}s`);
});
Fetch session data via the PostHog API

Step 2: Create an Insight to track duration trends

Go to Insights and click + New insight. Select Trends and choose Session duration broken down by day or week. This shows how engagement changes over time.

javascript
// Capture custom events to track engagement depth
posthog.capture('feature_used', {
  feature_name: 'analytics_dashboard',
  time_spent_seconds: 120,
  user_action: 'export_report'
});
Capture events that indicate engagement

Step 3: Segment by user properties

In your Insight, add a filter like plan = pro or signup_date > 2024-01-01. This breaks down session duration by cohort and shows which users are most engaged.

javascript
// Update user properties to reflect changes
posthog.identify('user-123', {
  plan: 'enterprise',
  plan_upgrade_date: '2024-03-20',
  annual_value: 12000
});
Update user properties for cohort-based analysis
Tip: Use Funnels to see where users spend the most time in your conversion flow. Compare session duration between users who convert and those who drop off.

Debug and Optimize Session Data

Ensure your session tracking is complete and accurate.

Step 1: Verify session capture in development

Open your browser's Network tab and look for PostHog API calls. You should see events with $session_id in their properties. Check that the SDK initialized before your first page event.

javascript
// Initialize PostHog early, before routing
if (typeof window !== 'undefined') {
  import('posthog-js').then(({ default: posthog }) => {
    posthog.init('phc_YOUR_API_KEY', {
      api_host: 'https://us.posthog.com',
      loaded: (ph) => {
        console.log('PostHog ready, session:', ph.get_distinct_id());
      }
    });
  });
}
Initialize PostHog early in your app lifecycle

Step 2: Check your event volume

Go to Settings > Billing & usage to see monthly event volume. If sessions are fragmented, consider reducing session recording sample rate to manage costs.

javascript
// Adjust session recording to reduce volume
posthog.init('phc_YOUR_API_KEY', {
  api_host: 'https://us.posthog.com',
  session_recording: {
    enabled: true,
    sampleRate: 0.5
  },
  capture_pageleave: true
});
Control session recording sample rate and end detection

Common Pitfalls

  • Initializing PostHog late in your app — if the SDK loads after routing, you'll miss the start of sessions and duration will be inaccurate.
  • Forgetting to identify users — you can see aggregate session duration, but without user identification, you can't segment by plan or cohort.
  • Not accounting for the 30-minute inactivity timeout — users with long gaps between actions might have their sessions split into multiple entries.
  • Capturing too many events — high event volume fragments sessions and inflates your data costs. Be selective about what you track.

Wrapping Up

You're now tracking session duration in PostHog. Start by exploring the Sessions view, then build Insights to spot engagement trends. Use filters and segmentation to compare duration across cohorts, then run experiments to improve it. 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