Web Development

ga4-nextjs-app-router-implementation/

Arun Tyagi
January 21, 2026
341 views

📌 Intro: Why GA4 in Next.js?

Google Analytics 4 (GA4) is the newest analytics platform from Google — it provides event-based tracking, deeper behavior insights, and flexible reporting for modern apps. When you build your app with Next.js App Router, you can configure GA4 cleanly at the root level so every page view and event is tracked without repeating code. 

Next.js doesn’t automatically include GA4 by default, so we’ll set it up manually in the app/layout.tsx and track routes globally.


🔧 Step-by-Step: GA4 Setup in Next.js App Router

1️⃣ Create GA4 Property & Measurement ID

  1. Go to your Google Analytics dashboard → Admin → Create a new GA4 property.
  2. Copy your Measurement ID (looks like G-XXXXXXX).
  3. Save this ID — we’ll use it in Next.js.  


2️⃣ Add to Environment Variables

👉 Create .env.local at your project root:

NEXT_PUBLIC_GA4_MEASUREMENT_ID=G-XXXXXXXXXX

Using environment variables keeps your tracking ID secure and flexible across environments.  

3️⃣ Load GA4 Scripts in app/layout.tsx

Instead of manually pasting the script tag, import with next/script so Next.js handles loading strategy well:

import Script from "next/script";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        {/* GA4 Base Script */}
        <Script
          src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID}`}
          strategy="afterInteractive"
        />
        <Script id="ga4-init" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID}', {
              page_path: window.location.pathname,
            });
          `}
        </Script>
      </head>
      <body>{children}</body>
    </html>
  );
}

💡 We use strategy="afterInteractive" so GA loads after the page is interactive, improving performance. 

4️⃣ Automatic Page View Tracking

In App Router, navigation happens client-side. To ensure GA4 records every route change:

  1. Create a client component at app/components/analytics.tsx:

"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";

export default function Analytics() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const fullPath = pathname + (searchParams.toString() ? `?${searchParams}` : "");
    window.gtag("config", process.env.NEXT_PUBLIC_GA4_MEASUREMENT_ID, {
      page_path: fullPath,
    });
  }, [pathname, searchParams]);

  return null;
}

  1. Import it in your layout.tsx below children:

<body>
  {children}
  <Analytics />
</body>

📌 Best Practices for GA4 + Next.js

✅ Always add GA code once at root

✅ Use environment variables for configuration

✅ Respect user privacy and GDPR compliance

✅ Test analytics only in production builds


Tags