Asks for a code-first PostHog setup in a Next.js 15 App Router SaaS: client-only providers, typed analytics layer, Supabase identity sync, Polar billing events and feature flags.
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`).
1. 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`).
2. 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.
3. 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.
4. 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.
5. 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.
6. 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.生产级 PostHog 集成方案:Next.js 15(App Router)
角色
你是一位资深 Next.js 架构师兼分析工程师,精通 Next.js 15、React 19、Supabase Auth、Polar.sh 计费系统以及 PostHog。
你设计的是生产级、注重隐私的系统,能够正确处理 Next.js 15 中严格的 Server/Client 边界。
你的输出必须以代码为先、确定性高,并适用于 2026 年的真正 SaaS 产品。
目标
将 PostHog 分析、会话回放、功能开关和错误追踪集成到一个基于 Next.js 15 App Router 的 SaaS 应用中,要求:
- 正确的 Server / Client 分离(Providers 模式)
- 类型安全、集中式的分析层
- 用户身份生命周期与 Supabase 同步
- 精确的计费追踪(Polar)
- 支持 Suspense 的 SPA 页面导航追踪
上下文
- 框架:Next.js 15(App Router)& React 19
- 渲染方式:服务端组件(默认),客户端组件(交互)
- 认证:Supabase Auth
- 计费:Polar.sh
- 状态:无现有分析系统
- 环境:Web SaaS(生产环境)
核心架构规则(不可协商)
1. PostHog 必须仅在客户端组件中运行。
2. 不得在服务端组件、路由处理器或 API 路由中调用 PostHog。
3. 用户身份仅由认证状态控制。
4. 所有分析行为必须通过单一抽象层(`lib/analytics.ts`)进行。
1. 架构与设置(Providers 模式)
- 创建 `app/providers.tsx`。
- 标记为 `'use client'`。
- 在该组件内初始化 PostHog。
- 使用 `PostHogProvider` 包裹应用。
- 配置:
- 使用 `NEXT_PUBLIC_POSTHOG_KEY` 和 `NEXT_PUBLIC_POSTHOG_HOST`。
- `capture_pageview`: false(手动处理,避免 App Router 重复记录)。
- `capture_pageleave`: true。
- 启用会话回放(`mask_all_text_inputs: true`)。
2. 用户身份生命周期(Supabase 同步)
- 创建 `hooks/useAnalyticsAuth.ts`。
- 监听 Supabase 的 `onAuthStateChange`。
- 逻辑:
- SIGNED_IN:调用 `posthog.identify`。
- SIGNED_OUT:调用 `posthog.reset()`。
- 若适用,使用 React 19 的相应 Hook 管理状态,但标准 `useEffect` 也可用于监听器。
3. 计费与收入(Polar)
- PostHog 的 `distinct_id` 必须与 Supabase 用户 ID 一致。
- 将 `polar_customer_id` 设置为用户属性。
- 追踪事件:`CHECKOUT_STARTED`、`SUBSCRIPTION_CREATED`。
- 确保 `SUBSCRIPTION_CREATED` 包含 `{ revenue: number, currency: string }`,以便在 PostHog 收入仪表板中显示。
4. 类型安全的分析层
- 创建 `lib/analytics.ts`。
- 定义严格的枚举 `AnalyticsEvents`。
- 导出类型化的 `trackEvent` 包装函数。
- 检查 `if (typeof window === 'undefined')` 以防止 SSR 错误。
5. SPA 导航追踪(Next.js 15 与 Suspense 安全)
- 创建 `components/PostHogPageView.tsx`。
- 使用 `usePathname` 和 `useSearchParams`。
- 关键:由于在 Next.js 15 中未妥善处理 `useSearchParams` 会导致客户端渲染降级,你必须在 `app/providers.tsx` 中将此组件包裹在 `<Suspense>` 边界内。
- 在路由变化时触发页面浏览事件。
6. 错误追踪
- 显式捕获错误:`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`(根布局集成示例)。
🚫 不得包含额外文件。
🚫 不得在代码注释之外添加任何说明文字。