Adding Google Analytics 4 to a Next.js App Router project looks like a two-line job. Then the client asks why page views are a third of what they expected, or why the cookie banner doesn't actually stop tracking. Here's the setup I use and the issues I fix most often.
1. Keep the Measurement ID in an env variable
# .env.local NEXT_PUBLIC_GA4_ID = G-XXXXXXXXXX
Enter fullscreen mode
Exit fullscreen mode
Pick one name and use it everywhere. A surprising number of bugs are just two different variable names in two files.
2. Load gtag once, in the root layout
// app/layout.tsx import Script from 'next/script' ; import { Analytics } from './components/analytics' ;
const GA_ID = process . env . NEXT_PUBLIC_GA4_ID ;
export default function RootLayout ( { children } : { children : React .…