Next.js web analytics installation
Install posthog-js using your package manager:
Add your environment variables to your .env.local file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project API key in your project settings.
These values need to start with NEXT_PUBLIC_ to be accessible on the client-side.
Integration
Next.js 15.3+ provides the instrumentation-client.ts|js file for a quick, lightweight setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this:
Using Next.js 15.2 or older?
Older versions of Next.js don't support the instrumentation-client.ts|js file. You can use the following setup instead:
If your Next.js app uses the app router, you can integrate PostHog by creating a providers file in your app folder. This is because the posthog-js library needs to be initialized on the client-side using the Next.js 'use client' directive.
Then, import the PostHogProvider component into your app/layout file and wrap your app with it.
PostHog is now set up and ready to go. It will begin to autocapture events and pageviews. Files and components accessing PostHog on the client-side need the 'use client' directive.
If you use the pages router, you can integrate PostHog at the root of your app in pages/_app.js.
Bootstrapping with instrumentation-client
When using instrumentation-client, the values you pass to posthog.init remain fixed for the entire session. This means bootstrapping only works if you evaluate flags before your app renders (for example, on the server).
If you need flag values after the app has rendered, you’ll want to:
- Evaluate the flag on the server and pass the value into your app, or
- Evaluate the flag in an earlier page/state, then store and re-use it when needed.
Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same distinct_id across client and server.
See the bootstrapping guide for more information.
Next steps
After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.
PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.