From 06866af7fefb19c3b46b3ce3c19dfb75de05fda5 Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Fri, 3 Jul 2026 16:29:54 +0000 Subject: [PATCH] wizard-ci: next-js/15-app-router-saas --- .../.posthog-wizard | 0 .../integration-nextjs-app-router/SKILL.md | 59 ++ .../references/1-begin.md | 56 ++ .../references/2-edit.md | 36 + .../references/3-revise.md | 22 + .../references/4-conclude.md | 57 ++ .../references/EXAMPLE.md | 710 ++++++++++++++++++ .../references/identify-users.md | 272 +++++++ .../references/next-js.md | 383 ++++++++++ .../next-js/15-app-router-saas/.env.example | 4 +- .../next-js/15-app-router-saas/README.md | 3 + .../(dashboard)/dashboard/general/page.tsx | 11 +- .../(dashboard)/dashboard/security/page.tsx | 19 +- .../app/(dashboard)/layout.tsx | 19 +- .../app/(dashboard)/pricing/page.tsx | 3 +- .../app/(dashboard)/pricing/submit-button.tsx | 15 +- .../15-app-router-saas/app/(login)/actions.ts | 58 +- .../15-app-router-saas/app/(login)/login.tsx | 20 +- .../app/api/stripe/checkout/route.ts | 17 +- .../app/api/stripe/webhook/route.ts | 14 +- .../instrumentation-client.ts | 9 + .../lib/payments/actions.ts | 18 + .../15-app-router-saas/lib/posthog-server.ts | 39 + .../next-js/15-app-router-saas/next.config.ts | 27 +- .../next-js/15-app-router-saas/package.json | 2 + .../next-js/15-app-router-saas/pnpm-lock.yaml | 111 +++ .../posthog-setup-report.md | 44 ++ 27 files changed, 2007 insertions(+), 21 deletions(-) create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/.posthog-wizard create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/SKILL.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/1-begin.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/2-edit.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/3-revise.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/4-conclude.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/identify-users.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/next-js.md create mode 100644 apps/basic-integration/next-js/15-app-router-saas/instrumentation-client.ts create mode 100644 apps/basic-integration/next-js/15-app-router-saas/lib/posthog-server.ts create mode 100644 apps/basic-integration/next-js/15-app-router-saas/posthog-setup-report.md diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/.posthog-wizard b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/SKILL.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/SKILL.md new file mode 100644 index 000000000..9e7d13908 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/SKILL.md @@ -0,0 +1,59 @@ +--- +name: integration-nextjs-app-router +description: PostHog integration for Next.js App Router applications +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for Next.js App Router + +This skill helps you add PostHog analytics to Next.js App Router applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - Next.js App Router example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/next-js.md` - Next.js - docs +- `references/identify-users.md` - Identify users - docs + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## Key principles + +- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. +- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. +- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup +- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically +- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes +- Do NOT use useEffect for data transformation - calculate derived values during render instead +- Do NOT use useEffect to respond to user events - put that logic in the event handler itself +- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler +- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler +- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect +- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/1-begin.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/1-begin.md @@ -0,0 +1,56 @@ +--- +title: PostHog Setup - Begin +description: Start the event tracking setup process by analyzing the project and creating an event tracking plan +--- + +We're making an event tracking plan for this project. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. + +From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. + +Look for opportunities to track client-side events. + +**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: + + - Payment/checkout completion + - Webhook handlers + - Authentication endpoints + +Do not skip server-side events - they capture actions that cannot be tracked client-side. + +Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. + +Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. + +As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. + +## Status + +Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: + +[STATUS] Checking project structure. + +Status to report in this phase: + +- Checking project structure +- Verifying PostHog dependencies +- Generating events based on project + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/2-edit.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/2-edit.md @@ -0,0 +1,36 @@ +--- +title: PostHog Setup - Edit +description: Implement PostHog event tracking in the identified files, following best practices and the example project +--- + +For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. + +Use environment variables for PostHog keys. Do not hardcode PostHog keys. + +If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it. + +For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. + +Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. + +Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. + +It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. + +You should also add PostHog exception capture error tracking to these files where relevant. + +Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. + +Remember the documentation and example project resources you were provided at the beginning. Read them now. + +## Status + +Status to report in this phase: + +- Inserting PostHog capture code +- A status message for each file whose edits you are planning, including a high level summary of changes +- A status message for each file you have edited + +--- + +**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/3-revise.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/3-revise.md @@ -0,0 +1,22 @@ +--- +title: PostHog Setup - Revise +description: Review and fix any errors in the PostHog integration implementation +--- + +Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. + +Ensure that any components created were actually used. + +Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. + +## Status + +Status to report in this phase: + +- Finding and correcting errors +- Report details of any errors you fix +- Linting, building and prettying + +--- + +**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/4-conclude.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/4-conclude.md new file mode 100644 index 000000000..d876d4353 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/4-conclude.md @@ -0,0 +1,57 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Use the PostHog MCP to create a new dashboard named "Analytics basics (wizard)" based on the events created here. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: + + +# PostHog post-wizard report + +The wizard has completed a deep integration of your project. [Detailed summary of changes] + +[table of events/descriptions/files] + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +[links] + +## Verify before merging + +[checklist] + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +Upon completion, remove .posthog-events.json. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Created setup report: [insert full local file path] \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md new file mode 100644 index 000000000..9bb8aef02 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md @@ -0,0 +1,710 @@ +# PostHog Next.js App Router Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/next-app-router + +--- + +## README.md + +# PostHog Next.js app router example + +This is a [Next.js](https://nextjs.org) App Router example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking. + +## Features + +- **Product analytics**: Track user events and behaviors +- **Session replay**: Record and replay user sessions +- **Error tracking**: Capture and track errors +- **User authentication**: Demo login system with PostHog user identification +- **Server-side & Client-side tracking**: Examples of both tracking methods +- **Reverse proxy**: PostHog ingestion through Next.js rewrites + +## Getting started + +### 1. Install dependencies + +```bash +npm install +# or +pnpm install +``` + +### 2. Configure environment variables + +Create a `.env.local` file in the root directory: + +```bash +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +### 3. Run the development server + +```bash +npm run dev +# or +pnpm dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. + +## Project structure + +``` +src/ +├── app/ +│ ├── api/ +│ │ └── auth/ +│ │ └── login/ +│ │ └── route.ts # Login API with server-side tracking +│ ├── burrito/ +│ │ └── page.tsx # Demo feature page with event tracking +│ ├── profile/ +│ │ └── page.tsx # User profile with error tracking demo +│ ├── layout.tsx # Root layout with providers +│ ├── page.tsx # Home/Login page +│ └── globals.css # Global styles +├── components/ +│ └── Header.tsx # Navigation header with auth state +├── contexts/ +│ └── AuthContext.tsx # Authentication context with PostHog integration +└── lib/ + └── posthog-server.ts # Server-side PostHog client + +instrumentation-client.ts # Client-side PostHog initialization +``` + +## Key integration points + +### Client-side initialization (instrumentation-client.ts) + +```typescript +import posthog from "posthog-js" + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + defaults: '2026-01-30', + capture_exceptions: true, + debug: process.env.NODE_ENV === "development", +}); +``` + +### User identification (AuthContext.tsx) + +```typescript +posthog.identify(username, { + username: username, +}); +``` + +### Event tracking (burrito/page.tsx) + +```typescript +posthog.capture('burrito_considered', { + total_considerations: count, + username: username, +}); +``` + +### Error tracking (profile/page.tsx) + +```typescript +posthog.captureException(error); +``` + +### Server-side tracking (app/api/auth/login/route.ts) + +```typescript +const posthog = getPostHogClient(); +posthog.capture({ + distinctId: username, + event: 'server_login', + properties: { ... } +}); +``` + +## App router differences from pages router + +This example uses Next.js App Router instead of Pages Router. Key differences: + +1. **File-based routing**: Pages in `src/app/` instead of `src/pages/` +2. **layout.tsx**: Root layout component wraps all pages +3. **API Routes**: Located in `src/app/api/` with `route.ts` files +4. **'use client'**: Client components need explicit directive +5. **useRouter**: From `next/navigation` instead of `next/router` +6. **Metadata**: Exported from layout/page instead of Head component +7. **Server Components**: Components are server-side by default + +## Learn more + +- [PostHog Documentation](https://posthog.com/docs) +- [Next.js App Router Documentation](https://nextjs.org/docs/app) +- [PostHog Next.js Integration Guide](https://posthog.com/docs/libraries/next-js) + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new). + +Check out the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. + +--- + +## .env.example + +```example +# PostHog Configuration +# Get your PostHog project token from: https://app.posthog.com/project/settings +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token_here +# NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +--- + +## instrumentation-client.ts + +```ts +import posthog from "posthog-js" + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + // Include the defaults option as required by PostHog + defaults: '2026-01-30', + // Enables capturing unhandled exceptions via Error Tracking + capture_exceptions: true, + // Turn on debug in development mode + debug: process.env.NODE_ENV === "development", +}); + +//IMPORTANT: Never combine this approach with other client-side PostHog initialization approaches, especially components like a PostHogProvider. instrumentation-client.ts is the correct solution for initializating client-side PostHog in Next.js 15.3+ apps. +``` + +--- + +## next.config.ts + +```ts +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ + async rewrites() { + return [ + { + source: "/ingest/static/:path*", + destination: "https://us-assets.i.posthog.com/static/:path*", + }, + { + source: "/ingest/array/:path*", + destination: "https://us-assets.i.posthog.com/array/:path*", + }, + { + source: "/ingest/:path*", + destination: "https://us.i.posthog.com/:path*", + }, + ]; + }, + // This is required to support PostHog trailing slash API requests + skipTrailingSlashRedirect: true, +}; + +export default nextConfig; + +``` + +--- + +## src/app/api/auth/login/route.ts + +```ts +import { NextResponse } from 'next/server'; +import { getPostHogClient } from '@/lib/posthog-server'; + +const users = new Map(); + +export async function POST(request: Request) { + const { username, password } = await request.json(); + + if (!username || !password) { + return NextResponse.json({ error: 'Username and password required' }, { status: 400 }); + } + + let user = users.get(username); + const isNewUser = !user; + + if (!user) { + user = { username, burritoConsiderations: 0 }; + users.set(username, user); + } + + // Capture server-side login event + const posthog = getPostHogClient(); + posthog.capture({ + distinctId: username, + event: 'server_login', + properties: { + username: username, + isNewUser: isNewUser, + source: 'api' + } + }); + + // Identify user on server side + posthog.identify({ + distinctId: username, + properties: { + username: username, + createdAt: isNewUser ? new Date().toISOString() : undefined + } + }); + + return NextResponse.json({ success: true, user }); +} +``` + +--- + +## src/app/burrito/page.tsx + +```tsx +'use client'; + +import { useState } from 'react'; +import { useAuth } from '@/contexts/AuthContext'; +import { useRouter } from 'next/navigation'; +import posthog from 'posthog-js'; + +export default function BurritoPage() { + const { user, incrementBurritoConsiderations } = useAuth(); + const router = useRouter(); + const [hasConsidered, setHasConsidered] = useState(false); + + // Redirect to home if not logged in + if (!user) { + router.push('/'); + return null; + } + + const handleConsideration = () => { + incrementBurritoConsiderations(); + setHasConsidered(true); + setTimeout(() => setHasConsidered(false), 2000); + + // Capture burrito consideration event + posthog.capture('burrito_considered', { + total_considerations: user.burritoConsiderations + 1, + username: user.username, + }); + }; + + return ( +
+

Burrito consideration zone

+

Take a moment to truly consider the potential of burritos.

+ +
+ + + {hasConsidered && ( +

+ Thank you for your consideration! Count: {user.burritoConsiderations} +

+ )} +
+ +
+

Consideration stats

+

Total considerations: {user.burritoConsiderations}

+
+
+ ); +} +``` + +--- + +## src/app/layout.tsx + +```tsx +import type { Metadata } from "next"; +import "./globals.css"; +import { AuthProvider } from "@/contexts/AuthContext"; +import Header from "@/components/Header"; + +export const metadata: Metadata = { + title: "Burrito Consideration App", + description: "Consider the potential of burritos", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + +
+
{children}
+ + + + ); +} + +``` + +--- + +## src/app/page.tsx + +```tsx +'use client'; + +import { useState } from 'react'; +import { useAuth } from '@/contexts/AuthContext'; + +export default function Home() { + const { user, login } = useAuth(); + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(''); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(''); + + try { + const success = await login(username, password); + if (success) { + setUsername(''); + setPassword(''); + } else { + setError('Please provide both username and password'); + } + } catch (err) { + console.error('Login failed:', err); + setError('An error occurred during login'); + } + }; + + if (user) { + return ( +
+

Welcome back, {user.username}!

+

You are now logged in. Feel free to explore:

+
    +
  • Consider the potential of burritos
  • +
  • View your profile and statistics
  • +
+
+ ); + } + + return ( +
+

Welcome to Burrito Consideration App

+

Please sign in to begin your burrito journey

+ +
+
+ + setUsername(e.target.value)} + placeholder="Enter any username" + /> +
+ +
+ + setPassword(e.target.value)} + placeholder="Enter any password" + /> +
+ + {error &&

{error}

} + + +
+ +

+ Note: This is a demo app. Use any username and password to sign in. +

+
+ ); +} +``` + +--- + +## src/app/profile/page.tsx + +```tsx +'use client'; + +import { useAuth } from '@/contexts/AuthContext'; +import { useRouter } from 'next/navigation'; +import posthog from 'posthog-js'; + +export default function ProfilePage() { + const { user } = useAuth(); + const router = useRouter(); + + // Redirect to home if not logged in + if (!user) { + router.push('/'); + return null; + } + + const triggerTestError = () => { + try { + throw new Error('Test error for PostHog error tracking'); + } catch (err) { + posthog.captureException(err); + console.error('Captured error:', err); + alert('Error captured and sent to PostHog!'); + } + }; + + return ( +
+

User Profile

+ +
+

Your Information

+

Username: {user.username}

+

Burrito Considerations: {user.burritoConsiderations}

+
+ +
+ +
+ +
+

Your Burrito Journey

+ {user.burritoConsiderations === 0 ? ( +

You haven't considered any burritos yet. Visit the Burrito Consideration page to start!

+ ) : user.burritoConsiderations === 1 ? ( +

You've considered the burrito potential once. Keep going!

+ ) : user.burritoConsiderations < 5 ? ( +

You're getting the hang of burrito consideration!

+ ) : user.burritoConsiderations < 10 ? ( +

You're becoming a burrito consideration expert!

+ ) : ( +

You are a true burrito consideration master! 🌯

+ )} +
+
+ ); +} +``` + +--- + +## src/components/Header.tsx + +```tsx +'use client'; + +import Link from 'next/link'; +import { useAuth } from '@/contexts/AuthContext'; + +export default function Header() { + const { user, logout } = useAuth(); + + return ( +
+
+ +
+ {user ? ( + <> + Welcome, {user.username}! + + + ) : ( + Not logged in + )} +
+
+
+ ); +} +``` + +--- + +## src/contexts/AuthContext.tsx + +```tsx +'use client'; + +import { createContext, useContext, useState, ReactNode } from 'react'; +import posthog from 'posthog-js'; + +interface User { + username: string; + burritoConsiderations: number; +} + +interface AuthContextType { + user: User | null; + login: (username: string, password: string) => Promise; + logout: () => void; + incrementBurritoConsiderations: () => void; +} + +const AuthContext = createContext(undefined); + +const users: Map = new Map(); + +export function AuthProvider({ children }: { children: ReactNode }) { + // Use lazy initializer to read from localStorage only once on mount + const [user, setUser] = useState(() => { + if (typeof window === 'undefined') return null; + + const storedUsername = localStorage.getItem('currentUser'); + if (storedUsername) { + const existingUser = users.get(storedUsername); + if (existingUser) { + return existingUser; + } + } + return null; + }); + + const login = async (username: string, password: string): Promise => { + try { + const response = await fetch('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + + if (response.ok) { + const { user: userData } = await response.json(); + + let localUser = users.get(username); + if (!localUser) { + localUser = userData as User; + users.set(username, localUser); + } + + setUser(localUser); + localStorage.setItem('currentUser', username); + + // Identify user in PostHog using username as distinct ID + posthog.identify(username, { + username: username, + }); + + // Capture login event + posthog.capture('user_logged_in', { + username: username, + }); + + return true; + } + return false; + } catch (error) { + console.error('Login error:', error); + return false; + } + }; + + const logout = () => { + // Capture logout event before resetting + posthog.capture('user_logged_out'); + posthog.reset(); + + setUser(null); + localStorage.removeItem('currentUser'); + }; + + const incrementBurritoConsiderations = () => { + if (user) { + user.burritoConsiderations++; + users.set(user.username, user); + setUser({ ...user }); + } + }; + + return ( + + {children} + + ); +} + +export function useAuth() { + const context = useContext(AuthContext); + if (context === undefined) { + throw new Error('useAuth must be used within an AuthProvider'); + } + return context; +} +``` + +--- + +## src/lib/posthog-server.ts + +```ts +import { PostHog } from 'posthog-node'; + +let posthogClient: PostHog | null = null; + +export function getPostHogClient() { + if (!posthogClient) { + posthogClient = new PostHog( + process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, + { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0 + } + ); + posthogClient.debug(true); + } + return posthogClient; +} + +export async function shutdownPostHog() { + if (posthogClient) { + await posthogClient.shutdown(); + } +} +``` + +--- + diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/identify-users.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/identify-users.md new file mode 100644 index 000000000..1417e03a8 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/identify-users.md @@ -0,0 +1,272 @@ +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/features.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/features.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/next-js.md b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/next-js.md new file mode 100644 index 000000000..4c032fcef --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/.claude/skills/integration-nextjs-app-router/references/next-js.md @@ -0,0 +1,383 @@ +# Next.js - Docs + +PostHog makes it easy to get data about traffic and usage of your [Next.js](https://nextjs.org/) app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. + +This guide walks you through integrating PostHog into your Next.js app using the [React](/docs/libraries/react.md) and the [Node.js](/docs/libraries/node.md) SDKs. + +> You can see a working example of this integration in our [Next.js demo app](https://github.com/PostHog/posthog-js/tree/main/playground/nextjs). + +Next.js has both client and server-side rendering, as well as pages and app routers. We'll cover all of these options in this guide. + +> **Try `@posthog/next` (pre-release):** A simplified Next.js integration with synchronized client/server identity, server-side flag bootstrapping, and a built-in API proxy. [Read the setup guide →](/docs/libraries/next-js/posthog-next.md) + +## Prerequisites + +To follow this guide along, you need: + +1. A PostHog instance (either [Cloud](https://app.posthog.com/signup) or [self-hosted](/docs/self-host.md)) +2. A Next.js application + +## Beta: integration via LLM + +Install PostHog for Next.js in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal. + +`npx @posthog/wizard` + +[Learn more](/wizard.md) + +Or, to integrate manually, continue with the rest of this guide. + +## Client-side setup + +Install `posthog-js` using your package manager: + +PostHog AI + +### npm + +```bash +npm install --save posthog-js +``` + +### Yarn + +```bash +yarn add posthog-js +``` + +### pnpm + +```bash +pnpm add posthog-js +``` + +### Bun + +```bash +bun add posthog-js +``` + +Add your environment variables to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your [project settings](https://app.posthog.com/project/settings). + +.env.local + +PostHog AI + +```shell +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN= +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +These values need to start with `NEXT_PUBLIC_` to be accessible on the client-side. + +## Integration + +Next.js provides the [`instrumentation-client.ts|js`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client) file for client-side setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this: + +PostHog AI + +### instrumentation-client.js + +```javascript +import posthog from 'posthog-js' +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + defaults: '2026-05-30' +}); +``` + +### instrumentation-client.ts + +```typescript +import posthog from 'posthog-js' +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + defaults: '2026-05-30' +}); +``` + +Bootstrapping with `instrumentation-client` + +When using `instrumentation-client`, the values you pass to `posthog.init` remain fixed for the entire session. This means bootstrapping only works if you evaluate flags **before your app renders** (for example, on the server). + +If you need flag values after the app has rendered, you’ll want to: + +- Evaluate the flag on the server and pass the value into your app, or +- Evaluate the flag in an earlier page/state, then store and re-use it when needed. + +Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same `distinct_id` across client and server. + +See the [bootstrapping guide](/docs/feature-flags/bootstrapping.md) for more information. + +## Identifying users + +> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +Set up a reverse proxy (recommended) + +We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers. + +We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy. + +If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md). + +Grouping products in one project (recommended) + +If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md). + +This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms. + +Add IPs to Firewall/WAF allowlists (recommended) + +For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site. + +**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253` + +**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173` + +These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots). + +## Accessing PostHog + +Once initialized in `instrumentation-client.js|ts`, import `posthog` from `posthog-js` anywhere and call the methods you need on the `posthog` object. + +JavaScript + +PostHog AI + +```javascript +"use client"; +import posthog from "posthog-js"; +export default function Home() { + return ( +
+ +
+ ); +} +``` + +### Using React hooks + +The [React feature flag hooks](/docs/libraries/react.md#feature-flags) work automatically when PostHog is initialized via `instrumentation-client.ts`. The hooks use the initialized posthog-js singleton: + +JavaScript + +PostHog AI + +```javascript +"use client"; +import { useFeatureFlagEnabled } from "@posthog/react"; +export default function FeatureComponent() { + const showNewFeature = useFeatureFlagEnabled("new-feature"); + return showNewFeature ? : ; +} +``` + +### Usage + +See the [React SDK docs](/docs/libraries/react.md) for examples of how to use: + +- [`posthog-js` functions like custom event capture, user identification, and more.](/docs/libraries/react.md#using-posthog-js-functions) +- [Feature flags including variants and payloads.](/docs/libraries/react.md#feature-flags) + +You can also read [the full `posthog-js` documentation](/docs/libraries/js/features.md) for all the usable functions. + +## Server-side analytics + +Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the [Node SDK](/docs/libraries/node.md). + +First, install the `posthog-node` library: + +PostHog AI + +### npm + +```bash +npm install posthog-node --save +``` + +### Yarn + +```bash +yarn add posthog-node +``` + +### pnpm + +```bash +pnpm add posthog-node +``` + +### Bun + +```bash +bun add posthog-node +``` + +### Router-specific instructions + +## App router + +For the app router, we can initialize the `posthog-node` SDK once with a `PostHogClient` function, and import it into files. + +This enables us to send events and fetch data from PostHog on the server – without making client-side requests. + +JavaScript + +PostHog AI + +```javascript +// app/posthog.js +import { PostHog } from 'posthog-node' +export default function PostHogClient() { + const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0 + }) + return posthogClient +} +``` + +> **Note:** Because server-side functions in Next.js can be short-lived, we set `flushAt` to `1` and `flushInterval` to `0`. +> +> - `flushAt` sets how many capture calls we should flush the queue (in one batch). +> - `flushInterval` sets how many milliseconds we should wait before flushing the queue. Setting them to the lowest number ensures events are sent immediately and not batched. We also need to call `await posthog.shutdown()` once done. + +To use this client, we import it into our pages and call it with the `PostHogClient` function: + +JavaScript + +PostHog AI + +```javascript +import Link from 'next/link' +import PostHogClient from '../posthog' +export default async function About() { + const posthog = PostHogClient() + const flags = await posthog.getAllFlags( + 'user_distinct_id' // replace with a user's distinct ID + ); + await posthog.shutdown() + return ( +
+

About

+ Go home + { flags['main-cta'] && + Go to PostHog + } +
+ ) +} +``` + +## Pages router + +For the pages router, we can use the `getServerSideProps` function to access PostHog on the server-side, send events, evaluate feature flags, and more. + +This looks like this: + +JavaScript + +PostHog AI + +```javascript +// pages/posts/[id].js +import { useContext, useEffect, useState } from 'react' +import { getServerSession } from "next-auth/next" +import { PostHog } from 'posthog-node' +export default function Post({ post, flags }) { + const [ctaState, setCtaState] = useState() + useEffect(() => { + if (flags) { + setCtaState(flags['blog-cta']) + } + }) + return ( +
+

{post.title}

+

By: {post.author}

+

{post.content}

+ {ctaState && +

Go to PostHog

+ } + +
+ ) +} +export async function getServerSideProps(ctx) { + const session = await getServerSession(ctx.req, ctx.res) + let flags = null + if (session) { + const client = new PostHog( + process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, + { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + } + ) + flags = await client.getAllFlags(session.user.email); + client.capture({ + distinctId: session.user.email, + event: 'loaded blog article', + properties: { + $current_url: ctx.req.url, + }, + }); + await client.shutdown() + } + const { posts } = await import('../../blog.json') + const post = posts.find((post) => post.id.toString() === ctx.params.id) + return { + props: { + post, + flags + }, + } +} +``` + +> **Note**: Make sure to *always* call `await client.shutdown()` after sending events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately. + +### Server-side configuration + +Next.js overrides the default `fetch` behavior on the server to introduce their own cache. PostHog ignores that cache by default, as this is Next.js's default behavior for any fetch call. + +You can override that configuration when initializing PostHog, but make sure you understand the pros/cons of using Next.js's cache and that you might get cached results rather than the actual result our server would return. This is important for feature flags, for example. + +TSX + +PostHog AI + +```jsx +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + // ... your configuration + fetch_options: { + cache: 'force-cache', // Use Next.js cache + next_options: { // Passed to the `next` option for `fetch` + revalidate: 60, // Cache for 60 seconds + tags: ['posthog'], // Can be used with Next.js `revalidateTag` function + }, + } +}) +``` + +## Configuring a reverse proxy to PostHog + +To improve the reliability of client-side tracking and make requests less likely to be intercepted by tracking blockers, you can setup a reverse proxy in Next.js. Read more about deploying a reverse proxy using [Next.js rewrites](/docs/advanced/proxy/nextjs.md), [Next.js middleware](/docs/advanced/proxy/nextjs-middleware.md), and [Vercel rewrites](/docs/advanced/proxy/vercel.md). + +## Further reading + +- [How to set up Next.js analytics, feature flags, and more](/tutorials/nextjs-analytics.md) +- [How to set up Next.js pages router analytics, feature flags, and more](/tutorials/nextjs-pages-analytics.md) +- [How to set up Next.js A/B tests](/tutorials/nextjs-ab-tests.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/next-js/15-app-router-saas/.env.example b/apps/basic-integration/next-js/15-app-router-saas/.env.example index 9f67031a4..5d9d493ef 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/.env.example +++ b/apps/basic-integration/next-js/15-app-router-saas/.env.example @@ -8,4 +8,6 @@ AUTH_SECRET=*** # Stripe Stub Mode (optional) # Set to 'stub' to use mock Stripe implementation without real API keys -# STRIPE_MODE=stub \ No newline at end of file +# STRIPE_MODE=stub +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com diff --git a/apps/basic-integration/next-js/15-app-router-saas/README.md b/apps/basic-integration/next-js/15-app-router-saas/README.md index 093d91d2e..c563dbb9d 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/README.md +++ b/apps/basic-integration/next-js/15-app-router-saas/README.md @@ -15,6 +15,7 @@ This is a starter template for building a SaaS application using **Next.js** wit - Global middleware to protect logged-in routes - Local middleware to protect Server Actions or validate Zod schemas - Activity logging system for any user events +- PostHog product analytics with client-side and server-side event capture ## Tech Stack @@ -107,6 +108,8 @@ In your Vercel project settings (or during deployment), add all the necessary en 3. `STRIPE_WEBHOOK_SECRET`: Use the webhook secret from the production webhook you created in step 1. 4. `POSTGRES_URL`: Set this to your production database URL. 5. `AUTH_SECRET`: Set this to a random string. `openssl rand -base64 32` will generate one. +6. `NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN`: Set this to your PostHog project token. +7. `NEXT_PUBLIC_POSTHOG_HOST`: Set this to your PostHog host URL. ## Other Templates diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx index e3e0165aa..e37f2574f 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useActionState } from 'react'; +import { useActionState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; @@ -8,6 +8,7 @@ import { Label } from '@/components/ui/label'; import { Loader2 } from 'lucide-react'; import { updateAccount } from '@/app/(login)/actions'; import { User } from '@/lib/db/schema'; +import posthog from 'posthog-js'; import useSWR from 'swr'; import { Suspense } from 'react'; @@ -78,6 +79,14 @@ export default function GeneralPage() { {} ); + useEffect(() => { + if (state.success) { + posthog.capture('account_updated', { + source: 'general_settings' + }); + } + }, [state.success]); + return (

diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/security/page.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/security/page.tsx index 642b072da..c008e574f 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/security/page.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/dashboard/security/page.tsx @@ -5,7 +5,8 @@ import { Input } from '@/components/ui/input'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Label } from '@/components/ui/label'; import { Lock, Trash2, Loader2 } from 'lucide-react'; -import { useActionState } from 'react'; +import posthog from 'posthog-js'; +import { useActionState, useEffect } from 'react'; import { updatePassword, deleteAccount } from '@/app/(login)/actions'; type PasswordState = { @@ -33,6 +34,22 @@ export default function SecurityPage() { FormData >(deleteAccount, {}); + useEffect(() => { + if (passwordState.success) { + posthog.capture('password_updated', { + source: 'security_settings' + }); + } + }, [passwordState.success]); + + useEffect(() => { + if (isDeletePending) { + posthog.capture('account_deletion_requested', { + source: 'security_settings' + }); + } + }, [isDeletePending]); + return (

diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/layout.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/layout.tsx index 5e1d0b1b2..aa00a0e01 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/layout.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/layout.tsx @@ -1,7 +1,7 @@ 'use client'; import Link from 'next/link'; -import { use, useState, Suspense } from 'react'; +import { useEffect, useState, Suspense } from 'react'; import { Button } from '@/components/ui/button'; import { CircleIcon, Home, LogOut } from 'lucide-react'; import { @@ -14,6 +14,7 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { signOut } from '@/app/(login)/actions'; import { useRouter } from 'next/navigation'; import { User } from '@/lib/db/schema'; +import posthog from 'posthog-js'; import useSWR, { mutate } from 'swr'; const fetcher = (url: string) => fetch(url).then((res) => res.json()); @@ -24,11 +25,27 @@ function UserMenu() { const router = useRouter(); async function handleSignOut() { + posthog.capture('user_signed_out', { + source: 'dashboard_header' + }); + posthog.reset(); await signOut(); mutate('/api/user'); router.push('/'); } + useEffect(() => { + if (!user) { + return; + } + + posthog.identify(user.email, { + email: user.email, + name: user.name ?? undefined, + role: user.role + }); + }, [user]); + if (!user) { return ( <> diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/page.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/page.tsx index 234cbf5ed..bfb3905cd 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/page.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/page.tsx @@ -87,7 +87,8 @@ function PricingCard({
- + + ); diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/submit-button.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/submit-button.tsx index aa04ea9db..5c54db10e 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/submit-button.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(dashboard)/pricing/submit-button.tsx @@ -2,9 +2,15 @@ import { Button } from '@/components/ui/button'; import { ArrowRight, Loader2 } from 'lucide-react'; +import posthog from 'posthog-js'; import { useFormStatus } from 'react-dom'; -export function SubmitButton() { +type SubmitButtonProps = { + planName: string; + priceId?: string; +}; + +export function SubmitButton({ planName, priceId }: SubmitButtonProps) { const { pending } = useFormStatus(); return ( @@ -13,6 +19,13 @@ export function SubmitButton() { disabled={pending} variant="outline" className="w-full rounded-full" + onClick={() => { + posthog.capture('pricing_cta_clicked', { + plan_name: planName, + price_id: priceId ?? null, + source: 'pricing_page' + }); + }} > {pending ? ( <> diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(login)/actions.ts b/apps/basic-integration/next-js/15-app-router-saas/app/(login)/actions.ts index 532adc0ef..b418ef518 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(login)/actions.ts +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(login)/actions.ts @@ -21,6 +21,7 @@ import { redirect } from 'next/navigation'; import { cookies } from 'next/headers'; import { createCheckoutSession } from '@/lib/payments/stripe'; import { getUser, getUserWithTeam } from '@/lib/db/queries'; +import { captureServerEvent } from '@/lib/posthog-server'; import { validatedAction, validatedActionWithUser @@ -88,7 +89,15 @@ export const signIn = validatedAction(signInSchema, async (data, formData) => { await Promise.all([ setSession(foundUser), - logActivity(foundTeam?.id, foundUser.id, ActivityType.SIGN_IN) + logActivity(foundTeam?.id, foundUser.id, ActivityType.SIGN_IN), + captureServerEvent({ + distinctId: foundUser.id.toString(), + event: 'server_user_signed_in', + properties: { + team_id: foundTeam?.id ?? null, + redirect_to: formData.get('redirect') ?? null + } + }) ]); const redirectTo = formData.get('redirect') as string | null; @@ -209,7 +218,15 @@ export const signUp = validatedAction(signUpSchema, async (data, formData) => { await Promise.all([ db.insert(teamMembers).values(newTeamMember), logActivity(teamId, createdUser.id, ActivityType.SIGN_UP), - setSession(createdUser) + setSession(createdUser), + captureServerEvent({ + distinctId: createdUser.id.toString(), + event: 'server_user_signed_up', + properties: { + team_id: teamId, + invited_signup: Boolean(inviteId) + } + }) ]); const redirectTo = formData.get('redirect') as string | null; @@ -279,7 +296,15 @@ export const updatePassword = validatedActionWithUser( .update(users) .set({ passwordHash: newPasswordHash }) .where(eq(users.id, user.id)), - logActivity(userWithTeam?.teamId, user.id, ActivityType.UPDATE_PASSWORD) + logActivity(userWithTeam?.teamId, user.id, ActivityType.UPDATE_PASSWORD), + captureServerEvent({ + distinctId: user.id.toString(), + event: 'password_updated', + properties: { + team_id: userWithTeam?.teamId ?? null, + source: 'security_settings' + } + }) ]); return { @@ -307,11 +332,17 @@ export const deleteAccount = validatedActionWithUser( const userWithTeam = await getUserWithTeam(user.id); - await logActivity( - userWithTeam?.teamId, - user.id, - ActivityType.DELETE_ACCOUNT - ); + await Promise.all([ + logActivity(userWithTeam?.teamId, user.id, ActivityType.DELETE_ACCOUNT), + captureServerEvent({ + distinctId: user.id.toString(), + event: 'account_deletion_requested', + properties: { + team_id: userWithTeam?.teamId ?? null, + source: 'security_settings' + } + }) + ]); // Soft delete await db @@ -351,7 +382,16 @@ export const updateAccount = validatedActionWithUser( await Promise.all([ db.update(users).set({ name, email }).where(eq(users.id, user.id)), - logActivity(userWithTeam?.teamId, user.id, ActivityType.UPDATE_ACCOUNT) + logActivity(userWithTeam?.teamId, user.id, ActivityType.UPDATE_ACCOUNT), + captureServerEvent({ + distinctId: user.id.toString(), + event: 'account_updated', + properties: { + team_id: userWithTeam?.teamId ?? null, + has_name: Boolean(name), + source: 'general_settings' + } + }) ]); return { name, success: 'Account updated successfully.' }; diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/(login)/login.tsx b/apps/basic-integration/next-js/15-app-router-saas/app/(login)/login.tsx index 86c7e280d..c4a4b2d9e 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/(login)/login.tsx +++ b/apps/basic-integration/next-js/15-app-router-saas/app/(login)/login.tsx @@ -1,12 +1,13 @@ 'use client'; import Link from 'next/link'; -import { useActionState } from 'react'; +import { useActionState, useState } from 'react'; import { useSearchParams } from 'next/navigation'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { CircleIcon, Loader2 } from 'lucide-react'; +import posthog from 'posthog-js'; import { signIn, signUp } from './actions'; import { ActionState } from '@/lib/auth/middleware'; @@ -15,6 +16,7 @@ export function Login({ mode = 'signin' }: { mode?: 'signin' | 'signup' }) { const redirect = searchParams.get('redirect'); const priceId = searchParams.get('priceId'); const inviteId = searchParams.get('inviteId'); + const [email, setEmail] = useState(''); const [state, formAction, pending] = useActionState( mode === 'signin' ? signIn : signUp, { error: '' } @@ -52,6 +54,7 @@ export function Login({ mode = 'signin' }: { mode?: 'signin' | 'signup' }) { type="email" autoComplete="email" defaultValue={state.email} + onChange={(event) => setEmail(event.target.value)} required maxLength={50} className="appearance-none rounded-full relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-orange-500 focus:border-orange-500 focus:z-10 sm:text-sm" @@ -94,6 +97,21 @@ export function Login({ mode = 'signin' }: { mode?: 'signin' | 'signup' }) { type="submit" className="w-full flex justify-center items-center py-2 px-4 border border-transparent rounded-full shadow-sm text-sm font-medium text-white bg-orange-600 hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500" disabled={pending} + onClick={() => { + if (!email) { + return; + } + + posthog.identify(email, { + email + }); + posthog.capture( + mode === 'signin' ? 'user_signed_in' : 'user_signed_up', + { + source: mode === 'signin' ? 'sign_in_page' : 'sign_up_page' + } + ); + }} > {pending ? ( <> diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/checkout/route.ts b/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/checkout/route.ts index d1eba26fd..b1bcb3bc5 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/checkout/route.ts +++ b/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/checkout/route.ts @@ -5,6 +5,7 @@ import { setSession } from '@/lib/auth/session'; import { NextRequest, NextResponse } from 'next/server'; import { stripe } from '@/lib/payments/stripe'; import Stripe from 'stripe'; +import { captureServerEvent } from '@/lib/posthog-server'; export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams; @@ -88,7 +89,21 @@ export async function GET(request: NextRequest) { }) .where(eq(teams.id, userTeam[0].teamId)); - await setSession(user[0]); + await Promise.all([ + setSession(user[0]), + captureServerEvent({ + distinctId: user[0].id.toString(), + event: 'checkout_completed', + properties: { + team_id: userTeam[0].teamId, + stripe_customer_id: customerId, + stripe_subscription_id: subscriptionId, + plan_name: (plan.product as Stripe.Product).name, + subscription_status: subscription.status + } + }) + ]); + return NextResponse.redirect(new URL('/dashboard', request.url)); } catch (error) { console.error('Error handling successful checkout:', error); diff --git a/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/webhook/route.ts b/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/webhook/route.ts index 446066dc9..417ea81bb 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/webhook/route.ts +++ b/apps/basic-integration/next-js/15-app-router-saas/app/api/stripe/webhook/route.ts @@ -1,6 +1,7 @@ import Stripe from 'stripe'; import { handleSubscriptionChange, stripe } from '@/lib/payments/stripe'; import { NextRequest, NextResponse } from 'next/server'; +import { captureServerEvent } from '@/lib/posthog-server'; // Use a dummy webhook secret for stub mode const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || 'whsec_stub_secret'; @@ -25,7 +26,18 @@ export async function POST(request: NextRequest) { case 'customer.subscription.updated': case 'customer.subscription.deleted': const subscription = event.data.object as Stripe.Subscription; - await handleSubscriptionChange(subscription); + await Promise.all([ + handleSubscriptionChange(subscription), + captureServerEvent({ + distinctId: String(subscription.customer), + event: 'stripe_subscription_updated', + properties: { + event_type: event.type, + stripe_subscription_id: subscription.id, + subscription_status: subscription.status + } + }) + ]); break; default: console.log(`Unhandled event type ${event.type}`); diff --git a/apps/basic-integration/next-js/15-app-router-saas/instrumentation-client.ts b/apps/basic-integration/next-js/15-app-router-saas/instrumentation-client.ts new file mode 100644 index 000000000..ac3e74603 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/instrumentation-client.ts @@ -0,0 +1,9 @@ +import posthog from 'posthog-js'; + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: '/ingest', + ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + defaults: '2026-05-30', + capture_exceptions: true, + debug: process.env.NODE_ENV === 'development' +}); diff --git a/apps/basic-integration/next-js/15-app-router-saas/lib/payments/actions.ts b/apps/basic-integration/next-js/15-app-router-saas/lib/payments/actions.ts index 26492c19e..14187c32d 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/lib/payments/actions.ts +++ b/apps/basic-integration/next-js/15-app-router-saas/lib/payments/actions.ts @@ -3,9 +3,27 @@ import { redirect } from 'next/navigation'; import { createCheckoutSession, createCustomerPortalSession } from './stripe'; import { withTeam } from '@/lib/auth/middleware'; +import { getUser } from '@/lib/db/queries'; +import { captureServerEvent } from '@/lib/posthog-server'; export const checkoutAction = withTeam(async (formData, team) => { const priceId = formData.get('priceId') as string; + const planName = formData.get('planName') as string | null; + const user = await getUser(); + + if (user) { + await captureServerEvent({ + distinctId: user.id.toString(), + event: 'checkout_session_started', + properties: { + team_id: team.id, + price_id: priceId, + plan_name: planName, + source: 'pricing_page' + } + }); + } + await createCheckoutSession({ team: team, priceId }); }); diff --git a/apps/basic-integration/next-js/15-app-router-saas/lib/posthog-server.ts b/apps/basic-integration/next-js/15-app-router-saas/lib/posthog-server.ts new file mode 100644 index 000000000..85cc8768b --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/lib/posthog-server.ts @@ -0,0 +1,39 @@ +import { PostHog } from 'posthog-node'; + +let posthogClient: PostHog | null = null; + +export function getPostHogClient() { + if (!posthogClient) { + posthogClient = new PostHog( + process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, + { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0 + } + ); + } + + return posthogClient; +} + +export async function captureServerEvent({ + distinctId, + event, + properties +}: { + distinctId: string; + event: string; + properties?: Record; +}) { + const posthog = getPostHogClient(); + + posthog.capture({ + distinctId, + event, + properties + }); + + await posthog.shutdown(); + posthogClient = null; +} diff --git a/apps/basic-integration/next-js/15-app-router-saas/next.config.ts b/apps/basic-integration/next-js/15-app-router-saas/next.config.ts index fd4fd4546..e18e97270 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/next.config.ts +++ b/apps/basic-integration/next-js/15-app-router-saas/next.config.ts @@ -1,9 +1,30 @@ import type { NextConfig } from 'next'; +const posthogHost = process.env.NEXT_PUBLIC_POSTHOG_HOST; +const posthogAssetHost = posthogHost?.replace('i.', 'assets.i.'); + const nextConfig: NextConfig = { - // Configuration for stable Next.js 15 - // To enable experimental features like PPR, upgrade to canary: - // pnpm add next@canary + async rewrites() { + if (!posthogHost || !posthogAssetHost) { + return []; + } + + return [ + { + source: '/ingest/static/:path*', + destination: `${posthogAssetHost}/static/:path*` + }, + { + source: '/ingest/array/:path*', + destination: `${posthogAssetHost}/array/:path*` + }, + { + source: '/ingest/:path*', + destination: `${posthogHost}/:path*` + } + ]; + }, + skipTrailingSlashRedirect: true }; export default nextConfig; diff --git a/apps/basic-integration/next-js/15-app-router-saas/package.json b/apps/basic-integration/next-js/15-app-router-saas/package.json index 020d334a4..ccc4a13cb 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/package.json +++ b/apps/basic-integration/next-js/15-app-router-saas/package.json @@ -27,6 +27,8 @@ "next": "15.5.7", "postcss": "^8.5.3", "postgres": "^3.4.5", + "posthog-js": "^1.396.6", + "posthog-node": "^5.39.4", "radix-ui": "^1.4.2", "react": "19.1.2", "react-dom": "19.1.2", diff --git a/apps/basic-integration/next-js/15-app-router-saas/pnpm-lock.yaml b/apps/basic-integration/next-js/15-app-router-saas/pnpm-lock.yaml index c4753ff95..aa3f15f22 100644 --- a/apps/basic-integration/next-js/15-app-router-saas/pnpm-lock.yaml +++ b/apps/basic-integration/next-js/15-app-router-saas/pnpm-lock.yaml @@ -56,6 +56,12 @@ importers: postgres: specifier: ^3.4.5 version: 3.4.5 + posthog-js: + specifier: ^1.396.6 + version: 1.396.6 + posthog-node: + specifier: ^5.39.4 + version: 5.39.4 radix-ui: specifier: ^1.4.2 version: 1.4.2(@types/react-dom@19.1.5(@types/react@19.1.4))(@types/react@19.1.4)(react-dom@19.1.2(react@19.1.2))(react@19.1.2) @@ -441,89 +447,105 @@ packages: resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-arm@1.2.4': resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-ppc64@1.2.4': resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} cpu: [ppc64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-riscv64@1.2.4': resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} cpu: [riscv64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-s390x@1.2.4': resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-libvips-linux-x64@1.2.4': resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-libvips-linuxmusl-arm64@1.2.4': resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-libvips-linuxmusl-x64@1.2.4': resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-linux-arm64@0.34.5': resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [glibc] '@img/sharp-linux-arm@0.34.5': resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm] os: [linux] + libc: [glibc] '@img/sharp-linux-ppc64@0.34.5': resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [ppc64] os: [linux] + libc: [glibc] '@img/sharp-linux-riscv64@0.34.5': resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [riscv64] os: [linux] + libc: [glibc] '@img/sharp-linux-s390x@0.34.5': resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [s390x] os: [linux] + libc: [glibc] '@img/sharp-linux-x64@0.34.5': resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [glibc] '@img/sharp-linuxmusl-arm64@0.34.5': resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [arm64] os: [linux] + libc: [musl] '@img/sharp-linuxmusl-x64@0.34.5': resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} cpu: [x64] os: [linux] + libc: [musl] '@img/sharp-wasm32@0.34.5': resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} @@ -590,24 +612,28 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@next/swc-linux-arm64-musl@15.5.7': resolution: {integrity: sha512-nfymt+SE5cvtTrG9u1wdoxBr9bVB7mtKTcj0ltRn6gkP/2Nu1zM5ei8rwP9qKQP0Y//umK+TtkKgNtfboBxRrw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@next/swc-linux-x64-gnu@15.5.7': resolution: {integrity: sha512-hvXcZvCaaEbCZcVzcY7E1uXN9xWZfFvkNHwbe/n4OkRhFWrs1J1QV+4U1BN06tXLdaS4DazEGXwgqnu/VMcmqw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@next/swc-linux-x64-musl@15.5.7': resolution: {integrity: sha512-4IUO539b8FmF0odY6/SqANJdgwn1xs1GkPO5doZugwZ3ETF6JUdckk7RGmsfSf7ws8Qb2YB5It33mvNL/0acqA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@next/swc-win32-arm64-msvc@15.5.7': resolution: {integrity: sha512-CpJVTkYI3ZajQkC5vajM7/ApKJUOlm6uP4BknM3XKvJ7VXAvCqSjSLmM0LKdYzn6nBJVSjdclx8nYJSa3xlTgQ==} @@ -624,6 +650,12 @@ packages: '@petamoriken/float16@3.9.2': resolution: {integrity: sha512-VgffxawQde93xKxT3qap3OH+meZf7VaSB5Sqd4Rqc+FP5alWbpOyan/7tRbOAvynjpG3GpdtAuGU/NdhQpmrog==} + '@posthog/core@1.39.6': + resolution: {integrity: sha512-o6ajIwN5zXoNP0D4H/QPmOyibNTUkSyOR6ya7AG5U2ywXx4awo72L2KnCoiZPQM5x/bXv6jPBdimH8M18Ax0aw==} + + '@posthog/types@1.392.1': + resolution: {integrity: sha512-Qg6Gl7/1vlr8+gPtBi5gwnLgAgiyFoKOVmTvTtDcvya9cpTwZfna7rQmkGQ4B63CunUYNNbOlqcwiUwUDyTK6w==} + '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -1355,24 +1387,28 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.1.7': resolution: {integrity: sha512-PjGuNNmJeKHnP58M7XyjJyla8LPo+RmwHQpBI+W/OxqrwojyuCQ+GUtygu7jUqTEexejZHr/z3nBc/gTiXBj4A==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.1.7': resolution: {integrity: sha512-HMs+Va+ZR3gC3mLZE00gXxtBo3JoSQxtu9lobbZd+DmfkIxR54NO7Z+UQNPsa0P/ITn1TevtFxXTpsRU7qEvWg==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.1.7': resolution: {integrity: sha512-MHZ6jyNlutdHH8rd+YTdr3QbXrHXqwIhHw9e7yXEBcQdluGwhpQY2Eku8UZK6ReLaWtQ4gijIv5QoM5eE+qlsA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.1.7': resolution: {integrity: sha512-ANaSKt74ZRzE2TvJmUcbFQ8zS201cIPxUDm5qez5rLEwWkie2SkGtA4P+GPTj+u8N6JbPrC8MtY8RmJA35Oo+A==} @@ -1416,6 +1452,9 @@ packages: '@types/react@19.1.4': resolution: {integrity: sha512-EB1yiiYdvySuIITtD5lhW4yPyJ31RkJkkDw794LaQYrxCSaQV/47y5o1FMC4zF9ZyjUjzJMZwbovEnT5yHTW6g==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + aria-hidden@1.2.4: resolution: {integrity: sha512-y+CcFFwelSXpLZk/7fMB2mUbGtX9lKycf1MWJ7CaTIERyitVlyQx6C+sxcROU2BAJ24OiZyK+8wj2i8AlBoS3A==} engines: {node: '>=10'} @@ -1464,6 +1503,9 @@ packages: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} + core-js@3.49.0: + resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==} + csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} @@ -1491,6 +1533,9 @@ packages: detect-node-es@1.1.0: resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==} + dompurify@3.4.11: + resolution: {integrity: sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==} + dotenv@16.5.0: resolution: {integrity: sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==} engines: {node: '>=12'} @@ -1634,6 +1679,9 @@ packages: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} + fflate@0.4.8: + resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==} + fraction.js@4.3.7: resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==} @@ -1715,24 +1763,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.30.1: resolution: {integrity: sha512-jmUQVx4331m6LIX+0wUhBbmMX7TCfjF5FoOH6SD1CttzuYlGNVpA7QnrmLxrsub43ClTINfGSYyHe2HWeLl5CQ==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.30.1: resolution: {integrity: sha512-piWx3z4wN8J8z3+O5kO74+yr6ze/dKmPnI7vLqfSqI8bccaTGY5xiSGVIJBDd5K5BHlvVLpUB3S2YCfelyJ1bw==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.30.1: resolution: {integrity: sha512-rRomAK7eIkL+tHY0YPxbc5Dra2gXlI63HL+v1Pdi1a3sC+tJTcFrHX+E86sulgAXeI7rSzDYhPSeHHjqFhqfeQ==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.30.1: resolution: {integrity: sha512-mSL4rqPi4iXq5YVqzSsJgMVFENoa4nGTT/GjO2c0Yl9OuQfPsIfncvLrEW6RbbB24WtZ3xP/2CCmI3tNkNV4oA==} @@ -1833,10 +1885,28 @@ packages: resolution: {integrity: sha512-cDWgoah1Gez9rN3H4165peY9qfpEo+SA61oQv65O3cRUE1pOEoJWwddwcqKE8XZYjbblOJlYDlLV4h67HrEVDg==} engines: {node: '>=12'} + posthog-js@1.396.6: + resolution: {integrity: sha512-ARI5k7sXak74lmSWGQ4Wwk+uEkpM0Za+KTc/1E6EVk6BIo916VS9tzVAQ6IinDPuPu+ODFlFb9/5gVHnOaY4Uw==} + + posthog-node@5.39.4: + resolution: {integrity: sha512-+fCQ7htBFRQQFbIzl1T0TA7bDwYyaB9XP308ZFMCUoB5LzTzOFxBa6TYVrxdH/VQl43WXTp6sf0QsG2Z4XlNBg==} + engines: {node: ^20.20.0 || >=22.22.0} + peerDependencies: + rxjs: ^7.0.0 + peerDependenciesMeta: + rxjs: + optional: true + + preact@10.29.4: + resolution: {integrity: sha512-GMpwh9+NJ8tSmqwIaVyFRQkiKfBEzQ+k7r7tle4W+kaJ+7wJiB9hFz9BixAomMtenPPSBfM4bZhXozGxhf0uFQ==} + qs@6.14.0: resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==} engines: {node: '>=0.6'} + query-selector-shadow-dom@1.0.1: + resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + radix-ui@1.4.2: resolution: {integrity: sha512-fT/3YFPJzf2WUpqDoQi005GS8EpCi+53VhcLaHUj5fwkPYiZAjk1mSxFvbMA8Uq71L03n+WysuYC+mlKkXxt/Q==} peerDependencies: @@ -2024,6 +2094,9 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + web-vitals@5.3.0: + resolution: {integrity: sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==} + which@4.0.0: resolution: {integrity: sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg==} engines: {node: ^16.13.0 || >=18.0.0} @@ -2367,6 +2440,12 @@ snapshots: '@petamoriken/float16@3.9.2': optional: true + '@posthog/core@1.39.6': + dependencies: + '@posthog/types': 1.392.1 + + '@posthog/types@1.392.1': {} + '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.1.2': {} @@ -3202,6 +3281,9 @@ snapshots: dependencies: csstype: 3.1.3 + '@types/trusted-types@2.0.7': + optional: true + aria-hidden@1.2.4: dependencies: tslib: 2.8.1 @@ -3249,6 +3331,8 @@ snapshots: clsx@2.1.1: {} + core-js@3.49.0: {} + csstype@3.1.3: {} debug@4.4.1: @@ -3264,6 +3348,10 @@ snapshots: detect-node-es@1.1.0: {} + dompurify@3.4.11: + optionalDependencies: + '@types/trusted-types': 2.0.7 + dotenv@16.5.0: {} drizzle-kit@0.31.1: @@ -3366,6 +3454,8 @@ snapshots: escalade@3.2.0: {} + fflate@0.4.8: {} + fraction.js@4.3.7: {} function-bind@1.1.2: {} @@ -3537,10 +3627,29 @@ snapshots: postgres@3.4.5: {} + posthog-js@1.396.6: + dependencies: + '@posthog/core': 1.39.6 + '@posthog/types': 1.392.1 + core-js: 3.49.0 + dompurify: 3.4.11 + fflate: 0.4.8 + preact: 10.29.4 + query-selector-shadow-dom: 1.0.1 + web-vitals: 5.3.0 + + posthog-node@5.39.4: + dependencies: + '@posthog/core': 1.39.6 + + preact@10.29.4: {} + qs@6.14.0: dependencies: side-channel: 1.1.0 + query-selector-shadow-dom@1.0.1: {} + radix-ui@1.4.2(@types/react-dom@19.1.5(@types/react@19.1.4))(@types/react@19.1.4)(react-dom@19.1.2(react@19.1.2))(react@19.1.2): dependencies: '@radix-ui/primitive': 1.1.2 @@ -3784,6 +3893,8 @@ snapshots: dependencies: react: 19.1.2 + web-vitals@5.3.0: {} + which@4.0.0: dependencies: isexe: 3.1.1 diff --git a/apps/basic-integration/next-js/15-app-router-saas/posthog-setup-report.md b/apps/basic-integration/next-js/15-app-router-saas/posthog-setup-report.md new file mode 100644 index 000000000..ab6f4b232 --- /dev/null +++ b/apps/basic-integration/next-js/15-app-router-saas/posthog-setup-report.md @@ -0,0 +1,44 @@ + +# PostHog post-wizard report + +The wizard has completed a deep integration of this Next.js App Router SaaS starter with PostHog product analytics. The setup adds client-side initialization through `instrumentation-client.ts`, a reverse-proxy rewrite in `next.config.ts`, a reusable server capture helper in `lib/posthog-server.ts`, client identification on auth and returning dashboard sessions, and targeted event capture across authentication, pricing, account management, security settings, checkout completion, and Stripe webhook processing. Documentation and env examples were also updated to include the new PostHog configuration. + +| Event name | Description | File | +| --- | --- | --- | +| `user_signed_in` | Captures authentication form submissions for sign in and identifies the returning user. | `app/(login)/login.tsx` | +| `user_signed_up` | Captures authentication form submissions for account creation and identifies the new user. | `app/(login)/login.tsx` | +| `pricing_cta_clicked` | Captures plan selection from the pricing page before checkout begins. | `app/(dashboard)/pricing/submit-button.tsx` | +| `account_updated` | Captures successful account profile updates from the general settings page. | `app/(dashboard)/dashboard/general/page.tsx` | +| `password_updated` | Captures successful password changes from the security settings page. | `app/(dashboard)/dashboard/security/page.tsx` | +| `account_deletion_requested` | Captures account deletion requests from the security settings page. | `app/(dashboard)/dashboard/security/page.tsx` | +| `user_signed_out` | Captures logout actions from the dashboard header and resets the client identity. | `app/(dashboard)/layout.tsx` | +| `server_user_signed_in` | Captures successful sign in events on the server for authenticated users. | `app/(login)/actions.ts` | +| `server_user_signed_up` | Captures successful sign up events on the server for new accounts. | `app/(login)/actions.ts` | +| `checkout_session_started` | Captures server-side checkout session creation for subscription upgrades. | `lib/payments/actions.ts` | +| `checkout_completed` | Captures successful Stripe checkout completions after subscription activation. | `app/api/stripe/checkout/route.ts` | +| `stripe_subscription_updated` | Captures Stripe webhook subscription updates and deletions on the server. | `app/api/stripe/webhook/route.ts` | + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +- Dashboard: https://us.posthog.com/project/483112/dashboard/1796219 +- Insight: Sign-up to checkout funnel — https://us.posthog.com/project/483112/insights/2ihsSuO6 +- Insight: Authentication activity trend — https://us.posthog.com/project/483112/insights/g3IFM8pH +- Insight: Account management actions — https://us.posthog.com/project/483112/insights/6VeqYiwY +- Insight: Billing pipeline activity — https://us.posthog.com/project/483112/insights/KYmEAiVr +- Insight: Pricing CTA volume — https://us.posthog.com/project/483112/insights/r7sYt46m + +## Verify before merging + +- [ ] Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code. +- [ ] Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures. +- [ ] Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set. +- [ ] Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify. +- [ ] Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs. + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + +