Using PostHog with the Next.js App Router and Vercel

Learn how to use PostHog with Next.js and Vercel to add analytics, feature flags, and more.
Last updated on August 13, 2023
FrameworksDatabases & CMS

PostHog is an open-source, developer-friendly product analytics platform. Combined with Next.js and Vercel, developers can easily track events, set up feature flags, and gain insights into their customer traffic.

  • Next.js: A powerful React framework for building dynamic, high-performance UIs. With the App Router, server-side experimentation and personalization are made easy with React Server Components.
  • Vercel: A frontend cloud providing the frameworks, workflows, and infrastructure to build a faster, more personalized web. Vercel created and maintains Next.js.
  • PostHog: PostHog is an open-source, developer-friendly product analytics platform. It respects user privacy and gives you full control over your data.

This guide will show how to use these tools together on both the client and server.

After ensuring Node.js is installed:

npx create-next-app@latest next-app
cd next-app
npm run dev
Creating a new Next.js application to get started.

Sign up for a PostHog instance to obtain your project API key and instance address. Add your API key and address to a .env.local:

.env.local
NEXT_PUBLIC_POSTHOG_KEY="your-api-key"
NEXT_PUBLIC_POSTHOG_HOST="your-ph-address"
Using NEXT_PUBLIC_ prefix makes the environment variables available on the client.

Add posthog-js to your project and then configure PostHost by creating a new Client Component to instantiate the provider:

app/providers.js
'use client'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
if (typeof window !== 'undefined') {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST
})
}
export function PHProvider({ children }) {
return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}
Create a new PostHog provider in a Client Component.

Finally, consume the provider inside your root layout, which is a Server Component.

app/layout.js
import './globals.css'
import { PHProvider } from './providers'
export const metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<PHProvider>
<body>{children}</body>
</PHProvider>
</html>
)
}
Your root layout in the Next.js App Router.

The Next.js App Router uses React Server Components by default. This provides a number of benefits, including running code server-only that is not included in the client-side JavaScript bundle.

To use PostHost on the server, you can use the PostHog Node SDK to access features like server-side rendered feature flags. First, install posthog-node and then use the following:

app/page.js
import { PostHog } from 'posthog-node'
const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
})
export default function Page() {
posthog.capture({
distinctId: '[email protected]',
event: 'Page was loaded'
})
return '...'
}
Using Posthog to capture server-side events with React Server Components.

You can access feature flags in PostHog to conditionally render content from Next.js. First, create a flag inside PostHog with the key my_flag. This flag should be rolled out to 100% of your traffic.

Inside your Next.js application, you can read the flag as follows:

app/page.js
import { PostHog } from 'posthog-node'
const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
})
export default async function Page() {
const flags = await posthog.getAllFlags(
'[email protected]' // replace with a user's distinct ID
);
return (
flags.my_flag ? <p>On</p> : <p>Off</p>
)
}
Reading feature flags inside of a React Server Component in Next.js.

Now that your Next.js application is integrated with PostHog for capturing events and handling feature flags, you can deploy to Vercel's frontend cloud.

  1. Set up Vercel with your GitHub repository
  2. Push changes to GitHub
  3. Clone and deploy your repository
  4. Add the Environment Variables you created earlier
  5. Your site is now online!

Couldn't find the guide you need?