codersteps logo

How to add Google Analytics to your Next.js website

Abdessamad Ely
Abdessamad Ely
Software Engineer
Reading time: 4 min read  •  Published: in Next.js  •  Updated:

When launching a new website one of the most important tasks is to have a way to track your website visitors.

One of the leading web analytics services is Google Analytics, offered by Google is totally free, the only thing you need is a google account.

In this article, I want to show you How you can add Google Analytics to your Next.js website with a step-by-step guide that you can follow.

Setting Up Our Project

Like in every article, I like to start with a fresh Next.js project so It's easy for you to follow and not get lost in a lot of irrelevant topics.

To create a new Next.js project we will use the command npx create-next-app@latest --typescript google_analytics this will create a new Next.js with Typescript and a default structure.

Because we want to add google analytics to the whole website covering all pages, I like to add it inside the pages/_document.tsx file which is missing from the default structure.

Let's add it first before moving to create the GoogleAnalytics component, to do that create a new file at pages/_document.tsx with the following (need more explanation? Next.js docs)

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

export default function Document() {
  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

It's simple we're just overriding the default one that Next.js was using before creating the pages/_document.tsx file.

The GoogleAnalytics component

The GoogleAnalytics component will be responsible for adding the scripts to the Next.js website, and we will use it inside the next/document Head component.

Create a new file for our analytics component at components/common/google/Analytics.tsx feel free to change the component location to match what you already used to.

components/common/google/Analytics.tsx
const Analytics = ({
  analyticsMeasurementId,
}: {
  analyticsMeasurementId: string;
}) => {
  return (
    <>
      <script
        async
        src={`https://www.googletagmanager.com/gtag/js?id=${analyticsMeasurementId}`}
      ></script>
      <script
        dangerouslySetInnerHTML={{
          __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
              
                gtag('config', '${analyticsMeasurementId}');
                `,
        }}
      ></script>
    </>
  );
};

export default Analytics;

As you can see we are using normal HTML script elements instead of the Next.js Script component, I tried using the Script component at first but it wasn’t consistent in my case.

We are adding the google analytics script to the _document.tsx file which runs only on the server, so I didn't see the benefit of using the Script component anyway so I didn’t bother.

The component is simple it takes a measurement ID provided by Google Analytics and returns the google analytics scripts.

Adding the google Analytics component to the document Head

To make it more convenient we will add the measurement ID to our .env file so it's easy to change in multiple environments.

Create the .env file at the root of your project and add the following variable to it, after that make sure to restart the next.js server to load the newly added env vars.

.env
ANALYTICS_MEASUREMENT_ID="Your google analytics measurement ID"

When dealing with environment variables I like to use a config file instead of using them directly, it has multiple benefits like type checking and so on.

Create a new file config/app.config.ts which will simply export an appConfig object that we can use throughout the project.

config/app.config.ts
type AppConfig = {
  env: {
    analyticsMeasurementId?: string;
  };
};

const appConfig: AppConfig = {
  env: {
    analyticsMeasurementId: process.env.ANALYTICS_MEASUREMENT_ID,
  },
};

export default appConfig;

You can extend it to add more app-related configs like meta-information, date formats, etc.

Now we're all set to add the component to the _document Head open the pages/_document.tsx file and change it to match the following.

pages/_document.tsx
import { Html, Head, Main, NextScript } from "next/document";
import appConfig from "../config/app.config";
import Analytics from "../components/common/google/Analytics";

export default function Document() {
  return (
    <Html>
      <Head>
        {process.env.NODE_ENV === "production" &&
          typeof appConfig.env.analyticsMeasurementId !== "undefined" && (
            <Analytics
              analyticsMeasurementId={appConfig.env.analyticsMeasurementId}
            />
          )}
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

We added the condition process.env.NODE_ENV === "production" to disable it on development because we don't want to track our own visits, which may cause some unclear analytic reports.

It's time to try it out, set the ANALYTICS_MEASUREMENT_ID variable to your google analytics measurement ID you can find it on your google analytics dashboard.

Now build and start your next.js server by running the command yarn build && yarn start then visit any page and view the page source.

You should see that a new script was added with the src attribute with something like https://www.googletagmanager.com/gtag/js....

Now open your Google Analytics dashboard, and you should see 1 visitor if it's only you 👊.

Conclusion

In this article, we explained how to add google analytics to your next.js website with a step-by-step guide including all the code snippets that you will need.

Source code is available at: https://github.com/codersteps/nextjs_google_analytics.

That's it for this one, see you in the next one 😁

Abdessamad Ely
Abdessamad Ely
Software Engineer

A web developer from Morocco Morocco flag , and the founder of coderstep.com a website that help developers grow and improve their skills with a set of step-by-step articles that just works.

Your Questions

  • No questions have been asked yet.

Submit your question

Please use the form bellow to submit your question, and it will be include in the list asap.