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.
Copy link to headingWhy choose Next.js, Vercel, and PostHog?
- 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.
Copy link to headingSetting Up PostHog with Next.js
Copy link to heading1. Create a Next.js Application
After ensuring Node.js is installed:
Copy link to heading2. Adding PostHog
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:
Add posthog-js to your project and then configure PostHost by creating a new Client Component to instantiate the provider:
Finally, consume the provider inside your root layout, which is a Server Component.
Copy link to heading3. Using PostHog with React Server Components
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:
Copy link to heading4. Setting Up Feature Flags
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:
Copy link to headingDeploying on Vercel
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.
- Set up Vercel with your GitHub repository
- Push changes to GitHub
- Clone and deploy your repository
- Add the Environment Variables you created earlier
- Your site is now online!