From 152a6b803ddbe62f95462de29520e2a73ef2daf6 Mon Sep 17 00:00:00 2001 From: Guilherme Biff Zarelli Date: Sun, 25 Oct 2026 14:33:00 -0300 Subject: [PATCH] fix(analytics): wait for gtag before sending pageviews --- src/app/components/GoogleAnalytics.tsx | 30 ++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/app/components/GoogleAnalytics.tsx b/src/app/components/GoogleAnalytics.tsx index d69be99..ed899f5 100644 --- a/src/app/components/GoogleAnalytics.tsx +++ b/src/app/components/GoogleAnalytics.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import { usePathname } from "next/navigation"; import Script from "next/script"; @@ -16,23 +16,35 @@ declare global { export default function GoogleAnalytics() { const pathname = usePathname(); const lastTrackedPath = useRef(null); + const pendingPageViews = useRef>([]); + const [gtagReady, setGtagReady] = useState(false); useEffect(() => { - if (!pathname || lastTrackedPath.current === pathname) return; + if (!pathname) return; - lastTrackedPath.current = pathname; - window.gtag("event", "page_view", { - page_path: pathname, - page_location: `${window.location.origin}${pathname}`, - page_title: document.title, - }); - }, [pathname]); + if (lastTrackedPath.current !== pathname) { + lastTrackedPath.current = pathname; + pendingPageViews.current.push({ pathname, pageTitle: document.title }); + } + + if (!gtagReady || typeof window.gtag !== "function") return; + + for (const pageView of pendingPageViews.current) { + window.gtag("event", "page_view", { + page_path: pageView.pathname, + page_location: `${window.location.origin}${pageView.pathname}`, + page_title: pageView.pageTitle, + }); + } + pendingPageViews.current = []; + }, [gtagReady, pathname]); return ( <>