This project demonstrates how to integrate PostHog analytics with a Next.js application using the App Router. It includes examples of both client-side and server-side event tracking.
First, install the dependencies:
npm install
Then, run the development server:
NEXT_PUBLIC_POSTHOG_KEY='<your-posthog-api-key>' npm run dev
Open http://localhost:3000 with your browser to see the result.
This demo project showcases:
- Client-side event tracking using the
usePostHog
hook - Server-side event tracking using the PostHog Node.js library
- Integration of PostHog with Next.js App Router
The main page (/
) contains links to two sample pages:
/client-event
: Demonstrates client-side event tracking/server-event
: Demonstrates server-side event tracking
The project uses the following environment variables:
NEXT_PUBLIC_POSTHOG_KEY
: Your PostHog API keyNEXT_PUBLIC_POSTHOG_HOST
: The PostHog host (optional, defaults to 'https://app.posthog.com')
You can set these in a .env.local
file or provide them when running the development server.
If you're running PostHog locally, you can point the project to your local instance:
NEXT_PUBLIC_POSTHOG_KEY='<your-local-api-key>' NEXT_PUBLIC_POSTHOG_HOST='http://localhost:8000' npm run dev
If you need to test local changes to the posthog-js
library, you can use npm link:
-
In your local
posthog-js
directory:npm link
-
In this project's directory:
npm link posthog-js
-
Run the development server with your environment variables:
NEXT_PUBLIC_POSTHOG_KEY='<your-api-key>' NEXT_PUBLIC_POSTHOG_HOST='http://localhost:8000' npm run dev
To learn more about Next.js and PostHog, check out the following resources:
You can deploy this Next.js app using Vercel or any other Next.js-compatible hosting platform.
Remember to set your environment variables in your deployment platform's settings.