How to add PostHog to Next.js.
How to add PostHog to Next.js and start collecting events you can use in funnels, recordings, or feature flag experiments.

Loading the lesson…
Loading activities…
How to add PostHog to Next.js and start collecting events you can use in funnels, recordings, or feature flag experiments.

Loading the lesson…
Loading activities…
Connect your Next.js app to PostHog so it can send events. Once that works, you can look at session recordings, build a funnel, and try a feature flag.
Sign up at posthog.com. The free tier is VERY generous.
Add PostHog to your app.
Set PostHog up when your app loads.
Add tracking code wherever the important stuff happens.
Here's a basic setup for a Next.js app. Install the library first.
Then put your project token and host in .env.local. Use https://us.i.posthog.com if your PostHog project lives in the US cloud, or https://eu.i.posthog.com if it's in the EU cloud.
Last, create a file called instrumentation-client.js in the root of your Next.js app. Next.js runs it once in the browser when your app loads, which is exactly when PostHog wants to start up.
That defaults date pins PostHog's default settings to a specific version, so an update doesn't quietly change how your tracking behaves. Copy whatever date PostHog's own Next.js docs show when you set it up.
One of PostHog's coolest features is session recording. It records exactly what people do in your app... mouse movements, clicks, scrolling, all of it.
This stuff is crazy valuable for a few jobs.
A "funnel" follows people through a series of steps. Here's a checkout funnel, for example.
The funnel shows you where people drop off. In this example, MOST of them leave between viewing the product and adding it to the cart. So that's your sign to go fix the product page.
PostHog comes with feature flags, which are a way to show new features to only some of your users.
That onFeatureFlags wrapper matters. Right when the page loads PostHog hasn't fetched your flags yet, so checking too early can show everybody the old version.
Here's what that lets you do.