Blog / Measuring in PostHog and Stripe
PostHog in a Next.js app: install, identify, and first events
Init posthog-js in instrumentation-client.ts, identify users after login, send account and activation events from the server with posthog-node, then proxy.
To add PostHog to a Next.js app, install posthog-js, call posthog.init() in an instrumentation-client.ts file at the root of the project, and import posthog wherever you need it. Then identify users after login, send the events that prove something happened (account created, activation, payment) from the server with posthog-node, and route the traffic through your own domain. That is the setup in PostHog's Next.js guide.
Most tutorials stop once a $pageview shows up. This one goes as far as the first events a growth funnel needs, and lists the configuration mistakes that make the integration look finished while nothing arrives.
Which setup to pick
PostHog documents two routes for Next.js, read on November 18, 2026:
| Route | What you install | Status |
|---|---|---|
| Standard | posthog-js in instrumentation-client.ts, posthog-node on the server | Recommended for production |
@posthog/next | One package with a provider, a proxy file and a server helper | Pre-release, API may change |
The new package does useful things: the client and the server share one identity through a cookie, feature flags can be evaluated on the server so the page renders without flicker, and a built-in proxy routes events through your domain. PostHog still sends production apps to the standard guide, so that is what this article follows. If you want to try the package, note that its docs use NEXT_PUBLIC_POSTHOG_KEY as the variable name where the standard guide uses NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN.
PostHog also offers a wizard (npx @posthog/wizard) that detects the framework and writes the setup for you. It saves time; read the diff before you commit it.
Step 1. Install and initialize on the client
npm install --save posthog-js
Add two variables to .env.local and to your hosting provider. The project token is in your PostHog project settings.
NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=<your_project_token>
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
For a project on PostHog Cloud EU, the host is https://eu.i.posthog.com. Both variables need the NEXT_PUBLIC_ prefix, because the browser reads them.
Then create instrumentation-client.ts at the root, next to app or pages (both routers use it):
import posthog from 'posthog-js'
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
defaults: '2026-08-30',
})
Next.js runs this file before the application becomes interactive. The file convention arrived in Next.js 15.3, so this setup needs 15.3 or later.
The defaults line matters more than it looks. It is a date that switches on the recommended behaviors released up to that day. According to the configuration reference, any date from 2025-05-24 makes capture_pageview default to history_change, which records a page view each time the URL changes. Without it, PostHog listens to page loads only, and the client-side navigations of the App Router go uncounted. The 2026-01-30 defaults also inject PostHog's extra scripts in the <head> to avoid hydration errors in server-rendered frameworks.
From here, any client component can import posthog from posthog-js and call posthog.capture(). The feature flag hooks from @posthog/react work with the same singleton.
Step 2. Identify the user after login
Until you call identify, PostHog sees anonymous visitors. The Next.js guide calls this step required: it links events, replays and errors to a known person.
In a Next.js app, the simplest place is a small client component mounted in your authenticated layout, which runs once the session is known:
'use client'
import { useEffect } from 'react'
import posthog from 'posthog-js'
export function PostHogIdentify({ user }: { user: { id: string; email: string; plan: string } | null }) {
useEffect(() => {
if (user) {
posthog.identify(user.id, { email: user.email, plan: user.plan })
}
}, [user])
return null
}
Pass your database user ID, never a placeholder such as "anonymous" or "user", and send the email as a property. Call posthog.reset() in your logout handler. The PostHog identify guide covers which ID to choose, the order of calls around signup and the mistakes that split one person into two.
Step 3. Send the first events from the server
A click on "Create account" proves an intention. The row written in your database proves the account exists. The SaaS tracking plan sends facts from the server for that reason: no ad blocker, no tab closed too early. In Next.js, that means posthog-node in route handlers and server actions.
npm install --save posthog-node
The App Router setup in the docs creates a small factory:
// app/posthog.ts
import { PostHog } from 'posthog-node'
export default function PostHogClient() {
return new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
flushAt: 1,
flushInterval: 0,
})
}
flushAt: 1 and flushInterval: 0 send each event at once instead of batching, because server functions in Next.js can be short-lived. Then call await posthog.shutdown() when you are done, so nothing is left in the queue when the function stops.
Your first server event is the account itself, in the server action that creates it:
'use server'
import PostHogClient from '@/app/posthog'
export async function createAccount(form: FormData) {
const user = await db.user.create({ /* ... */ })
const posthog = PostHogClient()
posthog.capture({
distinctId: user.id,
event: 'account created',
properties: { method: 'email' },
})
await posthog.shutdown()
return user
}
The distinctId must be exactly the string the browser passed to identify. That is what puts the landing page view, the signup and the server event on one person. Use the same pattern for activation reached once your activation milestone is defined (the activation rate guide helps pick it), and for subscription events from your billing webhook.
When the browser calls your own API, posthog-js can add X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to those requests through the tracing_headers option, which lets server events link back to the browser session. List hostnames only, without protocol or port.
Step 4. Route events through your own domain
Tracking blockers drop requests to known analytics domains, and a funnel whose browser steps lose events while its server steps don't shows conversion rates that are wrong. PostHog recommends a reverse proxy, and offers a managed one free for Cloud users. If you prefer to keep it in your app, Next.js rewrites do the job:
// next.config.js
const nextConfig = {
async rewrites() {
return [
{ source: '/relay-x7/static/:path*', destination: 'https://us-assets.i.posthog.com/static/:path*' },
{ source: '/relay-x7/array/:path*', destination: 'https://us-assets.i.posthog.com/array/:path*' },
{ source: '/relay-x7/:path*', destination: 'https://us.i.posthog.com/:path*' },
]
},
skipTrailingSlashRedirect: true,
}
module.exports = nextConfig
Then set api_host: '/relay-x7' and ui_host: 'https://us.posthog.com' in posthog.init(). Four details from the docs:
- Order. The
staticandarrayrules come before the catch-all, because Next.js evaluates rewrites in order. - Path name. Avoid
/analytics,/tracking,/telemetryor/posthog: blockers catch them. Pick something specific to your app. - Trailing slash. PostHog paths end with a slash. Without
skipTrailingSlashRedirect, each request takes a 308 redirect first. If that setting creates duplicate URLs for your pages, PostHog lists canonical tags or a middleware redirect as fixes. - Cost. Rewrites route everything through your server, session recordings included. PostHog notes that recordings often weigh 1 to 5 MB per session, which counts toward Vercel's data transfer. If you record sessions on a busy site (see the session replay guide), the managed proxy avoids that line.
Why events don't arrive
Three causes account for most silent setups, all from PostHog's own troubleshooting notes:
- Content-Security-Policy. If your site sends a CSP, it must allow
https://*.posthog.cominscript-srcandconnect-src, andblob:inworker-srcfor replay. Otherwisecaptureandidentifynever send, with no error in your code. Remember thatdefault-src 'self'alone blocks event delivery. A first-party proxy also solves this. - Middleware matcher. A
middleware.ts(orproxy.tssince Next.js 16) from next-intl or an auth library can match your proxy path and redirect the capture requests. The SDK script still loads because its URL has a file extension, so PostHog looks connected while nothing is sent. Add your proxy path to the matcher's negative lookahead. - Region mismatch. A 401 or "No project token provided" usually means a US host for an EU project, or the reverse.
To verify, open the Network tab, trigger an event, look for a 200 on your proxy path, then check the activity view in PostHog. Then run the end-to-end test: sign up with a fresh account in a private window, and confirm that one person in PostHog holds the landing page view, the $identify event and your server-side account created.
What to remember
Four steps, in this order: posthog.init() in instrumentation-client.ts with a recent defaults date, identify after login with your database ID, facts sent from server actions with posthog-node and the same ID, and a proxy on a path blockers don't know. Check the CSP and the middleware matcher before you trust a quiet dashboard. Once one person holds the whole path from first visit to activation, every drop between two steps becomes a number you can compare, price, and pick as this week's priority.
Frequently asked questions
Where do I initialize PostHog in Next.js?
On Next.js 15.3 or later, in an instrumentation-client.ts file at the root of the project, next to the app or pages folder. Next.js runs that file before the app becomes interactive, so posthog.init() runs once and any client component can then import posthog from posthog-js. No provider component is needed for this setup.
Does PostHog track page views in the Next.js App Router?
Yes, if you pass a defaults date of 2025-05-24 or later to posthog.init(). From that date, capture_pageview defaults to history_change, which records a page view each time the URL changes through the browser history API. That covers client-side navigations, which a plain page load listener would miss.
Should I use @posthog/next or posthog-js?
PostHog labels @posthog/next a pre-release whose API may change, and points production apps to the standard guide: posthog-js in instrumentation-client.ts plus posthog-node on the server. The new package adds shared client and server identity, server-side flag bootstrapping and a built-in proxy, so it is worth testing on a side branch.
Why are no events arriving from my Next.js app?
Check three things. A Content-Security-Policy without https://*.posthog.com in connect-src blocks every send silently. A middleware or proxy.ts matcher can catch your proxy path and redirect the capture requests. And an EU project needs eu.i.posthog.com as host, otherwise requests fail with authentication errors.
Sources
- PostHog docs, Next.js: https://posthog.com/docs/libraries/next-js
- PostHog docs, Next.js: @posthog/next: https://posthog.com/docs/libraries/next-js/posthog-next
- PostHog docs, Next.js rewrites reverse proxy: https://posthog.com/docs/advanced/proxy/nextjs
- PostHog docs, JavaScript configuration: https://posthog.com/docs/libraries/js/config
- PostHog docs, Node.js: https://posthog.com/docs/libraries/node
- PostHog docs, Identifying users: https://posthog.com/docs/product-analytics/identify
- Next.js docs, instrumentation-client.js: https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client