Skip to content

Instantly share code, notes, and snippets.

@finnmglas
Created September 10, 2025 14:02
Show Gist options
  • Select an option

  • Save finnmglas/9d067fd85ec777bfdb431ff5c916444a to your computer and use it in GitHub Desktop.

Select an option

Save finnmglas/9d067fd85ec777bfdb431ff5c916444a to your computer and use it in GitHub Desktop.
Basic posthog provider to integrate posthog (in nextjs; dont now about basic react), hope it helps you @shiv ; needs env var NEXT_PUBLIC_POSTHOG_KEY; and then in App.tsx you can wrap everything in that / or just the pages needing tracking
'use client';
import posthog from 'posthog-js';
import { PostHogProvider as PHProvider, usePostHog } from 'posthog-js/react';
import { Suspense, useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
export function PostHogProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
if (process.env.NEXT_PUBLIC_POSTHOG_KEY) {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
api_host: '/ingest',
ui_host: 'https://eu.posthog.com',
capture_pageview: false, // We capture pageviews manually
capture_pageleave: true, // Enable pageleave capture
});
}
}, []);
return (
<PHProvider client={posthog}>
<SuspendedPostHogPageView />
{children}
</PHProvider>
);
}
function PostHogPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
const posthog = usePostHog();
useEffect(() => {
if (pathname && posthog) {
let url = window.origin + pathname;
const search = searchParams!.toString();
if (search) {
url += '?' + search;
}
posthog.capture('$pageview', { $current_url: url });
}
}, [pathname, searchParams, posthog]);
return null;
}
function SuspendedPostHogPageView() {
return (
<Suspense fallback={null}>
<PostHogPageView />
</Suspense>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment