Quick answer. The official way to add GA4 to Next.js is the @next/third-parties package. Install it, then drop the GoogleAnalytics component into your root layout. It loads after hydration so it won't hurt performance, and it automatically tracks page views across client-side route changes. For the Pages Router, add the same component in pages/_app. Custom events use the sendGAEvent helper.
One package, one component, automatic page views on route changes. The Next.js team built it.
What you'll need
- A Next.js app (App Router or Pages Router) you can edit and deploy.
- Your GA4 Measurement ID (G-XXXXXXX), ideally in an env var.
Add GA4 to Next.js
- Install the package. Run npm install @next/third-parties@latest next@latest.
- Add the component (App Router). Open app/layout.tsx and add <GoogleAnalytics gaId="G-XXXXXXX" /> inside the html tag, after body.
- Or Pages Router. Add the same GoogleAnalytics component to pages/_app.tsx.
- Deploy. The package handles loading and page-view tracking automatically.
Do it with AI
Want it wired up with an env var and custom events?
Wire up GA4 in my Next.js app with an env var
Add Google Analytics 4 to my Next.js app using @next/third-parties. I'm on the [App Router / Pages Router]. Put my Measurement ID in an environment variable (NEXT_PUBLIC_GA_ID), show me exactly where the GoogleAnalytics component goes, and add a typed helper to fire a custom event with sendGAEvent. Then tell me how to verify in GA4 Realtime.
How to check it worked
Deploy (or run a production build), open the site, and check GA4 Realtime. Navigate between routes and confirm page views increment without a full reload.
Common mistakes
- Hardcoding the ID and adding a manual gtag script. Use the component only, or you double-count.
- Component in the wrong place. It belongs in the root layout, not inside a Client Component.
- Missing NEXT_PUBLIC_ prefix. Without the prefix, the env var is undefined in the browser.
FAQ
- What's the official way to add GA4 to Next.js?
- The @next/third-parties package. Add the GoogleAnalytics component to your root layout with your Measurement ID. It's built and recommended by the Next.js team.
- Does it track page views on route changes?
- Yes, automatically. The component tracks client-side navigations without extra code.
- Do I still need next/script?
- No. @next/third-parties wraps the script loading for you, optimized to load after hydration.
Shipped.
Holy Bucket reads your app's GA4 and Search Console and tells you what's working and what's leaking, so you can stay in the editor.