Source citations: root/README.md
Session replay is one of PostHog's core features—it captures real user sessions so you can watch exactly how people interact with your app, diagnose bugs, and understand behavior patterns. This guide walks you through installing PostHog in a Next.js application, configuring privacy masking, and setting performance budgets to keep replay overhead minimal.
Prerequisites
- Next.js 13+ (App Router or Pages Router)
- Node.js 18+ and npm/pnpm/yarn
- A PostHog account (Cloud or self-hosted instance)
- Your PostHog Project API Key and Host URL (find these in Project Settings)
Step 1: Install the PostHog JavaScript SDK
PostHog provides a dedicated posthog-js library for browser-side tracking. Install it:
npm install posthog-js
# or
pnpm add posthog-js
Step 2: Initialize PostHog in Your Next.js App
App Router (Next.js 13+)
Create a client-side provider component to initialize PostHog once. The exact file structure will depend on your Next.js setup:
'use client'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
import { useEffect } from 'react'
export function PHProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init('<your-api-key>', {
api_host: '<value>',
session_recording: {
maskAllInputs: true,
maskTextSelector: '[data-private]',
},
})
}, [])
return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}
Wrap your root layout with the provider component.
Pages Router (Next.js 12 and earlier)
Initialize PostHog in your app entry point:
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
import { useEffect } from 'react'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
useEffect(() => {
posthog.init('<your-api-key>', {
api_host: '<value>',
session_recording: {
maskAllInputs: true,
maskTextSelector: '[data-private]',
},
})
}, [])
return (
<PostHogProvider client={posthog}>
<Component {...pageProps} />
</PostHogProvider>
)
}
Configuration
Replace <your-api-key> and <value> with your actual values. For PostHog Cloud, use https://app.posthog.com as the host. For self-hosted PostHog, use your instance URL.
Store these values as environment variables in your deployment configuration to avoid hardcoding credentials.
Step 3: Configure Privacy Masking
Session replay captures DOM snapshots and user interactions. By default, PostHog masks sensitive data, but you should tune this for your app's privacy requirements.
Mask All Text Inputs
The maskAllInputs: true option (shown above) redacts all <input>, <textarea>, and <select> values. Users will see *** in replays instead of actual input text.
Mask Specific Elements
Use the maskTextSelector option to target custom elements:
session_recording: {
maskTextSelector: '[data-private],.sensitive-info, #user-email',
}
Then mark elements in your JSX:
<div data-private>
User's credit card: 4111 1111 1111 1111
</div>
Unmask Safe Inputs
If you want to capture certain inputs (e.g., search queries), set maskAllInputs: false and selectively mask sensitive fields:
session_recording: {
maskAllInputs: false,
maskInputOptions: {
password: true,
email: true,
},
}
Block Entire Sections
Add the ph-no-capture class to prevent recording specific DOM subtrees:
<div className="ph-no-capture">
<CreditCardForm />
</div>
PostHog will replace this section with a placeholder in replays.
Step 4: Set a Performance Budget
Session replay adds network and CPU overhead. PostHog provides several knobs to control resource usage:
Sampling Rate
Record only a percentage of sessions:
session_recording: {
sampleRate: 0.5, // Record 50% of sessions
}
Use conditional sampling to record more sessions for authenticated users:
posthog.init('<your-api-key>', {
session_recording: {
sampleRate: posthog.get_distinct_id() ? 1.0: 0.2,
},
})
Network Payload Size
Limit the size of network request/response bodies captured in replays:
session_recording: {
recordHeaders: true,
recordBody: true,
networkPayloadCapture: {
recordHeaders: true,
recordBody: true,
},
}
Configure URL patterns to exclude from network capture based on your application's API structure.
Canvas and Performance Capture
Disable canvas recording if your app uses heavy graphics:
session_recording: {
recordCanvas: false,
}
Disable performance metrics if you don't need Web Vitals in replays:
session_recording: {
capturePerformance: false,
}
Minimum Session Duration
Skip very short sessions (e.g., bots, accidental clicks):
session_recording: {
minimumDuration: 5000, // Only record sessions longer than 5 seconds
}
Step 5: Verify Session Replay is Working
-
Start your Next.js dev server:
npm run dev
-
Open your app in a browser and interact with it (click buttons, fill forms, navigate pages).
-
Go to PostHog → Session Replay in your project dashboard. You should see your session appear within 30 seconds.
-
Click on a session to watch the replay. Verify that:
- Masked inputs show
***
- Elements with
data-private are redacted
- Sections with
ph-no-capture are blocked
Troubleshooting
No Sessions Appear in PostHog
- Check configuration: Ensure your Project API Key and Host URL are correct.
- Verify initialization: Open browser DevTools → Network tab and look for requests to PostHog endpoints. If missing, PostHog isn't initializing.
- Check sampling rate: If you set
sampleRate < 1.0, you may need to refresh multiple times to trigger a recorded session.
Replays Are Choppy or Missing Interactions
- Network throttling: Session replay sends snapshots in batches. Slow networks can delay uploads. Check the Network tab for failed requests.
- Ad blockers: Some ad blockers block PostHog. Test in an incognito window without extensions.
Sensitive Data Leaking in Replays
- Review masking selectors: Use browser DevTools to inspect elements and confirm they match your
maskTextSelector.
- Test with real data: Fill out forms with fake sensitive data and verify it's redacted in the replay.
High CPU Usage
- Disable canvas recording: Set
recordCanvas: false if your app has heavy animations.
- Reduce sampling: Lower
sampleRate to 0.1 or 0.2 for high-traffic apps.
Next Steps
- Analyze user behavior: Use PostHog's Product Analytics to correlate session replays with feature usage, conversion funnels, and retention cohorts (source:
root/README.md).
- A/B test with replays: Combine Feature Flags with session replay to watch how users interact with experimental features (source:
root/README.md).
- Monitor performance: Enable
capturePerformance: true to track Web Vitals (LCP, FID, CLS) alongside replays.
Knowledge base references:
- PostHog feature overview:
root/README.md