Next.js experiments installation
- 1
Install the package
RequiredInstall the PostHog JavaScript library using your package manager:
- 2
Add environment variables
RequiredAdd your PostHog API key and host to your
.env.localfile and to your hosting provider (e.g. Vercel, Netlify). These values need to start withNEXT_PUBLIC_to be accessible on the client-side..env.local - 3
Initialize PostHog
RequiredChoose the integration method based on your Next.js version and router type.
If you're using Next.js 15.3+, you can use
instrumentation-client.tsfor a lightweight, fast integration:instrumentation-client.tsFor the App router, create a
providers.tsxfile in yourappfolder. Theposthog-jslibrary needs to be initialized on the client-side using the'use client'directive:app/providers.tsxThen import the
PostHogProvidercomponent in yourapp/layout.tsxand wrap your app with it:app/layout.tsxFor the Pages router, integrate PostHog at the root of your app in
pages/_app.tsx:pages/_app.tsxDefaults optionThe
defaultsoption automatically configures PostHog with recommended settings for new projects. See SDK defaults for details. - 4
Implement your experiment
RequiredExperiments 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:
For client-side experiments in React components, you can use the
useFeatureFlagVariantKeyhook or thePostHogFeaturecomponent:For server-side experiments in API routes or server actions, use
posthog-node: - 5
Run your experiment
RequiredOnce 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
Next steps
RecommendedNow 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 How to create an experiment in PostHog Adding experiment code How to implement experiments for all platforms Statistical significance Understanding when results are meaningful Experiment insights How to analyze your experiment data More tutorials Other real-world examples and use cases