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.
// 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 loadFilter 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.
// 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 InsightsCalculate 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.
// 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 IDQuery 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.
// 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();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.
// 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 changesWatch 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?
// 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 appCommon 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_endevents. 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.