Skip to content

Commit 4aef4bc

Browse files
authored
fix(analytics): use automatic pageview detection (#32)
1 parent 2237e9d commit 4aef4bc

1 file changed

Lines changed: 0 additions & 44 deletions

File tree

‎src/app/components/GoogleAnalytics.tsx‎

Lines changed: 0 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,13 @@
1-
"use client";
2-
3-
import { useEffect, useRef, useState } from "react";
4-
import { usePathname } from "next/navigation";
51
import Script from "next/script";
62

73
const measurementId = process.env.NEXT_PUBLIC_GA_ID || "G-VWDH18RX25";
84

9-
declare global {
10-
interface Window {
11-
dataLayer: unknown[][];
12-
gtag: (...args: unknown[]) => void;
13-
}
14-
}
15-
165
export default function GoogleAnalytics() {
17-
const pathname = usePathname();
18-
const lastTrackedPath = useRef<string | null>(null);
19-
const hasTrackedInitialPage = useRef(false);
20-
const pendingPageViews = useRef<Array<{ pathname: string; pageTitle: string }>>([]);
21-
const [gtagReady, setGtagReady] = useState(false);
22-
23-
useEffect(() => {
24-
if (!pathname) return;
25-
26-
if (!hasTrackedInitialPage.current) {
27-
hasTrackedInitialPage.current = true;
28-
lastTrackedPath.current = pathname;
29-
return;
30-
}
31-
32-
if (lastTrackedPath.current !== pathname) {
33-
lastTrackedPath.current = pathname;
34-
pendingPageViews.current.push({ pathname, pageTitle: document.title });
35-
}
36-
37-
if (!gtagReady || typeof window.gtag !== "function") return;
38-
39-
for (const pageView of pendingPageViews.current) {
40-
window.gtag("event", "page_view", {
41-
page_path: pageView.pathname,
42-
page_location: `${window.location.origin}${pageView.pathname}`,
43-
page_title: pageView.pageTitle,
44-
});
45-
}
46-
pendingPageViews.current = [];
47-
}, [gtagReady, pathname]);
48-
496
return (
507
<>
518
<Script
529
src={`https://www.googletagmanager.com/gtag/js?id=${measurementId}`}
5310
strategy="afterInteractive"
54-
onReady={() => setGtagReady(true)}
5511
/>
5612
<Script id="google-analytics-init" strategy="beforeInteractive">
5713
{`window.dataLayer = window.dataLayer || [];

0 commit comments

Comments
 (0)