If you are using Next.js and want to track your application using PostHog this tutorial might help you out.
It will guide you through an example integration of PostHog using Next.js and the posthog-js library.
Is this tutorial for me?
This tutorial is aimed at Next.js users. We are going to look at some minimal example code which should get you started quickly.
Prerequisites
To follow this tutorial along, you need to:
- Have a self-hosted instance of PostHog or use PostHog Cloud.
- Have a running Next.js application
Setup and tracking page views (automatically)
The first thing you want to do is to install the next-use-posthog library in your project - so add it using your package manager:
yarn add next-use-posthog
or
npm install --save next-use-posthog
After that, we want to initialize the PostHog instance in pages/_app.js
import { usePostHog } from 'next-use-posthog'function MyApp({ Component, pageProps }) {// NOTE: If set as an environment variable be sure to prefix with `NEXT_PUBLIC_`// For more info see https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browserusePostHog('<ph_project_api_key>', { api_host: '<ph_instance_address>' })return <Component {...pageProps} />}export default MyApp
Disable in development
import { usePostHog } from 'next-use-posthog'function MyApp({ Component, pageProps }) {usePostHog('<ph_project_api_key>', {api_host: '<ph_instance_address>',loaded: (posthog) => {if (process.env.NODE_ENV === 'development') posthog.opt_out_capturing()},})return <Component {...pageProps} />}export default MyApp
Setup and tracking page views (manually)
The first thing you want to do is to install the posthog-js library in your project - so add it using your package manager:
yarn add posthog-js
or
npm install --save posthog-js
After that, we want to initialize the PostHog instance in pages/_app.js
import { useRouter } from 'next/router';import posthog from 'posthog-js';import { useEffect } from 'react';function MyApp({ Component, pageProps }) {const router = useRouter();useEffect(() => {// Init PostHogposthog.init('<ph_project_api_key>', { api_host: '<ph_instance_address>' });// Track page viewsconst handleRouteChange = () => posthog.capture('$pageview');router.events.on('routeChangeComplete', handleRouteChange);return () => {router.events.off('routeChangeComplete', handleRouteChange);};}, []);return <Component {...pageProps} />;}export default MyApp;
Tracking custom events
const handleOnBuy = () => {posthog.capture('purchase', { price: 5900, currency: 'USD' });};return (<main><h1>Store</h1><button onClick={handleOnBuy}>Buy</button></main>);