fix: use explicit posthog.init() with client prop for reliable initialization (#113)

Switch from apiKey+options pattern to explicit posthog.init() before
render, then pass client instance to PostHogProvider. This is more
reliable and matches the PostHog SDK docs' recommended client pattern.

Enables autocapture and pageview tracking per PostHog defaults.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit was merged in pull request #113.
This commit is contained in:
chihlasm
2026-03-16 19:25:17 -04:00
committed by GitHub
parent 8178657632
commit d5a87e2eca

View File

@@ -1,5 +1,6 @@
import "./instrument"; // Sentry must init before any other imports
import posthog from 'posthog-js'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { reactErrorHandler } from '@sentry/react'
@@ -9,10 +10,17 @@ import { Toaster } from 'sonner'
import './index.css'
import App from './App'
const posthogOptions = {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
defaults: '2026-01-30',
} as const
// Initialize PostHog client before rendering
const posthogKey = import.meta.env.VITE_PUBLIC_POSTHOG_KEY as string | undefined
if (posthogKey) {
posthog.init(posthogKey, {
api_host: (import.meta.env.VITE_PUBLIC_POSTHOG_HOST as string) || 'https://us.i.posthog.com',
autocapture: true,
capture_pageview: true,
capture_pageleave: 'if_capture_pageview',
persistence: 'localStorage+cookie',
})
}
createRoot(document.getElementById('root')!, {
onUncaughtError: reactErrorHandler(),
@@ -20,10 +28,7 @@ createRoot(document.getElementById('root')!, {
onRecoverableError: reactErrorHandler(),
}).render(
<StrictMode>
<PostHogProvider
apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY || ''}
options={posthogOptions}
>
<PostHogProvider client={posthog}>
<HelmetProvider>
{/* Toast notification system - theme syncs automatically via CSS custom properties */}
<Toaster