DEV Community

Cover image for How to Add Google Analytics to Your Next.js App (TypeScript & JavaScript)
Hasanul Banna Khan Abir
Hasanul Banna Khan Abir

Posted on

How to Add Google Analytics to Your Next.js App (TypeScript & JavaScript)

Adding Google Analytics (GA4) to your Next.js web application is essential to track user engagement, measure traffic, and optimize performance. This step-by-step guide covers the best practices for implementing GA4 in both App Router (Next.js 13+) and Pages Router, with examples for both TypeScript and JavaScript projects.


✅ 1. Get Your GA4 Measurement ID

  1. Go to Google Analytics
  2. Set up a property and data stream
  3. Copy your Measurement ID (e.g. G-XXXXXXX)

✅ 2. Add GA4 Script in the App Router (Next.js 13+)

✅ Option A: Using app/layout.tsx or app/layout.js

// app/layout.tsx (or layout.js)
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <Script
          strategy="afterInteractive"
          src={`https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX`}
        />
        <Script id="ga-script" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXXXXX');
          `}
        </Script>
      </head>
      <body>{children}</body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Pitfall: Using Script in Client Components

Google Analytics setup must occur in the <head> or top-level layout. Don’t put tracking code in individual client components.


✅ 3. Add GA4 in Pages Router (pages/_document.tsx)

// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <script
          async
          src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
        ></script>
        <script
          dangerouslySetInnerHTML={{
            __html: `
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', 'G-XXXXXXX');
            `,
          }}
        ></script>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Enter fullscreen mode Exit fullscreen mode

✅ 4. Track Route Changes (Optional for SPA Tracking)

// app/providers.tsx or app/analytics.tsx
'use client';

import { usePathname } from 'next/navigation';
import { useEffect } from 'react';

export function GoogleAnalytics() {
  const pathname = usePathname();

  useEffect(() => {
    if (window.gtag) {
      window.gtag('config', 'G-XXXXXXX', {
        page_path: pathname,
      });
    }
  }, [pathname]);

  return null;
}
Enter fullscreen mode Exit fullscreen mode

Then include <GoogleAnalytics /> inside your layout or root component.


✅ 5. Test Your Setup

  1. Open Google Analytics > Realtime
  2. Visit your website in an incognito window
  3. Confirm the visit shows up in real-time data

❌ Common Google Analytics Mistakes

Mistake Solution
Forgetting to include GA script Add to layout or _document.tsx
Using wrong measurement ID Double-check ID format (G-XXXXXXX)
Not tracking page views in SPA mode Use pathname listener in App Router
Putting script in client-only components Use <Script /> from next/script instead

🆚 Google Analytics Alternatives: Pros and Cons

Tool Pros Cons
Plausible Privacy-friendly, simple setup, EU-hosted Paid plan, fewer enterprise features
Umami Open-source, lightweight, self-hosted available Requires self-hosting or paid SaaS
PostHog Open-source, advanced analytics & session replay Heavier setup, requires DB
Matomo GDPR-compliant, powerful enterprise features Complex setup, can be resource-intensive
Fathom Privacy-first, fast-loading Limited custom events support
GoatCounter Lightweight, open-source Less intuitive UI

Recommendation: Use Plausible or Fathom if you care about privacy & simplicity. Use PostHog for in-depth product analytics.


📌 Tips

  • Always use strategy="afterInteractive" for performance
  • For GDPR compliance, consider cookie consent management
  • Combine with tools like Google Tag Manager for advanced setups

Conclusion

Adding Google Analytics to your Next.js project is straightforward when done correctly. Whether you use TypeScript or JavaScript, Pages or App Router, this guide helps you track real user interactions and make data-driven decisions.

If GA isn't the right fit for your project, try an alternative like Plausible or Umami to stay privacy-compliant and developer-friendly.

Now you're all set to monitor traffic and grow your Next.js application with insights!

Top comments (0)