Files
Dustin ByrneandGitHub 87bcfbe4b4 feat(next): Add first class support for Next.js (#3122)
* feat(next): Introduce a first class Next.js integration

* feat(next): Next.js app router example

* feat(next): Provide default client configuration

* feat(next): Composable middleware; allow first-class proxy

* refactor(next): Use `resolveApiKey`

* feat(next): Example uses proxied PostHog at /ingest

* fix(next): Skip initial client flag load when flags are bootstrapped via SSR

* feat(next): Deduplicate flag evaluation with React.cache

* refactor(next): Use `readPostHogCookie`

* feat(next): Sync $sesid and $device_id from cookies in server clients

* feat(next): Scope server-side client via `enterContext()`

* fix(next): Eagerly init the client-side PostHog client

This avoids a race condition where the client may be used before it's
initialized

* feat(next): Next SSR is aware of client opt-out consent

When configured, the server will respect the clients opt-out consent
configuration.

* chore(next): Update the app router example

* fix(next): Wrap PostHogPageView in Suspense

* docs(next): Add README and USAGE

* refactor(next): Drop explicit force-dynamic in example

* feat(next): Use a composable pages API

* feat(next): Integrate `waitUntil` automatically in Vercel; expose serverOptions

* chore(next): Clean up tsconfig

* fix(next): finalizing clean up

* chore(next): add changeset

* fix(next): packaging and bug fixes

Getting the example back in running order

* chore(next): move the app-router example

* chore(next): fix the vercel build

* fix: greptile comments

* fix: ClientPostHogProvider warns on missing api key

* test: validate pageview on router ready

* trigger ci

* fix: greptile

* chore: prettier
2026-03-05 16:06:22 -05:00

1.6 KiB

@posthog/next App Router Example

A Next.js 15 App Router example demonstrating all features of the @posthog/next package.

Setup

  1. Copy the environment template:

    cp .env.local.example .env.local
    
  2. Add your PostHog API key to .env.local:

    NEXT_PUBLIC_POSTHOG_KEY=phc_your_key_here
    NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
    
  3. From the monorepo root, export packages as tarballs:

    pnpm package:watch
    
  4. In a new terminal, install dependencies and start the dev server from this directory:

    pnpm install
    pnpm dev
    
  5. Open http://localhost:3000

Demos

Route Feature Description
/auth Identity Log in/out with posthog.identify() and posthog.reset()
/server-flags Server Components Evaluate feature flags server-side
/client-hooks React Hooks Use useFeatureFlag and friends
/ssr-bootstrap SSR Bootstrap Feature flags on first render with no flicker
/capture Event Capture Capture custom events from client components

Feature Flags

Create these flags in your PostHog project to see the demos in action:

  • example-flag -- Used by the Client Hooks and SSR Bootstrap demos. Can be boolean or multivariate.