Search
Close this search box.

How to Use Google Analytics with Next.js

Table of Contents

In today’s data-driven world, it’s crucial to understand your user interactions on your website to improve the user experience and make informed decisions. Google Analytics (GA) is one of the most popular tools for tracking user interactions on your site. If you’re using Next.js for your application, this blog post will guide you on how to integrate Google Analytics with Next.js.

Next.js since v11 recommends using their <Script> tag for adding external scripts, and the right place to add them within the App component. This setup will allow Google Analytics to start tracking page views on your website. However, note that Google Analytics does automatic page tracking, but this might not work for every use case. For instance, hash and search parameter changes are not tracked. To have full control over page view tracking, you can disable automatic tracking.

Here’s a step-by-step guide on how to set up Google Analytics with Next.js:

Step 1: Create a Google Analytics Project

Firstly, you need to create a Google Analytics project and obtain a Measurement ID. This ID will be used to track and send data to your specific Google Analytics account.

Step 2: Set up a Google Analytics Tag in Your Next.js Project

In your Next.js project, create a /lib/gtag.ts file and add your Google Measurement ID. This file will contain the configuration for Google Analytics, including the page view and event tracking functions.

Here’s a simple implementation in TypeScript:

export const GA_TRACKING_ID = "<INSERT_TAG_ID>";

export const pageview = (url: URL): void => {
  window.gtag("config", GA_TRACKING_ID, {
    page_path: url,
  });
};

type GTagEvent = {
  action: string;
  category: string;
  label: string;
  value: number;
};

export const event = ({ action, category, label, value }: GTagEvent): void => {
  window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value,
  });
};

Also, install the gtag types using npm:

bashCopy codenpm i -D @types/gtag.js

Step 3: Add the Google Analytics Script to Your Document

Next, add the Google Analytics script to your Document (/pages/_document.tsx). This script will initialize the Google Analytics tracking on your website. Remember to enable the analytics script only for the production environment to avoid tracking visits during development or testing.

Here’s a sample implementation:

import Document, { Html, Head, Main, NextScript } from "next/document";
import { GA_TRACKING_ID } from "../lib/gtag";

const isProduction = process.env.NODE_ENV === "production";

export default class MyDocument extends Document {
  render(): JSX.Element {
    return (
      <Html>
        <Head>
          {isProduction && (
            <>
              <script
                async
                src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
              />
              <script
                dangerouslySetInnerHTML={{
                  __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', '${GA_TRACKING_ID}', {
                  page_path: window.location.pathname,
                });
              `,
                }}
              />
            </>
          )}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

Step 4: Implement Page View Tracking

Finally, implement the page view tracking in your App component (/pages/_app.tsx). The page view tracking function should be invoked every time a route change is completed. Remember to invoke the analytics function only for the production environment.

Here’s an example implementation:

import { AppProps } from "next/app";
import { useRouter } from "next/router";
import { useEffect } from "react";
import * as gtag from "../lib/gtag";
const isProduction = process.env.NODE_ENV === "production";

const App = ({ Component, pageProps }: AppProps): JSX.Element => {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url: URL) => {
      /* invoke analytics function only for production */
      if (isProduction) gtag.pageview(url);
    };
    router.events.on("routeChangeComplete", handleRouteChange);
    return () => {
      router.events.off("routeChangeComplete", handleRouteChange);
    };
  }, [router.events]);
  // eslint-disable-next-line react/jsx-props-no-spreading
  return <Component {...pageProps} />;
};

export default App;

Congratulations! You have now successfully integrated Google Analytics with your Next.js application. This setup will provide you with valuable insights into your users’ behaviors and interactions with your website, which you can use to improve the user experience and grow your business.

For more information about Next.js, you can visit Next.js Cheatsheet.

Categories