|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import posthog from 'posthog-js'; |
| 4 | +import { PostHogProvider as PHProvider, usePostHog } from 'posthog-js/react'; |
| 5 | +import { Suspense, useEffect } from 'react'; |
| 6 | +import { usePathname, useSearchParams } from 'next/navigation'; |
| 7 | + |
| 8 | +export function PostHogProvider({ children }: { children: React.ReactNode }) { |
| 9 | + useEffect(() => { |
| 10 | + posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, { |
| 11 | + api_host: '/ingest', |
| 12 | + ui_host: 'https://eu.posthog.com', |
| 13 | + capture_pageview: false, // We capture pageviews manually |
| 14 | + capture_pageleave: true, // Enable pageleave capture |
| 15 | + }); |
| 16 | + }, []); |
| 17 | + |
| 18 | + return ( |
| 19 | + <PHProvider client={posthog}> |
| 20 | + <SuspendedPostHogPageView /> |
| 21 | + {children} |
| 22 | + </PHProvider> |
| 23 | + ); |
| 24 | +} |
| 25 | + |
| 26 | +function PostHogPageView() { |
| 27 | + const pathname = usePathname(); |
| 28 | + const searchParams = useSearchParams(); |
| 29 | + const posthog = usePostHog(); |
| 30 | + |
| 31 | + useEffect(() => { |
| 32 | + if (pathname && posthog) { |
| 33 | + let url = window.origin + pathname; |
| 34 | + const search = searchParams.toString(); |
| 35 | + if (search) { |
| 36 | + url += '?' + search; |
| 37 | + } |
| 38 | + posthog.capture('$pageview', { $current_url: url }); |
| 39 | + } |
| 40 | + }, [pathname, searchParams, posthog]); |
| 41 | + |
| 42 | + return null; |
| 43 | +} |
| 44 | + |
| 45 | +function SuspendedPostHogPageView() { |
| 46 | + return ( |
| 47 | + <Suspense fallback={null}> |
| 48 | + <PostHogPageView /> |
| 49 | + </Suspense> |
| 50 | + ); |
| 51 | +} |
0 commit comments