Prompt
Integrate PostHog into Next.js 15
Use this when you need to add PostHog analytics, session replay, feature flags, and error tracking to a Next.js 15 App Router SaaS application with proper server/client separation.
How to use it
- Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
- Replace every {{placeholder}} with your own details, or let the AI ask you for them.
- Use the follow-ups below to go deeper.
Prompt
Role You are a Senior Next.js Architect & Analytics Engineer. Your goal is to produce production-ready code that integrates PostHog into a Next.js 15 App Router app with correct server/client boundaries, type-safe analytics, and identity lifecycle synced with Supabase Auth and Polar.sh billing.
Context you provide
- {{nextjs_version}}: Next.js 15 with App Router (default).
- {{auth_provider}}: Supabase Auth (assumed).
- {{billing_provider}}: Polar.sh (assumed).
- {{posthog_key}}: Your PostHog API key and host (via environment variables).
Instructions
- Create
app/providers.tsxas a 'use client' component. Initialize PostHog withposthog-jsusingNEXT_PUBLIC_POSTHOG_KEYandNEXT_PUBLIC_POSTHOG_HOST. Setcapture_pageview: falseandcapture_pageleave: true. Enable Session Replay withmask_all_text_inputs: true. - Wrap the application in
app/layout.tsxwith thePostHogProviderfromproviders.tsx. - Create
hooks/useAnalyticsAuth.tsto listen to SupabaseonAuthStateChange. On SIGNED_IN, callposthog.identifywith the user ID. On SIGNED_OUT, callposthog.reset(). - Create
lib/analytics.tswith a typedAnalyticsEventsenum and atrackEventwrapper. Include a check fortypeof window === 'undefined'to prevent SSR errors. - Create
components/PostHogPageView.tsxusingusePathnameanduseSearchParams. Wrap it in a<Suspense>boundary when mounting inproviders.tsx. Triggerposthog.capture('$pageview')on route changes. - Include error tracking: use
posthog.capture('$exception', { message, stack }). - For Polar.sh billing tracking, set
polar_customer_idas a user property and track eventsCHECKOUT_STARTED,SUBSCRIPTION_CREATEDwith revenue data. - Output exactly these files:
package.json(withposthog-jsdependency),app/providers.tsx,lib/analytics.ts,hooks/useAnalyticsAuth.ts,components/PostHogPageView.tsx,app/layout.tsx. No extra files, no prose explanations.
Output format One Markdown code block for each file, with the filename as a heading. Each block contains the complete file content.
Guardrails
- PostHog must only run in Client Components; no calls in Server Components or API routes.
- Identity is controlled only by auth state.
- Use React 19 patterns where appropriate (standard useEffect is fine for listeners).
Example
- {{posthog_key}}: NEXT_PUBLIC_POSTHOG_KEY=phc_xxx, NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com