> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Next.js Surveys installation Canonical URL: https://posthog.com/docs/surveys/installation/nextjs > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). ## On this page - [Install with the wizard](#install-with-the-wizard) - [Install the package](#install-the-package) - [Add environment variables](#add-environment-variables) - [Initialize PostHog](#initialize-posthog) - [Accessing PostHog on the client](#accessing-posthog-on-the-client) - [Server-side setup](#server-side-setup) - [Send events](#send-events) - [Next steps](#next-steps) ## Install with the wizard Run this command in your project directory to add PostHog to your Next.js project. The wizard detects your framework, installs the SDK, and sets up your first events. `npx @posthog/wizard` Or set it up manually by following the rest of this guide. 1. 1 ## Install the package Required Install the PostHog JavaScript library using your package manager: ### npm ```bash npm install posthog-js@1 ``` ### yarn ```bash yarn add posthog-js@1 ``` ### pnpm ```bash pnpm add posthog-js@1 ``` ### bun ```bash bun add posthog-js@1 ``` 2. 2 ## Add environment variables Required Add your PostHog project token and host to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify). These values need to start with `NEXT_PUBLIC_` to be accessible on the client-side. .env.local ```bash NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN= NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com ``` 3. 3 ## Initialize PostHog Required Choose the integration method based on your Next.js version and router type. ## Next.js 15.3+ If you're using Next.js 15.3+, you can use `instrumentation-client.ts` for a lightweight, fast integration: 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-08-30' }) ``` ## App router For the App router, create a `providers.tsx` file in your `app` folder. The `posthog-js` library needs to be initialized on the client-side using the `'use client'` directive: app/providers.tsx ```typescript 'use client' import { usePathname, useSearchParams } from "next/navigation" import { useEffect } from "react" import posthog from 'posthog-js' import { PostHogProvider as PHProvider } from '@posthog/react' export function PostHogProvider({ children }: { children: React.ReactNode }) { useEffect(() => { posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN as string, { api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, defaults: '2026-08-30' }) }, []) return ( {children} ) } ``` Then import the `PostHogProvider` component in your `app/layout.tsx` and wrap your app with it: app/layout.tsx ```typescript import './globals.css' import { PostHogProvider } from './providers' export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ) } ``` ## Pages router For the Pages router, integrate PostHog at the root of your app in `pages/_app.tsx`: pages/\_app.tsx ```typescript import { useEffect } from 'react' import { Router } from 'next/router' import posthog from 'posthog-js' import { PostHogProvider } from '@posthog/react' import type { AppProps } from 'next/app' export default function App({ Component, pageProps }: AppProps) { useEffect(() => { posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN as string, { api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, defaults: '2026-08-30', loaded: (posthog) => { if (process.env.NODE_ENV === 'development') posthog.debug() } }) }, []) return ( ) } ``` **Defaults option** The `defaults` option automatically configures PostHog with recommended settings for new projects. See [SDK defaults](https://posthog.com/docs/libraries/js.md#sdk-defaults) for details. 4. 4 ## Accessing PostHog on the client Recommended ## Next.js 15.3+ Once initialized in `instrumentation-client.ts`, import `posthog` from `posthog-js` anywhere and call the methods you need: app/checkout/page.tsx ```typescript 'use client' import posthog from 'posthog-js' export default function CheckoutPage() { function handlePurchase() { posthog.capture('purchase_completed', { amount: 99 }) } return } ``` ## App/Pages router Use the `usePostHog` hook to access PostHog in client components: app/checkout/page.tsx ```typescript 'use client' import { usePostHog } from '@posthog/react' export default function CheckoutPage() { const posthog = usePostHog() function handlePurchase() { posthog.capture('purchase_completed', { amount: 99 }) } return } ``` 5. 5 ## Server-side setup Optional To capture events from API routes or server actions, install `posthog-node`: ### npm ```bash npm install posthog-node@5 ``` ### yarn ```bash yarn add posthog-node@5 ``` ### pnpm ```bash pnpm add posthog-node@5 ``` ### bun ```bash bun add posthog-node@5 ``` Then, initialize PostHog in your API route or server action. Choose the method based on your router type: ## App router For the App router, you can use PostHog in API routes or server actions. Create a new PostHog client instance for each request, or reuse a singleton instance across requests: app/api/example/route.ts ```typescript import { PostHog } from 'posthog-node' export async function POST(request: Request) { const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { host: process.env.NEXT_PUBLIC_POSTHOG_HOST }) posthog.capture({ distinctId: 'distinct_id_of_the_user', event: 'event_name' }) await posthog.shutdown() } ``` You can also use PostHog in server actions: app/actions.ts ```typescript 'use server' import { PostHog } from 'posthog-node' export async function myServerAction() { const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { host: process.env.NEXT_PUBLIC_POSTHOG_HOST }) posthog.capture({ distinctId: 'distinct_id_of_the_user', event: 'server_action_completed' }) await posthog.shutdown() } ``` ## Pages router For the Pages router, use PostHog in your API routes: pages/api/example.ts ```typescript import { PostHog } from 'posthog-node' import type { NextApiRequest, NextApiResponse } from 'next' export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { host: process.env.NEXT_PUBLIC_POSTHOG_HOST }) posthog.capture({ distinctId: 'distinct_id_of_the_user', event: 'event_name' }) await posthog.shutdown() res.status(200).json({ success: true }) } ``` **Important** Always call `await posthog.shutdown()` when you're done with the client to ensure all events are flushed before the request completes. For better performance, consider creating a singleton PostHog instance that you reuse across requests. 6. 6 ## Send events Recommended Click around and view a couple pages to generate some events. PostHog automatically captures pageviews, clicks, and other interactions for you. If you'd like, you can also manually capture custom events: JavaScript ```javascript posthog.capture('my_custom_event', { property: 'value' }) ``` 7. 7 ## Next steps Recommended After installing the PostHog SDK, you can create your first survey. | Resource | Description | | --- | --- | | [Creating surveys](https://posthog.com/docs/surveys/creating-surveys.md) | Learn how to build and customize your surveys | | [Targeting surveys](https://posthog.com/docs/surveys/targeting.md) | Show surveys to specific users based on properties, events, or feature flags | | [How to create custom surveys](https://posthog.com/tutorials/survey.md) | Build advanced survey experiences with custom code | | [Framework guides](https://posthog.com/docs/surveys/tutorials.md#framework-guides) | Setup guides for React, Next.js, Vue, and other frameworks | | [More tutorials](https://posthog.com/docs/surveys/tutorials.md) | Other real-world examples and use cases | You should also [identify](https://posthog.com/docs/product-analytics/identify.md) users and [capture events](https://posthog.com/docs/product-analytics/capture-events.md) with PostHog to control who and when to show surveys to your users. Not all survey features are available on every SDK. See the [SDK feature support matrix](https://posthog.com/docs/surveys/sdk-feature-support.md) for a full comparison.