From f7fe55d95a4248c9a0128f80f8d2e6773963c16e Mon Sep 17 00:00:00 2001 From: Amit Sharma Date: Wed, 30 Jul 2025 16:45:30 -0700 Subject: [PATCH] fix: updated per @paabloLC request to move Posthog initialization outside of providers.tsx --- ui/app/providers.tsx | 15 ++++----------- ui/lib/analytics.ts | 23 ++++++++++++++++++++++- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/ui/app/providers.tsx b/ui/app/providers.tsx index d5ff088ad6..9d89ff6fb5 100644 --- a/ui/app/providers.tsx +++ b/ui/app/providers.tsx @@ -7,8 +7,8 @@ import { ThemeProvider as NextThemesProvider } from "next-themes"; import { ThemeProviderProps } from "next-themes/dist/types"; import posthog from "posthog-js"; import { PostHogProvider as PHProvider } from "posthog-js/react"; -import { useEffect } from "react"; import * as React from "react"; +import { initializePostHog } from "@/lib/analytics"; export interface ProvidersProps { children: React.ReactNode; @@ -18,16 +18,9 @@ export interface ProvidersProps { export function Providers({ children, themeProps }: ProvidersProps) { const router = useRouter(); - useEffect(() => { - posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, { - api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - autocapture: false, - defaults: "2025-05-24", - capture_exceptions: true, - capture_pageview: false, - capture_pageleave: false, - }); + // Initialize PostHog + React.useMemo(() => { + initializePostHog(); }, []); return ( diff --git a/ui/lib/analytics.ts b/ui/lib/analytics.ts index 32397b8739..a7a339f90f 100644 --- a/ui/lib/analytics.ts +++ b/ui/lib/analytics.ts @@ -1,5 +1,24 @@ import posthog from "posthog-js"; +// Initialize PostHog +export const initializePostHog = (): void => { + if (typeof window === "undefined") return; // Don't initialize on server side + + try { + posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + autocapture: false, + defaults: "2025-05-24", + capture_exceptions: true, + capture_pageview: false, + capture_pageleave: false, + }); + } catch (error) { + console.error("Failed to initialize PostHog:", error); + } +}; + // Type definitions for tracking payloads export interface UserLoginPayload { email: string; @@ -144,7 +163,9 @@ export const setUserProperties = (properties: Record): void => { export const isAnalyticsReady = (): boolean => { try { return ( - typeof posthog !== "undefined" && posthog._isIdentified !== undefined + typeof window !== "undefined" && + typeof posthog !== "undefined" && + posthog.__loaded === true ); } catch { return false;