Next.js web analytics installation
Install the PostHog JavaScript library using your package manager: Add your PostHog API key and host to your Choose the integration method based on your Next.js version and router type. If you're using Next.js 15.3+, you can use For the App router, create a Then import the For the Pages router, integrate PostHog at the root of your app in The Once initialized in Use the To capture events from API routes or server actions, install 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: You can also use PostHog in server actions: For the Pages router, use PostHog in your API routes: Always call 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: After 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.Install the package
RequiredAdd environment variables
Required.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.Initialize PostHog
Requiredinstrumentation-client.ts for a lightweight, fast integration:providers.tsx file in your app folder. The posthog-js library needs to be initialized on the client-side using the 'use client' directive:PostHogProvider component in your app/layout.tsx and wrap your app with it:pages/_app.tsx:defaults option automatically configures PostHog with recommended settings for new projects. See SDK defaults for details.Accessing PostHog on the client
Recommendedinstrumentation-client.ts, import posthog from posthog-js anywhere and call the methods you need:usePostHog hook to access PostHog in client components:Server-side setup
Optionalposthog-node: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.Send events
RecommendedNext steps
Recommended