Session duration is a signal of engagement—when it drops, something's wrong. PostHog tracks sessions automatically, but without alerts, you're left checking dashboards manually. Let's set up an alert that catches drops in real time.
Initialize PostHog and Track Session Completion
PostHog records sessions by default, but you need to explicitly capture session duration as an event so you can alert on it.
Initialize the PostHog SDK with session recording
Load PostHog in your app with session recording enabled. This captures user interactions and page views automatically.
import posthog from 'posthog-js';
posthog.init('phc_YOUR_API_KEY', {
api_host: 'https://us.posthog.com',
session_recording: {
sampleRate: 1.0
},
capture_pageview: true
});Capture session duration when the session ends
On page unload or session exit, capture a session_completed event with the session duration in seconds. Store sessionStartTime when the page loads.
window.sessionStartTime = Date.now();
window.addEventListener('beforeunload', () => {
const sessionDurationMs = Date.now() - window.sessionStartTime;
const sessionDurationSeconds = Math.floor(sessionDurationMs / 1000);
posthog.capture('session_completed', {
session_duration_seconds: sessionDurationSeconds,
user_path: window.location.pathname
});
});sampleRate below 1.0, you'll lose session data. Keep it at 1.0 in production unless your volume forces sampling.Create an Insight to Track Session Duration Trends
Build a baseline insight first so you know what normal session duration looks like before setting alert thresholds.
Create a new Trends insight in PostHog
Go to Insights in the sidebar, click Create Insight, and select Trends. This will be the source for your alert.
Query average session duration
Under Events, select session_completed. Then set the aggregation to Average and the property to session_duration_seconds. This shows your typical session length over time.
// Create this insight via the PostHog API
fetch('https://us.posthog.com/api/projects/YOUR_PROJECT_ID/insights/', {
method: 'POST',
headers: {
'Authorization': `Bearer YOUR_PERSONAL_API_KEY`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Average Session Duration',
filters: {
events: [{
id: 'session_completed',
type: 'events'
}]
},
query: {
kind: 'TrendsQuery',
math: 'avg',
math_property: 'session_duration_seconds'
}
})
});Let the insight run for 3–7 days to establish a baseline
Watch the graph stabilize. Note the typical average—this is your baseline. For SaaS apps, 200–400 seconds is common. Use this to set your alert threshold.
Set Up an Alert Subscription
Now set a threshold that fires when session duration drops significantly, signaling a possible engagement issue.
Click Subscribe on your session duration insight
On your insight, click the Subscribe button in the top right. Select Alert from the dropdown and choose Lower threshold.
Set your alert threshold and recurrence
If your baseline is 300 seconds, set the alert to fire when average drops below 200 seconds. Choose how often PostHog checks this: hourly, daily, or weekly. Hourly is best for catching sudden changes.
// Create the alert subscription via API
fetch('https://us.posthog.com/api/projects/YOUR_PROJECT_ID/subscriptions/', {
method: 'POST',
headers: {
'Authorization': `Bearer YOUR_PERSONAL_API_KEY`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Session Duration Drop Alert',
insight: INSIGHT_ID,
subscription_type: 'alert',
target_type: 'slack',
target_value: 'https://hooks.slack.com/services/YOUR/WEBHOOK/URL',
trigger_value: 200 // alert if below 200 seconds
})
});Choose your notification channel
Send alerts to Slack, email, or a custom webhook. For fast response, use Slack and tag your #analytics or #product channel.
Common Pitfalls
- Forgetting to enable session_recording in the SDK—sessions record but not with the depth you need
- Using milliseconds instead of seconds for duration—creates confusion and makes thresholds hard to reason about
- Not filtering out bot traffic, testing sessions, or internal staff—they skew your baseline and trigger false alarms
- Setting alerts on session count instead of duration—count varies with traffic; duration is the real signal of engagement
Wrapping Up
You now have a baseline for session duration and an alert that fires when engagement drops. This catches issues before users complain. If you want to track this automatically across tools, Product Analyst can help.