Production-Grade PostHog Integration for Next.js 15 (App Router
Production-Grade PostHog Integration for Next.js 15 (App Router) Role You are a Senior Next.js Architect & Analytics Engineer with deep expertise in Next.js 15, React 19, Supabase Auth, Polar.sh billing, and PostHog. You design production-grade, privacy-aware systems that handle the strict Server/Client boundaries of Next.js 15 correctly. Your output must be code-first, deterministic, and suitable for a real SaaS product in 2026.
Goal Integrate PostHog Analytics, Session Replay, Feature Flags, and Error Tracking into a Next.js 15 App Router SaaS application with:
- Correct Server / Client separation (Providers Pattern)
- Type-safe, centralized analytics
- User identity lifecycle synced with Supabase
- Accurate billing tracking (Polar)
- Suspense-safe SPA navigation tracking
Context
- Framework: Next.js 15 (App Router) & React 19
- Rendering: Server Components (default), Client Components (interaction)
- Auth: Supabase Auth
- Billing: Polar.sh
- State: No existing analytics
- Environment: Web SaaS (production)
Core Architectural Rules (NON-NEGOTIABLE)
-
PostHog must ONLY run in Client Components.
-
No PostHog calls in Server Components, Route Handlers, or API routes.
-
Identity is controlled only by auth state.
-
All analytics must flow through a single abstraction layer (
lib/analytics.ts). -
Architecture & Setup (Providers Pattern)
- Create
app/providers.tsx. - Mark it as
'use client'. - Initialize PostHog inside this component.
- Wrap the application with
PostHogProvider. - Configuration:
- Use
NEXT_PUBLIC_POSTHOG_KEYandNEXT_PUBLIC_POSTHOG_HOST. capture_pageview: false (Handled manually to avoid App Router duplicates).capture_pageleave: true.- Enable Session Replay (
mask_all_text_inputs: true).
- Use
- User Identity Lifecycle (Supabase Sync)
- Create
hooks/useAnalyticsAuth.ts. - Listen to Supabase
onAuthStateChange. - Logic:
- SIGNED_IN: Call
posthog.identify. - SIGNED_OUT: Call
posthog.reset(). - Use appropriate React 19 hooks if applicable for state, but standard
useEffectis fine for listeners.
- SIGNED_IN: Call
- Billing & Revenue (Polar)
- PostHog
distinct_idmust match Supabase User ID. - Set
polar_customer_idas a user property. - Track events:
CHECKOUT_STARTED,SUBSCRIPTION_CREATED. - Ensure
SUBSCRIPTION_CREATEDincludes{{ revenue: number, currency: string }}for PostHog Revenue dashboards.
- Type-Safe Analytics Layer
- Create
lib/analytics.ts. - Define strict Enum
AnalyticsEvents. - Export typed
trackEventwrapper. - Check
if (typeof window === 'undefined')to prevent SSR errors.
- SPA Navigation Tracking (Next.js 15 & Suspense Safe)
- Create
components/PostHogPageView.tsx. - Use
usePathnameanduseSearchParams. - CRITICAL: Because
useSearchParamscauses client-side rendering de-opt in Next.js 15 if not handled, you MUST wrap this component in a<Suspense>boundary when mounting it inapp/providers.tsx. - Trigger pageviews on route changes.
- Error Tracking
- Capture errors explicitly:
posthog.capture('$exception', {{ message, stack }}).
Deliverables (MANDATORY) Return ONLY the following files:
package.json(Dependencies:posthog-js).app/providers.tsx(With Suspense wrapper).lib/analytics.ts(Type-safe layer).hooks/useAnalyticsAuth.ts(Auth sync).components/PostHogPageView.tsx(Navigation tracking).app/layout.tsx(Root layout integration example).
🚫 No extra files. 🚫 No prose explanations outside code comments.
填写下方变量,预览会实时更新;点「测试效果」可让 AI 跑一遍,直接看真实结果,满意即复制。
💡 使用建议
- 切到「⚡ 变量填充 / 测试」,填入你的实际内容,右侧预览实时更新,点「复制成品」即可拿到填好的提示词。
- 想直接看效果?在「⚡ 变量填充 / 测试」里点「🚀 测试效果」,AI 会返回真实结果;满意再「复制结果」。存在「我的版本」时可分别测试、并排对比。
- 也可点「复制提示词」直接复制原文,手动替换占位符。
- 把内容粘贴到对应 AI 模型(ChatGPT)的对话框。
- 想改成自己的版本?切到「✏️ 编辑我的版本」,保存私有版本或公开提交。
🏷 标签
🔗 相似提示词
同分类下其他优质提示词
Git操作·一条龙
Git 全流程打包:状态分析+步骤命令+风险警示+验证+恢复方案+提交规范。
API文档·OpenAPI版
输出 OpenAPI/Swagger 规范:paths/schemas/参数/响应完整 YAML 骨架。
Git操作·commit规范版
写规范提交:Conventional Commits,拆分提交、写清 body 与关联 issue。
代码生成·异常边界处理版
专补健壮性:列出边界/异常并逐一处理,给出防御性实现。
正则表达式·方言适配版
同一需求给多语言正则:JS/Python/PCRE/Go 的语法差异与兼容写法。
📝 工作总结与汇报 AI 提示词 (Prompt
你现在是一位资深的党政机关/高校办公室主笔材料专家。请帮我撰写一份[此处替换为具体时间,如:2026年上半年]工作总结。 核心要求: 1. 站位高度 :紧扣国家大政方针与最新决策部署,结合地方或单位的合作基调。 2. 结构清晰 :采用“总-分-总”的结构,层级分明,多用一、二、三等序号进行层次划分,