#PostHog integration in NextJS
1 messages · Page 1 of 1 (latest)
Integrating PostHog with Next.js involves several steps. Here's a summary based on the information from the Vercel guide (https://vercel.com/guides/posthog-nextjs-vercel-feature-flags-analytics#setting-up-posthog-with-next.js):
-
Create a Next.js Application: You can create a new Next.js application using the command
npx create-next-app@latest next-appcd next-appnpm run dev. -
Adding PostHog: Sign up for a PostHog instance (https://app.posthog.com/signup) to obtain your project API key and instance address. Add your API key and address to a
.env.localfile. Then, addposthog-jsto your project and configure PostHog by creating a new Client Component to instantiate the provider. -
Using PostHog with React Server Components: The Next.js App Router uses React Server Components by default. To use PostHog on the server, you can use the PostHog Node SDK (https://posthog.com/docs/libraries/node) to access features like server-side rendered feature flags.
-
Setting Up Feature Flags: You can access feature flags in PostHog to conditionally render content from Next.js. Create a flag inside PostHog with the key
my_flagand read the flag in your Next.js application. -
Deploying on Vercel: Once your Next.js application is integrated with PostHog, you can deploy to Vercel's frontend cloud.
If you've followed these steps and are still not seeing data in your PostHog dashboard, it could be due to a few reasons:
-
Data not visible in Web Analytics dashboard: If data is not visible in the analytics dashboard or a 404 error occurs while loading
script.js, it could be due to deploying the tracking code before enabling Web Analytics. To fix this, ensure that you have enabled Analytics in the dashboard, re-deploy your app to Vercel, and promote your latest deployment to production (source (https://vercel.com/docs/analytics/quickstart#troubleshooting)). -
Not working with proxy (e.g., Cloudflare): Web Analytics may not function when using a proxy, such as Cloudflare. Check your proxy configuration to make sure that all desired pages are correctly proxied to the deployment and forward all requests to
/_vercel/insights/*to the deployments to ensure proper functioning of Web Analytics through the proxy (source (https://vercel.com/docs/analytics/quickstart#troubleshooting)).