Jan 12, 2026

Fixing Google Analytics Integration in a Next.js App

When I tried to add Google Analytics to my React/Next.js project, I used the GoogleTagManager React component with my GA4 tag ID:

    
<GoogleTagManager gtmId="G-XXXXXXXXXX" />
    
  

The build succeeded, but Analytics showed “No data received in past 48 hours.”

The Problem

Using the GoogleTagManager component with a GA4 ID (G-XXXXXXXXXX) only created a preload link in the <head>:

    
<link rel="preload" href="https://www.googletagmanager.com/gtm.js?id=G-XXXXXXXXXX" as="script"/>
    
  

This preload line fetched the script but did not initialize GA4 tracking. As a result, Google Analytics never received events.

The Solution

Instead of relying on the preload link, I injected the full GA4 snippet using Next.js’s next/script. This ensures the script loads after hydration and initializes correctly.

Sample Code

    
import Script from "next/script";

export default function Layout({ children }) {
  return (
    <html lang="en">
      <head>
        {/* Load GA4 script */}
        <Script
          src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
          strategy="afterInteractive"
        />

        {/* Initialize GA4 */}
        <Script id="ga4-init" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXXXXXXXX');
          `}
        </Script>
      </head>
      <body>{children}</body>
    </html>
  );
}
    
  

Replace G-XXXXXXXXXX with your own GA4 Measurement ID.

Key Takeaways

  • The GoogleTagManager React component with a GA4 ID only creates a preload link — it doesn’t initialize Analytics.
  • GA4 requires the full gtag.js snippet with initialization code.
  • Use next/script in Next.js for safe script injection.
  • Verify events in Analytics → Realtime after deployment.

👉 This adjustment solved the issue and got my Analytics dashboard flowing with data again.