Menu

1 / 2

GA4 in the Next.js App Router: page views, consent and the mistakes I keep seeing

DEV Community: nextjs·Arun Tyagi·8 days ago
#ypDeq55Z
#devtonextjs#devto#dev#next#gtag
Long article (607 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.