首页 全部提示词 Web Development

Next.js 15 (App Router) 生产级 PostHog 集成

Production-Grade PostHog Integration for Next.js 15 (App Router)

文本 @ted2xmen 2,321 字符 在 prompts.chat 查看 译文有问题?

中文译文

面向 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(生产)

核心架构规则(不可协商)

  1. PostHog 必须仅在 Client Components 中运行。

  2. 不得在 Server Components、Route Handlers 或 API routes 中调用 PostHog。

  3. 身份仅由认证状态控制。

  4. 所有分析必须流经单一抽象层(lib/analytics.ts)。

  5. 架构与设置(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)。
  1. 用户身份生命周期(Supabase 同步)
  • 创建 hooks/useAnalyticsAuth.ts。
  • 监听 Supabase onAuthStateChange。
  • 逻辑:
    • SIGNED_IN:调用 posthog.identify。
    • SIGNED_OUT:调用 posthog.reset()。
    • 如适用,使用适当的 React 19 hooks 处理状态,但监听器使用标准 useEffect 即可。
  1. 计费与收入(Polar)
  • PostHog 的 distinct_id 必须与 Supabase 用户 ID 匹配。
  • 将 polar_customer_id 设置为用户属性。
  • 追踪事件:CHECKOUT_STARTED、SUBSCRIPTION_CREATED。
  • 确保 SUBSCRIPTION_CREATED 包含 { revenue: number, currency: string },以供 PostHog 收入仪表盘使用。
  1. 类型安全的分析层
  • 创建 lib/analytics.ts。
  • 定义严格的枚举 AnalyticsEvents。
  • 导出带类型的 trackEvent 封装。
  • 检查 if (typeof window === 'undefined') 以防止 SSR 错误。
  1. SPA 导航追踪(Next.js 15 与 Suspense 安全)
  • 创建 components/PostHogPageView.tsx。
  • 使用 usePathname 和 useSearchParams。
  • 关键:由于在 Next.js 15 中,若不加以处理,useSearchParams 会导致客户端渲染降级,因此在 app/providers.tsx 中挂载此组件时,你必须将其包裹在 <Suspense> 边界中。
  • 在路由变化时触发页面浏览。
  1. 错误追踪
  • 显式捕获错误:posthog.capture('$exception', { message, stack })。

交付物(强制) 仅返回以下文件:

  1. package.json(依赖:posthog-js)。
  2. app/providers.tsx(带 Suspense 包裹)。
  3. lib/analytics.ts(类型安全层)。
  4. hooks/useAnalyticsAuth.ts(认证同步)。
  5. components/PostHogPageView.tsx(导航追踪)。
  6. 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)

  1. PostHog must ONLY run in Client Components.

  2. No PostHog calls in Server Components, Route Handlers, or API routes.

  3. Identity is controlled only by auth state.

  4. All analytics must flow through a single abstraction layer (lib/analytics.ts).

  5. 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_KEY and NEXT_PUBLIC_POSTHOG_HOST.
    • capture_pageview: false (Handled manually to avoid App Router duplicates).
    • capture_pageleave: true.
    • Enable Session Replay (mask_all_text_inputs: true).
  1. 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 useEffect is fine for listeners.
  1. Billing & Revenue (Polar)
  • PostHog distinct_id must match Supabase User ID.
  • Set polar_customer_id as a user property.
  • Track events: CHECKOUT_STARTED, SUBSCRIPTION_CREATED.
  • Ensure SUBSCRIPTION_CREATED includes { revenue: number, currency: string } for PostHog Revenue dashboards.
  1. Type-Safe Analytics Layer
  • Create lib/analytics.ts.
  • Define strict Enum AnalyticsEvents.
  • Export typed trackEvent wrapper.
  • Check if (typeof window === 'undefined') to prevent SSR errors.
  1. SPA Navigation Tracking (Next.js 15 & Suspense Safe)
  • Create components/PostHogPageView.tsx.
  • Use usePathname and useSearchParams.
  • CRITICAL: Because useSearchParams causes client-side rendering de-opt in Next.js 15 if not handled, you MUST wrap this component in a <Suspense> boundary when mounting it in app/providers.tsx.
  • Trigger pageviews on route changes.
  1. Error Tracking
  • Capture errors explicitly: posthog.capture('$exception', { message, stack }).

Deliverables (MANDATORY) Return ONLY the following files:

  1. package.json (Dependencies: posthog-js).
  2. app/providers.tsx (With Suspense wrapper).
  3. lib/analytics.ts (Type-safe layer).
  4. hooks/useAnalyticsAuth.ts (Auth sync).
  5. components/PostHogPageView.tsx (Navigation tracking).
  6. app/layout.tsx (Root layout integration example).

🚫 No extra files. 🚫 No prose explanations outside code comments.