# Next.js experiments installation - Docs

1.  1

    ## Install the package

    Required

    Install the PostHog JavaScript library using your package manager:

    PostHog AI

    ### npm

    ```bash
    npm install posthog-js
    ```

    ### yarn

    ```bash
    yarn add posthog-js
    ```

    ### pnpm

    ```bash
    pnpm add posthog-js
    ```

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

    PostHog AI

    ```bash
    NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=<ph_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

    PostHog AI

    ```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-01-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

    PostHog AI

    ```typescript
    'use client'
    import { usePathname, useSearchParams } from "next/navigation"
    import { useEffect } from "react"
    import posthog from 'posthog-js'
    import { PostHogProvider as PHProvider } from 'posthog-js/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-01-30'
        })
      }, [])
      return (
        <PHProvider client={posthog}>
          {children}
        </PHProvider>
      )
    }
    ```

    Then import the `PostHogProvider` component in your `app/layout.tsx` and wrap your app with it:

    app/layout.tsx

    PostHog AI

    ```typescript
    import './globals.css'
    import { PostHogProvider } from './providers'
    export default function RootLayout({ children }: { children: React.ReactNode }) {
      return (
        <html lang="en">
          <body>
            <PostHogProvider>
              {children}
            </PostHogProvider>
          </body>
        </html>
      )
    }
    ```

    ## Pages router

    For the Pages router, integrate PostHog at the root of your app in `pages/_app.tsx`:

    pages/\_app.tsx

    PostHog AI

    ```typescript
    import { useEffect } from 'react'
    import { Router } from 'next/router'
    import posthog from 'posthog-js'
    import { PostHogProvider } from 'posthog-js/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-01-30',
          loaded: (posthog) => {
            if (process.env.NODE_ENV === 'development') posthog.debug()
          }
        })
      }, [])
      return (
        <PostHogProvider client={posthog}>
          <Component {...pageProps} />
        </PostHogProvider>
      )
    }
    ```

    **Defaults option**

    The `defaults` option automatically configures PostHog with recommended settings for new projects. See [SDK defaults](/docs/libraries/js.md#sdk-defaults) for details.

4.  4

    ## Implement your experiment

    Required

    Experiments run on top of our feature flags. You can define which version of your code runs based on the return value of the feature flag:

    ## Client-side

    For client-side experiments in React components, you can use the `useFeatureFlagVariantKey` hook or the `PostHogFeature` component:

    ```jsx
    // You can either use the useFeatureFlagVariantKey hook,
    // or you can use the feature flags component - https://posthog.com/docs/libraries/react#feature-flags-react-component
    // Method one: using the useFeatureFlagVariantKey hook
    import { useFeatureFlagVariantKey } from 'posthog-js/react'
    function App() {
        const variant = useFeatureFlagVariantKey('your-experiment-feature-flag')
        if (variant === 'test') {
            // do something
        }
    }
    // Method two: using the feature flags component
    import { PostHogFeature } from 'posthog-js/react'
    function App() {
        return (
            <PostHogFeature flag='your-experiment-feature-flag' match='test'>
                <div>
                    {/* the component to show */}
                </div>
            </PostHogFeature>
        )
    }
    // You can also test your code by overriding the feature flag:
    posthog.featureFlags.overrideFeatureFlags({ flags: {'your-experiment-feature-flag': 'test'} })
    ```

    ## Server-side

    For server-side experiments in API routes or server actions, use `posthog-node`:

    ```javascript
    const experimentFlagValue = await client.getFeatureFlag('your-experiment-feature-flag', 'user distinct id')
    if (experimentFlagValue === 'test' ) {
        // Do something differently for this user
    } else {
        // It's a good idea to let control variant always be the default behaviour,
        // so if something goes wrong with flag evaluation, you don't break your app.
    }
    ```

5.  5

    ## Run your experiment

    Required

    Once you've implemented the feature flag in your code, you'll enable it for a target audience by creating a new experiment in the PostHog dashboard.

6.  6

    ## Next steps

    Recommended

    Now that you're running experiments, continue with the resources below to learn what else Experiments enables within the PostHog platform.

    | Resource | Description |
    | --- | --- |
    | [Creating an experiment](/docs/experiments/creating-an-experiment.md) | How to create an experiment in PostHog |
    | [Adding experiment code](/docs/experiments/adding-experiment-code.md) | How to implement experiments for all platforms |
    | [Statistical significance](/docs/experiments/statistics-bayesian.md) | Understanding when results are meaningful |
    | [Experiment insights](/docs/experiments/analyzing-results.md) | How to analyze your experiment data |
    | [More tutorials](/docs/experiments/tutorials.md) | Other real-world examples and use cases |

### Community questions

Ask a question

### Was this page useful?

HelpfulCould be better