diff --git a/src/hooks/usePageAnalytics.ts b/src/hooks/usePageAnalytics.ts index 612771b56..5eb01da20 100644 --- a/src/hooks/usePageAnalytics.ts +++ b/src/hooks/usePageAnalytics.ts @@ -8,6 +8,16 @@ export function usePageAnalytics() { const { asPath } = router; useEffect(() => { const justPath = asPath.split('?')[0]; - recordPageView(justPath); + // wait for analytics library to initilize on initial page load before sending event + if (window.analyticsInitialized) { + recordPageView(justPath); + } else { + const checkInterval = setInterval(() => { + if (window.analyticsInitialized) { + recordPageView(justPath); + clearInterval(checkInterval); + } + }, 100); + } }, [asPath]); } diff --git a/src/utils/rudder-analytics.ts b/src/utils/rudder-analytics.ts index ff69c5fff..2e2436ea3 100644 --- a/src/utils/rudder-analytics.ts +++ b/src/utils/rudder-analytics.ts @@ -14,6 +14,7 @@ let anonymousUserIdCreatedAt = ''; declare global { interface Window { rudderanalytics: Analytics | undefined; + analyticsInitialized: boolean; } } @@ -62,6 +63,7 @@ export async function init() { window.rudderanalytics.load(rudderAnalyticsKey, analyticsUrl); rudderAnalytics = window.rudderanalytics; if (rudderAnalytics) rudderAnalytics.setAnonymousId(getAnonymousId()); + window.analyticsInitialized = true; } catch (e) { console.error(e); }