+
+ );
+}
+```
+
+---
+
+## 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_KEY!,
+ {
+ 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/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.0-begin.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.0-begin.md
new file mode 100644
index 00000000..953ead2d
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.0-begin.md
@@ -0,0 +1,43 @@
+---
+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.
+
+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.
+
+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: event name, event description, and the file path we want to place the event in. 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
+
+
+---
+
+**Upon completion, continue with:** [basic-integration-1.1-edit.md](basic-integration-1.1-edit.md)
\ No newline at end of file
diff --git a/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.1-edit.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.1-edit.md
new file mode 100644
index 00000000..44c1a4e9
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.1-edit.md
@@ -0,0 +1,37 @@
+---
+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.
+
+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:** [basic-integration-1.2-revise.md](basic-integration-1.2-revise.md)
\ No newline at end of file
diff --git a/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.2-revise.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.2-revise.md
new file mode 100644
index 00000000..26f3a60e
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.2-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.
+
+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.
+
+## 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:** [basic-integration-1.3-conclude.md](basic-integration-1.3-conclude.md)
\ No newline at end of file
diff --git a/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.3-conclude.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.3-conclude.md
new file mode 100644
index 00000000..552118fb
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/basic-integration-1.3-conclude.md
@@ -0,0 +1,36 @@
+---
+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" based on the events created here. 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.
+
+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, along with a list of links for the dashboard and insights created. 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]
+
+### 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.
+
+
+
+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/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/identify-users.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/identify-users.md
new file mode 100644
index 00000000..ce165453
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/identify-users.md
@@ -0,0 +1,202 @@
+# 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#capturing-events.md) or [mobile app](/docs/libraries/ios#capturing-events.md), 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#capturing-anonymous-events.md).
+
+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
+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 user is already authenticated on the mobile app. In this case, call [`posthog.alias()`](/docs/libraries/js/features#alias.md) with the distinct ID from the web. This associates the two distinct IDs as a single person.
+- The user is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features#identifying-users.md) with the distinct ID from the web. Events will be associated with this distinct ID.
+
+As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms.
+
+## Further reading
+
+- [Identifying users docs](/docs/product-analytics/identify.md)
+- [How person processing works](/docs/how-posthog-works/ingestion-pipeline#2-person-processing.md)
+- [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/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/next-js.md b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/next-js.md
new file mode 100644
index 00000000..dd1f78ac
--- /dev/null
+++ b/apps/next-js/15-app-router-saas/.claude/skills/nextjs-app-router/references/next-js.md
@@ -0,0 +1,622 @@
+# 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.
+
+## 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.
+
+prompt
+
+PostHog AI
+
+```prompt
+npx -y @posthog/wizard@latest --region us
+```
+
+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 API key in your [project settings](https://app.posthog.com/project/settings).
+
+.env.local
+
+PostHog AI
+
+```shell
+NEXT_PUBLIC_POSTHOG_KEY=
+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 15.3+ provides the [`instrumentation-client.ts|js`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client) file for a quick, lightweight 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_KEY, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30'
+});
+```
+
+### instrumentation-client.ts
+
+```typescript
+import posthog from 'posthog-js'
+posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30'
+});
+```
+
+Using Next.js 15.2 or older?
+
+Older versions of Next.js don't support the `instrumentation-client.ts|js` file. You can use the following setup instead:
+
+## App router
+
+If your Next.js app uses the [app router](https://nextjs.org/docs/app), you can integrate PostHog by creating a `providers` file in your app folder. This is because the `posthog-js` library needs to be initialized on the client-side using the Next.js [`'use client'` directive](https://nextjs.org/docs/app/getting-started/server-and-client-components).
+
+PostHog AI
+
+### JSX
+
+```jsx
+// app/providers.jsx
+'use client'
+import posthog from 'posthog-js'
+import { PostHogProvider as PHProvider } from '@posthog/react'
+import { useEffect } from 'react'
+export function PostHogProvider({ children }) {
+ useEffect(() => {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30',
+ })
+ }, [])
+ return (
+
+ {children}
+
+ )
+}
+```
+
+### TSX
+
+```jsx
+// app/providers.tsx
+'use client'
+import posthog from 'posthog-js'
+import { PostHogProvider as PHProvider } from '@posthog/react'
+import { useEffect } from 'react'
+export function PostHogProvider({ children }: { children: React.ReactNode }) {
+ useEffect(() => {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30',
+ })
+ }, [])
+ return (
+
+ {children}
+
+ )
+}
+```
+
+Then, import the `PostHogProvider` component into your `app/layout` file and wrap your app with it.
+
+PostHog AI
+
+### JSX
+
+```jsx
+// app/layout.jsx
+import './globals.css'
+import { PostHogProvider } from './providers'
+export default function RootLayout({ children }) {
+ return (
+
+
+
+ {children}
+
+
+
+ )
+}
+```
+
+### TSX
+
+```jsx
+// app/layout.tsx
+import './globals.css'
+import { PostHogProvider } from './providers'
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+
+
+
+ {children}
+
+
+
+ )
+}
+```
+
+PostHog is now set up and ready to go. It will begin to autocapture events and pageviews. Files and components accessing PostHog on the client-side need the `'use client'` directive.
+
+## Pages router
+
+If you use the [pages router](https://nextjs.org/docs/pages), you can integrate PostHog at the root of your app in `pages/_app.js`.
+
+JavaScript
+
+PostHog AI
+
+```javascript
+// pages/_app.js
+import { useEffect } from 'react'
+import posthog from 'posthog-js'
+import { PostHogProvider } from '@posthog/react'
+export default function App({ Component, pageProps }) {
+ useEffect(() => {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
+ defaults: '2025-11-30',
+ // Enable debug mode in development
+ loaded: (posthog) => {
+ if (process.env.NODE_ENV === 'development') posthog.debug()
+ }
+ })
+ }, [])
+ return (
+
+
+
+ )
+}
+```
+
+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.
+
+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 included in the platform packages](/docs/advanced/proxy/managed-reverse-proxy.md), which 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
+
+## Instrumentation client
+
+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 (
+
+
+
+ );
+}
+```
+
+## PostHog provider
+
+PostHog can be accessed throughout your Next.js app by using the `usePostHog` hook.
+
+JavaScript
+
+PostHog AI
+
+```javascript
+'use client'
+import { usePostHog } from '@posthog/react'
+export default function Home() {
+ const posthog = usePostHog()
+ return (
+
+
+
+ );
+}
+```
+
+### 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#using-posthog-js-functions.md)
+- [Feature flags including variants and payloads.](/docs/libraries/react#feature-flags.md)
+
+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_KEY, {
+ 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 (
+
+ )
+}
+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_KEY,
+ {
+ 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_KEY, {
+ // ... 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).
+
+## Frequently asked questions
+
+### Does wrapping my app in the PostHog provider de-opt it to client-side rendering?
+
+No. Even though the PostHog provider is a client component, since we pass the `children` prop to it, any component inside the children tree can still be a server component. Next.js creates a boundary between server-run and client-run code.
+
+The [`use client` reference](https://react.dev/reference/rsc/use-client) says that it "defines the boundary between server and client code on the module dependency tree, not the render tree." It also says that "During render, the framework will server-render the root component and continue through the render tree, opting-out of evaluating any code imported from client-marked code."
+
+Pages router components are client components by default.
+
+### What does wrapping my app in the PostHog provider do?
+
+On top of the standard features like autocapture, custom events, session recording, and more, wrapping your app in the PostHog provider gives you:
+
+1. The `usePostHog`, `useFeatureFlagEnabled`, and other hooks in any component.
+2. A PostHog context you can access in any component.
+3. The `` component which simplifies feature flag logic.
+
+See the [React SDK docs](/docs/libraries/react.md) for more details.
+
+### Why use a `useEffect` hook to initialize PostHog in the provider?
+
+We want to initialize PostHog when the app is loaded. The [React docs](https://react.dev/learn/synchronizing-with-effects) recommend using a `useEffect` hook to do this:
+
+> Effects let you specify side effects that are caused by rendering itself, rather than by a particular event.
+
+Technically, you can also use a `window` object check to initialize PostHog. This happens outside the React lifecycle, meaning it happens earlier and it looks like this:
+
+PostHog AI
+
+### JavaScript
+
+```javascript
+// app/providers.js
+'use client'
+import posthog from 'posthog-js'
+import { PostHogProvider } from '@posthog/react'
+if (typeof window !== 'undefined') {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ capture_pageview: false // Disable automatic pageview capture, as we capture manually
+ })
+}
+export function PHProvider({ children }) {
+ return {children}
+}
+```
+
+### TSX
+
+```jsx
+// app/providers.tsx
+'use client'
+import posthog from 'posthog-js'
+import { PostHogProvider } from '@posthog/react'
+if (typeof window !== 'undefined') {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ capture_pageview: false // Disable automatic pageview capture, as we capture manually
+ })
+}
+export function PHProvider({
+ children,
+}: {
+ children: React.ReactNode
+}) {
+ return {children}
+}
+```
+
+The problem with this is that it can cause a [hydration and/or mismatch error](https://nextjs.org/docs/messages/react-hydration-error) like `Warning: Prop dangerouslySetInnerHTML did not match.`.
+
+### Why did the pageview component need a `useEffect`?
+
+Before updating the JavaScript Web SDK's default behavior when capturing pageviews (`'2025-11-30'`), we suggested using a `useEffect` hook to capture pageviews. This is because it's the simplest way to accurately capture pageviews. Other approaches include:
+
+1. Not using a `useEffect` hook, but this might lead to duplicate page views being tracked if the component re-renders for reasons other than navigation. It might work depending on your implementation.
+2. Using `window.navigation` to track pageviews, but this approach is more complex and is [not supported](https://developer.mozilla.org/en-US/docs/Web/API/Window/navigation) in all browsers.
+
+> **Note:** This approach of manually capturing pageviews is no longer recommended. We recommend using `defaults: '2025-11-30'` or `capture_pageview: 'history_change'` instead, which automatically handles both `$pageview` and `$pageleave` events.
+>
+> If you're still capturing pageviews manually, you should also capture `$pageleave` events to track important engagement metrics like time on page (`$prev_pageview_duration`) and scroll depth (`$prev_pageview_max_scroll_percentage`). To do this, set up a listener on window unload (similar to [how PostHog does it](https://github.com/PostHog/posthog-js/blob/main/packages/browser/src/posthog-core.ts#L644-L646)):
+>
+> JavaScript
+>
+> PostHog AI
+>
+> ```javascript
+> useEffect(() => {
+> const handlePageLeave = () => {
+> posthog.capture('$pageleave', null, { transport: 'sendBeacon' })
+> }
+> // Use pagehide if available for better reliability, otherwise fallback to unload
+> const event = 'onpagehide' in window ? 'pagehide' : 'unload'
+> window.addEventListener(event, handlePageLeave)
+> return () => window.removeEventListener(event, handlePageLeave)
+> }, [])
+> ```
+>
+> Using `sendBeacon` ensures the event is sent even when users quickly close tabs. See our [time on page tutorial](/tutorials/time-on-page.md) for more details on using these metrics.
+
+## 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/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx b/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx
index e3e0165a..743efd00 100644
--- a/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx
+++ b/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/general/page.tsx
@@ -10,6 +10,7 @@ import { updateAccount } from '@/app/(login)/actions';
import { User } from '@/lib/db/schema';
import useSWR from 'swr';
import { Suspense } from 'react';
+import posthog from 'posthog-js';
const fetcher = (url: string) => fetch(url).then((res) => res.json());
@@ -103,6 +104,7 @@ export default function GeneralPage() {
type="submit"
className="bg-orange-500 hover:bg-orange-600 text-white"
disabled={isPending}
+ onClick={() => posthog.capture('account_updated')}
>
{isPending ? (
<>
diff --git a/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/page.tsx b/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/page.tsx
index 60475a85..cd78a255 100644
--- a/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/page.tsx
+++ b/apps/next-js/15-app-router-saas/app/(dashboard)/dashboard/page.tsx
@@ -10,7 +10,7 @@ import {
CardFooter
} from '@/components/ui/card';
import { customerPortalAction } from '@/lib/payments/actions';
-import { useActionState } from 'react';
+import { useActionState, useRef } from 'react';
import { TeamDataWithMembers, User } from '@/lib/db/schema';
import { removeTeamMember, inviteTeamMember } from '@/app/(login)/actions';
import useSWR from 'swr';
@@ -19,6 +19,7 @@ import { Input } from '@/components/ui/input';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { Loader2, PlusCircle } from 'lucide-react';
+import posthog from 'posthog-js';
type ActionState = {
error?: string;
@@ -61,7 +62,11 @@ function ManageSubscription() {