Next.js web analytics 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
Accessing PostHog on the client
RecommendedOnce initialized in
instrumentation-client.ts, importposthogfromposthog-jsanywhere and call the methods you need:app/checkout/page.tsxUse the
usePostHoghook to access PostHog in client components:app/checkout/page.tsx - 5
Server-side setup
OptionalTo capture events from API routes or server actions, install
posthog-node:Then, initialize PostHog in your API route or server action. Choose the method based on your router type:
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.tsYou can also use PostHog in server actions:
app/actions.tsFor the Pages router, use PostHog in your API routes:
pages/api/example.tsImportantAlways 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
Send events
RecommendedClick 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 - 7
Next steps
RecommendedAfter installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.
PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.