How to add Google Analytics 4 to Next.js

10 min · light code · updated June 2026

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

Add GA4 to Next.js

  1. Install the package. Run npm install @next/third-parties@latest next@latest.
  2. Add the component (App Router). Open app/layout.tsx and add <GoogleAnalytics gaId="G-XXXXXXX" /> inside the html tag, after body.
  3. Or Pages Router. Add the same GoogleAnalytics component to pages/_app.tsx.
  4. 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

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.

Keep going

Last updated June 2026. By Holy Bucket.