Next.js: @posthog/next
Contents
@posthog/next is currently in pre-release. The API may change before the stable release. For production apps, see the standard Next.js setup guide.
@posthog/next is a unified package for integrating PostHog into your Next.js app. It provides a simplified interface that handles common patterns out of the box:
- Synchronized identity across client and server, so both sides share the same user automatically
- Server-side feature flag bootstrapping so hooks return real values immediately with no flicker
- Eager client initialization ensures PostHog is always available when your components render
- Built-in API proxy that routes SDK traffic through your domain to avoid ad blockers
- Automatic event flushing with no manual
shutdown()orflush()calls needed
This guide covers both the App Router and Pages Router. You'll need a PostHog instance (Cloud or self-hosted) and a Next.js 13.0.0+ application.
- 1
Install @posthog/next
Required - 2
Add your environment variables
RequiredAdd these to your
.env.localfile and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your project settings..env.localNEXT_PUBLIC_POSTHOG_HOSTis optional and defaults tohttps://us.i.posthog.com. - 3
Add the middleware
RecommendedThe middleware seeds an identity cookie on first visit so client and server share the same user, and optionally proxies API requests through your domain.
middleware.tsSetting
proxy: trueroutes PostHog API calls through your domain at/ingest, which helps avoid ad blockers. You can customize the path prefix by passingproxy: { pathPrefix: '/analytics' }instead.Note: Middleware requires a server runtime and is not available with
output: 'export'(fully static sites). If you can't use middleware, you can set up a reverse proxy separately to route traffic through your domain. - 4
Wrap your app with PostHogProvider
RequiredAdd
PostHogProviderandPostHogPageViewto your root layout:app/layout.tsxPostHogProvideris a React Server Component. WhenbootstrapFlagsis enabled, it evaluates feature flags server-side and passes the results to the client so hooks return real values immediately.Note: Enabling
bootstrapFlagsopts the route into dynamic rendering (incompatible with static generation / ISR). Without it, the provider does not call any dynamic Next.js APIs and is safe for static pages.Add
PostHogProviderandPostHogPageViewto your_app:pages/_app.tsxNote: For the Pages Router, import from
@posthog/next/pagesinstead of@posthog/next. Verify events are captured
CheckpointConfirm that you can see events in your PostHog projectVisit your app and click around. Within a minute or two, you should see
$pageviewand autocaptured events (like clicks) appear in the activity tab.- 5
Access PostHog in client components
RequiredAll hooks must be used in client components (
'use client').Capture events:
TSXFeature Flags:
TSXConditional rendering with
PostHogFeature:TSXYou can also read the full
posthog-jsdocumentation for all the usable functions. - 6
Identify your user
RecommendedCall
posthog.identify()on the client after login to link events to a known user. This connects event captures, session replays, LLM traces, and Error Tracking to the same person across client and server.TSXSee our guide on identifying users for more details.
- 7
Use PostHog on the server
RecommendedUse
getPostHog()in server components, route handlers, and server actions to capture events and evaluate feature flags. The client is automatically scoped to the current user via the identity cookie set by the middleware.TSXNote:
getPostHog()callscookies()internally, which opts the route into dynamic rendering. Pages using it cannot be statically generated.Event flushing: On Vercel,
@posthog/nextauto-detectswaitUntilfrom@vercel/functionsso events are flushed after the response is sent without blocking it. No manualshutdown()call is needed. In other environments, you can pass a customwaitUntilviaserverOptionson thePostHogProvider, or events will be batched and flushed normally.Use
getServerSidePostHoginsidegetServerSidePropsto capture events and evaluate feature flags for the current user:pages/dashboard.tsxTo bootstrap feature flags and eliminate flicker on page load, pass the flag data through
pageProps:pages/dashboard.tsxEvent flushing: On Vercel,
@posthog/nextauto-detectswaitUntilfrom@vercel/functionsso events are flushed after the response is sent without blocking it. No manualshutdown()call is needed. In other environments, you can pass a customwaitUntilviaserverOptionson thePostHogProvider, or events will be batched and flushed normally.Then wire the bootstrap data into the provider:
pages/_app.tsx - 8
Further reading
Recommended