How to Implement Google Analytics 4 (GA4) in a Next.js Project

Rajesh Kumar Yadav - Oct 18 - - Dev Community

Google Analytics 4 (GA4) provides advanced tracking features to help you monitor user behavior and engagement on your website. In this blog post, I’ll guide you through integrating GA4 into your Next.js project, tracking page views per route, setting up custom events, and troubleshooting common issues.

Step 1: Set Up Google Analytics 4 (GA4)

1. Create a GA4 Property

  1. Go to the Google Analytics dashboard.
  2. Click Admin on the left-side menu.
  3. Under the Property column, click Create Property and select GA4.
  4. Follow the steps to configure your property, and you’ll get a Measurement ID that looks like G-XXXXXXXXXX.

2. Add Your Measurement ID

For GA4 to work in your Next.js app, you need to store your GA4 Measurement ID securely using environment variables.

  1. Add your Measurement ID to your .env.local file in your project’s root directory:
NEXT_PUBLIC_GA_ID=G-XXXXXXXXXX
Enter fullscreen mode Exit fullscreen mode

If you're deploying to a cloud provider (like Azure Static Web Apps or Vercel), make sure to add NEXT_PUBLIC_GA_ID to the respective environment settings in the cloud provider's configuration.


Step 2: Add GA4 Script to Your Next.js App

1. Modify _app.tsx

Next.js automatically manages routing, so we’ll leverage the _app.tsx file to initialize Google Analytics and track page views whenever a route changes.

Here’s the code you’ll add to your pages/_app.tsx file:

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import Script from 'next/script'; // Next.js component to load external scripts
import type { AppProps } from 'next/app';
import Layout from '../components/layout'; // Import your layout component

export default function App({ Component, pageProps }: AppProps) {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url: string) => {
      if (typeof window.gtag === 'function') {
        window.gtag('config', process.env.NEXT_PUBLIC_GA_ID, {
          page_path: url,
        });
        console.log(`Page view tracked: ${url}`); // Optional: for debugging
      }
    };

    // Listen to route changes and track page views
    router.events.on('routeChangeComplete', handleRouteChange);

    // Clean up the event listener when the component unmounts
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return (
    <>
      {/* GA4 Script to load the analytics library */}
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
      />
      <Script
        id="gtag-init"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Points in This Code:

  • Google Analytics Script: We’re loading the GA4 script using the Script component from Next.js, ensuring it loads after the page is interactive (strategy="afterInteractive").
  • Page View Tracking: The router.events.on('routeChangeComplete', handleRouteChange) listens to route changes and sends a page view to GA4 each time a user navigates to a new page.
  • gtag Function: The GA4 function gtag('config', GA_ID, {...}) is called to track the page view for each route change.

Step 3: Track Custom Events (e.g., LinkedIn Button Click)

GA4 also allows tracking custom events, like button clicks or form submissions. You can track clicks on any element (e.g., a LinkedIn button) to measure user interaction.

1. Modify the Button Code

Let’s say you have a LinkedIn button in your Next.js app. Here’s how you can track clicks on this button:

import { Button, Nav } from 'react-bootstrap'; // Assuming you're using React Bootstrap

export default function LinkedInButton() {
  const handleLinkedInClick = () => {
    if (typeof window.gtag === 'function') {
      window.gtag('event', 'linkedin_click', {
        event_category: 'Social Media',
        event_label: 'LinkedIn Button',
        value: 1,
      });
    }
  };

  return (
    <Button variant="outline-primary" onClick={handleLinkedInClick}>
      <Nav.Link
        href="https://www.linkedin.com/in/your-profile"
        target="_blank"
        aria-label="View my LinkedIn profile (opens in a new tab)"
      >
        <i className="fab fa-linkedin" aria-hidden="true"></i> View my LinkedIn profile
      </Nav.Link>
    </Button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Key Points for Custom Event Tracking:

  • Custom Event: We use gtag('event', ...) to track the button click as a custom event named linkedin_click.
  • Event Parameters: You can customize parameters like event_category, event_label, and value to better organize and analyze events in GA4.

Step 4: Testing GA4 Implementation

1. Use DebugView in GA4

Google Analytics 4 offers a DebugView feature that helps you track events in real time as you test your site. To use this feature:

  1. Go to your Google Analytics dashboard.
  2. Navigate to ConfigureDebugView.
  3. Interact with your website (e.g., click links, navigate pages).
  4. Check the DebugView to verify that page views and custom events (like linkedin_click) are being tracked.

2. View Page Reports in GA4

Once your GA4 setup is live and data starts flowing, you can view reports:

  1. Page Views: Go to ReportsEngagementPages and screens to see a list of page views for your site.
  2. Custom Events: Navigate to ReportsEngagementEvents to view custom events, including how many users clicked the LinkedIn button (linkedin_click event).

Step 5: Troubleshooting Common Issues

  1. Environment Variable Not Loading: If NEXT_PUBLIC_GA_ID is undefined in production:

    • Make sure your environment variable is set correctly in .env.local for local development.
    • If using a cloud provider (e.g., Azure Static Web Apps or Vercel), make sure the environment variable is configured properly in the provider’s dashboard.
    • Use console.log(process.env.NEXT_PUBLIC_GA_ID) in _app.tsx to verify that the variable is loading correctly.
  2. Page Views Not Being Tracked: Ensure that the GA script is properly injected into the page by checking the browser’s Developer Tools (right-click → View Page Source) and looking for:

   <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
Enter fullscreen mode Exit fullscreen mode
  1. Ad Blockers: Some users might have ad-blocking extensions that prevent GA4 from working properly. Test your setup in Incognito Mode or with ad-blockers disabled.

Conclusion

Integrating Google Analytics 4 (GA4) into your Next.js project provides valuable insights into user engagement, behavior, and performance. By following this guide, you’ve implemented basic page view tracking and custom event tracking, giving you the tools to measure how users interact with your site.

Don’t forget to check the GA4 dashboard regularly to monitor your site’s performance and make data-driven decisions based on user behavior.

Happy coding!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .