From f487189a191ccea142881c9d73169a7c697cdff2 Mon Sep 17 00:00:00 2001 From: Tim Leikauf Date: Wed, 1 Jul 2026 21:04:57 +0200 Subject: [PATCH] =?UTF-8?q?Fix=20PostHog=20init=20race=20condition=20?= =?UTF-8?q?=E2=80=94=20remove=20=5F=5Floaded=20guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit posthog.capture() queues events automatically before init completes, so checking __loaded blocked the first pageview from being sent. Co-Authored-By: Claude Sonnet 4.6 --- components/PostHogProvider.tsx | 13 ++++++++----- lib/posthog.ts | 11 ----------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/components/PostHogProvider.tsx b/components/PostHogProvider.tsx index e632bcc..ba3c8c5 100644 --- a/components/PostHogProvider.tsx +++ b/components/PostHogProvider.tsx @@ -2,19 +2,22 @@ import { useEffect } from 'react' import { usePathname } from 'next/navigation' -import { initPostHog, posthog } from '@/lib/posthog' +import posthog from 'posthog-js' export default function PostHogProvider({ children }: { children: React.ReactNode }) { useEffect(() => { - initPostHog() + posthog.init('phc_BHgg9S7CQqVShe7EMCdi86PxA49qcNaTsR9Nn5EGxRCT', { + api_host: 'https://analytics.hyggecraftery.com', + capture_pageview: false, + persistence: 'localStorage', + }) }, []) const pathname = usePathname() useEffect(() => { - if (posthog.__loaded) { - posthog.capture('$pageview', { $current_url: window.location.href }) - } + // PostHog queues events automatically before init completes + posthog.capture('$pageview', { $current_url: window.location.href }) }, [pathname]) return <>{children} diff --git a/lib/posthog.ts b/lib/posthog.ts index 658b195..794536a 100644 --- a/lib/posthog.ts +++ b/lib/posthog.ts @@ -1,13 +1,2 @@ import posthog from 'posthog-js' - -export function initPostHog() { - if (typeof window !== 'undefined' && !posthog.__loaded) { - posthog.init('phc_BHgg9S7CQqVShe7EMCdi86PxA49qcNaTsR9Nn5EGxRCT', { - api_host: 'https://analytics.hyggecraftery.com', - capture_pageview: false, - persistence: 'localStorage', - }) - } -} - export { posthog }