diff --git a/src/providers/PosthogAnalytics.tsx b/src/providers/PosthogAnalytics.tsx new file mode 100644 index 00000000..7df79830 --- /dev/null +++ b/src/providers/PosthogAnalytics.tsx @@ -0,0 +1,65 @@ +// app/providers.tsx +'use client'; + +import { Suspense, useEffect } from 'react'; +import { usePathname, useSearchParams } from 'next/navigation'; +import { useRouterType } from '@hooks/useRouterType'; +import posthog, { PostHogConfig } from 'posthog-js'; +import { PostHogProvider } from 'posthog-js/react'; + +import { env } from '@utils/env'; + +const phConfig: Partial = { + api_host: 'https://mikebifulco.com/ingest', + person_profiles: 'identified_only', + capture_pageview: false, // Disable automatic pageview capture, as we capture manually +} as const; + +export function PHProvider({ children }: { children: React.ReactNode }) { + useEffect(() => { + posthog.init(env.NEXT_PUBLIC_POSTHOG_KEY, phConfig); + }, []); + + return {children}; +} + +// New component to track page views +const PosthogPageView = () => { + const pathname = usePathname(); + const searchParams = useSearchParams(); + + useEffect(() => { + if (!pathname) return; + + const searchParamsString = searchParams?.toString() ?? ''; + const url = window.origin + pathname + searchParamsString; + posthog.capture('$pageview', { + $current_url: url, + }); + }, [pathname, searchParams]); + + return null; +}; + +const PosthogAppRouter = () => { + return ( + + + + ); +}; + +/** + * This component is used to integrate Posthog with Next.js, + * and adjusts itself depending on the current route, regardless of + * whether it's from the Pages or App Router. + */ +export const PosthogAnalytics = () => { + const routerType = useRouterType(); + if (routerType === 'pages') { + return ; + } + return ; +}; + +export default PHProvider;