Next.js session replay installation

  1. Install the package

    Required

    Install the PostHog JavaScript library using your package manager:

    npm install posthog-js
  2. Add environment variables

    Required

    Add your PostHog API key and host to your .env.local file and to your hosting provider (e.g. Vercel, Netlify). These values need to start with NEXT_PUBLIC_ to be accessible on the client-side.

    .env.local
    NEXT_PUBLIC_POSTHOG_KEY=<ph_project_api_key>
    NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
  3. Initialize PostHog

    Required

    Choose 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.ts for a lightweight, fast integration:

    instrumentation-client.ts
    import posthog from 'posthog-js'
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
    api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
    defaults: '2025-11-30'
    })
    Defaults option

    The defaults option automatically configures PostHog with recommended settings for new projects. See SDK defaults for details.

  4. Accessing PostHog on the client

    Recommended

    Once initialized in instrumentation-client.ts, import posthog from posthog-js anywhere and call the methods you need:

    app/checkout/page.tsx
    'use client'
    import posthog from 'posthog-js'
    export default function CheckoutPage() {
    function handlePurchase() {
    posthog.capture('purchase_completed', { amount: 99 })
    }
    return <button onClick={handlePurchase}>Complete purchase</button>
    }
  5. Watch session recordings

    Recommended

    Visit 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.

    Watch your first recording →

  6. Next steps

    Recommended

    Now that you're recording sessions, continue with the resources below to learn what else Session Replay enables within the PostHog platform.

    ResourceDescription
    Watching recordingsHow to find and watch session recordings
    Privacy controlsHow to mask sensitive data in recordings
    Network recordingHow to capture network requests in recordings
    Console log recordingHow to capture console logs in recordings
    More tutorialsOther real-world examples and use cases

Community questions

Was this page useful?

Questions about this page? or post a community question.