Next.js session replay installation
- 1
Install the package
RequiredInstall the PostHog JavaScript library using your package manager:
- 2
Add environment variables
RequiredAdd your PostHog API key and host to your
.env.localfile and to your hosting provider (e.g. Vercel, Netlify). These values need to start withNEXT_PUBLIC_to be accessible on the client-side..env.local - 3
Initialize PostHog
RequiredChoose the integration method based on your Next.js version and router type.
If you're using Next.js 15.3+, you can use
instrumentation-client.tsfor a lightweight, fast integration:instrumentation-client.tsFor the App router, create a
providers.tsxfile in yourappfolder. Theposthog-jslibrary needs to be initialized on the client-side using the'use client'directive:app/providers.tsxThen import the
PostHogProvidercomponent in yourapp/layout.tsxand wrap your app with it:app/layout.tsxFor the Pages router, integrate PostHog at the root of your app in
pages/_app.tsx:pages/_app.tsxDefaults optionThe
defaultsoption automatically configures PostHog with recommended settings for new projects. See SDK defaults for details. - 4
Accessing PostHog on the client
RecommendedOnce initialized in
instrumentation-client.ts, importposthogfromposthog-jsanywhere and call the methods you need:app/checkout/page.tsxUse the
usePostHoghook to access PostHog in client components:app/checkout/page.tsx - 5
Watch session recordings
RecommendedVisit your site or app and interact with it for at least 10 seconds to generate a recording. Navigate between pages, click buttons, and fill out forms to capture meaningful interactions.
- 6
Next steps
RecommendedNow that you're recording sessions, continue with the resources below to learn what else Session Replay enables within the PostHog platform.
Resource Description Watching recordings How to find and watch session recordings Privacy controls How to mask sensitive data in recordings Network recording How to capture network requests in recordings Console log recording How to capture console logs in recordings More tutorials Other real-world examples and use cases