Complete AI Training

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

  1. Copy the prompt and paste it into ChatGPT, Claude, Gemini or any other AI.
  2. Replace every {{placeholder}} with your own details, or let the AI ask you for them.
  3. 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

  1. Create app/providers.tsx as a 'use client' component. Initialize PostHog with posthog-js using NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST. Set capture_pageview: false and capture_pageleave: true. Enable Session Replay with mask_all_text_inputs: true.
  2. Wrap the application in app/layout.tsx with the PostHogProvider from providers.tsx.
  3. Create hooks/useAnalyticsAuth.ts to listen to Supabase onAuthStateChange. On SIGNED_IN, call posthog.identify with the user ID. On SIGNED_OUT, call posthog.reset().
  4. Create lib/analytics.ts with a typed AnalyticsEvents enum and a trackEvent wrapper. Include a check for typeof window === 'undefined' to prevent SSR errors.
  5. Create components/PostHogPageView.tsx using usePathname and useSearchParams. Wrap it in a <Suspense> boundary when mounting in providers.tsx. Trigger posthog.capture('$pageview') on route changes.
  6. Include error tracking: use posthog.capture('$exception', { message, stack }).
  7. For Polar.sh billing tracking, set polar_customer_id as a user property and track events CHECKOUT_STARTED, SUBSCRIPTION_CREATED with revenue data.
  8. Output exactly these files: package.json (with posthog-js dependency), 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