Skip to content

Commit 56aa6db

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 225fc71 commit 56aa6db

2 files changed

Lines changed: 9 additions & 3 deletions

File tree

src/app/clientEffects.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,22 @@
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+
// The initial page view is reported by gtag('config') itself. This
21+
// mirrors the Pages Router's `routeChangeComplete` handler, which only
22+
// fired for client-side navigations.
23+
if (previousPathname.current === pathname) return;
24+
previousPathname.current = pathname;
25+
if (typeof gtag === 'undefined') return;
2026
gtag('event', 'pageview', {event_label: pathname});
2127
}, [pathname]);
2228

src/app/layout.tsx

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

0 commit comments

Comments
 (0)