中文译文
面向 Next.js 15(App Router)的生产级 PostHog 集成 角色 你是一位资深 Next.js 架构师兼分析工程师,在 Next.js 15、React 19、Supabase Auth、Polar.sh 计费以及 PostHog 方面拥有深厚专长。 你设计生产级、注重隐私的系统,能够正确处理 Next.js 15 严格的 Server/Client 边界。 你的输出必须代码优先、确定性,并适用于 2026 年的真实 SaaS 产品。
目标 将 PostHog Analytics、Session Replay、Feature Flags 和 Error Tracking 集成到 Next.js 15 App Router 的 SaaS 应用中,并满足:
- 正确的 Server / Client 分离(Providers 模式)
- 类型安全、集中式的分析
- 与 Supabase 同步的用户身份生命周期
- 准确的计费追踪(Polar)
- Suspense 安全的 SPA 导航追踪
背景
- 框架:Next.js 15(App Router)与 React 19
- 渲染:Server Components(默认)、Client Components(交互)
- 认证:Supabase Auth
- 计费:Polar.sh
- 状态:无现有分析
- 环境:Web SaaS(生产)
核心架构规则(不可协商)
PostHog 必须仅在 Client Components 中运行。
不得在 Server Components、Route Handlers 或 API routes 中调用 PostHog。
身份仅由认证状态控制。
所有分析必须流经单一抽象层(
lib/analytics.ts)。架构与设置(Providers 模式)
- 创建
app/providers.tsx。 - 将其标记为
'use client'。 - 在此组件内初始化 PostHog。
- 使用
PostHogProvider包裹应用。 - 配置:
- 使用
NEXT_PUBLIC_POSTHOG_KEY和NEXT_PUBLIC_POSTHOG_HOST。 capture_pageview:false(手动处理以避免 App Router 重复)。capture_pageleave:true。- 启用 Session Replay(
mask_all_text_inputs: true)。
- 使用
- 用户身份生命周期(Supabase 同步)
- 创建
hooks/useAnalyticsAuth.ts。 - 监听 Supabase
onAuthStateChange。 - 逻辑:
- SIGNED_IN:调用
posthog.identify。 - SIGNED_OUT:调用
posthog.reset()。 - 如适用,使用适当的 React 19 hooks 处理状态,但监听器使用标准
useEffect即可。
- SIGNED_IN:调用
- 计费与收入(Polar)
- PostHog 的
distinct_id必须与 Supabase 用户 ID 匹配。 - 将
polar_customer_id设置为用户属性。 - 追踪事件:
CHECKOUT_STARTED、SUBSCRIPTION_CREATED。 - 确保
SUBSCRIPTION_CREATED包含{ revenue: number, currency: string },以供 PostHog 收入仪表盘使用。
- 类型安全的分析层
- 创建
lib/analytics.ts。 - 定义严格的枚举
AnalyticsEvents。 - 导出带类型的
trackEvent封装。 - 检查
if (typeof window === 'undefined')以防止 SSR 错误。
- SPA 导航追踪(Next.js 15 与 Suspense 安全)
- 创建
components/PostHogPageView.tsx。 - 使用
usePathname和useSearchParams。 - 关键:由于在 Next.js 15 中,若不加以处理,
useSearchParams会导致客户端渲染降级,因此在app/providers.tsx中挂载此组件时,你必须将其包裹在<Suspense>边界中。 - 在路由变化时触发页面浏览。
- 错误追踪
- 显式捕获错误:
posthog.capture('$exception', { message, stack })。
交付物(强制) 仅返回以下文件:
package.json(依赖:posthog-js)。app/providers.tsx(带 Suspense 包裹)。lib/analytics.ts(类型安全层)。hooks/useAnalyticsAuth.ts(认证同步)。components/PostHogPageView.tsx(导航追踪)。app/layout.tsx(根布局集成示例)。
🚫 不要额外文件。 🚫 不要在代码注释之外写文字说明。
English original
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.