Skip to content

Commit 856856a

Browse files
gaearonclaude
andcommitted
Restore GA page_view parity with the Pages Router
`send_page_view: false` suppressed GA4's automatic page_view on landing, and the custom `pageview` event was sent for every pathname including the initial one. Match the old _app.tsx: let gtag('config') report the landing page_view, and only send the legacy custom event on client navigations. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent d114f3a commit 856856a

2 files changed

Lines changed: 7 additions & 3 deletions

File tree

‎src/app/clientEffects.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,20 @@
77

88
'use client';
99

10-
import {useEffect} from 'react';
10+
import {useEffect, useRef} from 'react';
1111
import {usePathname} from 'next/navigation';
1212

1313
declare const gtag: (...args: any[]) => void;
1414

1515
export function AnalyticsTracker() {
1616
const pathname = usePathname();
17+
const previousPathname = useRef(pathname);
1718

1819
useEffect(() => {
19-
if (typeof window === 'undefined' || typeof gtag === 'undefined') return;
20+
// gtag('config') already reports the initial page view.
21+
if (previousPathname.current === pathname) return;
22+
previousPathname.current = pathname;
23+
if (typeof gtag === 'undefined') return;
2024
gtag('event', 'pageview', {event_label: pathname});
2125
}, [pathname]);
2226

‎src/app/layout.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ export default function RootLayout({children}: {children: React.ReactNode}) {
208208
id="ga-init"
209209
strategy="afterInteractive"
210210
dangerouslySetInnerHTML={{
211-
__html: `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', '${gaId}', {send_page_view: false});`,
211+
__html: `window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag('js', new Date());gtag('config', '${gaId}');`,
212212
}}
213213
/>
214214
)}

0 commit comments

Comments
 (0)