Using the PostHog Analytics Provider in Next.js Supabase Turbo
Learn how to use the PostHog Analytics provider in Next.js Supabase Turbo
The Posthog provider in Next.js Supabase Turbo is a simple way to integrate PostHog Analytics into your Next.js application using the Makerkit's Analytics package.
Installation
First, you need to pull the @kit/analytics
package into your project using the CLI
npx @makerkit/cli@latest plugins install
When prompted, select the PostHog
package from the list of available packages. Once the command completes, you should see the packages/plugins/posthog
directory in your project.
You can now import this package into your project:
pnpm add "@kit/posthog@workspace:*" --filter "@kit/analytics" -D
You can now use the Google Analytics plugin in the Analytics package. Update the packages/analytics/src/index.ts
file as follows:
import { createPostHogAnalyticsService } from '@kit/posthog';import { createAnalyticsManager } from './analytics-manager';import type { AnalyticsManager } from './types';export const analytics: AnalyticsManager = createAnalyticsManager({ providers: { posthog: createPostHogAnalyticsService, },});
Configuration
Please add the following environment variables to your .env
file:
NEXT_PUBLIC_POSTHOG_KEY=phc_your_key_hereNEXT_PUBLIC_POSTHOG_HOST=https://eu.posthog.comNEXT_PUBLIC_POSTHOG_INGESTION_URL=http://localhost:3000/ingest
Ingestion Rewrites
In your apps/web/next.config.mjs file, add the following config:
/** @type {import('next').NextConfig} */const config = { // ...other config // This is required to support PostHog trailing slash API requests skipTrailingSlashRedirect: true, async rewrites() { // NOTE: change `eu` to `us` if applicable return [ { source: '/ingest/static/:path*', destination: 'https://eu-assets.i.posthog.com/static/:path*' }, { source: '/ingest/:path*', destination: 'https://eu.i.posthog.com/:path*' } ]; }}
CSRF Exclusion
In your apps/web/middleware.ts
file, exclude the PostHog ingestion URL from CSRF protection:
export const config = { matcher: ['/((?!_next/static|_next/image|images|locales|assets|ingest/*|api/*).*)'],};