How to set up Next.js with google analytics

Cover Image for How to set up Next.js with google analytics
Ali Bentaleb
Ali Bentaleb

This article will show you how to set up google analytics with Next.js framework, in the following we suppose that the purpose is to add your google annalytics to a website.

Step 1: Login to google analytics using gmail account

The first thing to do is create your property on google analytics, you can do so by heading to google analytics website, it will ask you to login using one of your gmail accounts.

Step 2: Set up your property

At the bottom left of the screen there is a gear icon for admin settings, click on it and then the screen will show up a blue link called create property![google analytics,create property icon][2] , it will take you then to create property setup, you give it a name, and then select the appropriate informations regarding your business size and so on. Once done click again on the gear icon, you must see now the property on the dropdown list, you select it and then click on data streams ![google analytics, data stream icon][3], hover to Web link, click on it and then click on "Add stream", it will ask you to give your website url, and the stream name that you would like to call it, do that and then click "create stream".

Step 3: get your google Measurement ID

Once finished, head again to "data streams" on the "Web" section, and click on the data stream you have named, it will pop up a screen and show you your measurement ID, copy it because we will need it later, you can also scroll down, and you will find your global site tag, Google analytics global site tag you can click on it and it will give you a code snippet where you can put it in the head of your html files.

Step 4: Set up Next.js with google analytics

Now the fun part! let's browse our Next.js project, so Next.js have a folder structure where each page that need to be served is contained under "pages" folder by default, so in order for google analytics to analyze our pages, it should be added on every single page, however with Next.js, this is much easier since all pages are inherited from Document class.

Step 5: Create _document.js

Next.js dictate that in order to overwrite the template on which pages are served, you need to declare your _document.js under pages folder, like so, every page served by Next.js will have the same template, so let's take a look :

import Document, { Html, Head, Main, NextScript } from "next/document";

import { G_TAG } from "../lib/constants";

export default class MyDocument extends Document {
  render() {
    const url = "" + `${G_TAG}`;
    return (
      <Html lang="en">
          <script async src={`${url}`}></script>

              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${G_TAG}', {
              page_path: window.location.pathname,
          <Main />
          <NextScript />

As you can see above, we are building the template of each page served by Next.js, and the content is served under NextScript, you can go ahead and copy and paste this code as it is undependant.

Step 6: Create your gtag constant

The next thing to do is to define you measurement ID which i asked to save, so for my example i am keeping this values on a separate file for maintenance facility, so it should look like :
export const G_TAG = {
  development: "dev-mode",
So in order to separate developement from deployement, we define two variables, i call it developement mode 'dev-mode', that way i'm not submitting anything to google while i am working on my app, and the production mode once the application is deployed, and this is orchestrated by the value of the "process.env.NODE_ENV".

Keep in mind that running "npm run build" will set the environement to production.

Testing everything is fine

Once done, you can browse any page of yours, on chrome navigator under windows OS, you can press "ctrl+u", it will pop up the page source code, then check whether the google tag on the html head is well configured, and it takes into account node environment. Also you can check your google analytics account, and see if it starts collecting data.

It could take sometimes if it is the first time you set it up, just be patient, and make sure whenever you check the html source code of any page of yours that your google tag is visible.

How to submit a form to an api...How to get the previous URL in...