Introduction

Google Analytics is a powerful and free tool that will give you invaluable information about your website and visitors.

Here are a few pieces of data Google Analytics provides:

  • Traffic for each page.
  • Overall traffic that your entire website gets.
  • Demographic information for your visitors.
  • What devices your visitors use (mobile, desktop, etc.).
  • The websites your traffic comes from.

In this article, we'll get your Next.js website configured with Google Analytics.

First, we'll go over how to obtain a Google Analytics Measurement ID. Then, we'll walk through how to get Google Analytics tracking on your Next.js website.

Let's get started!

Table Of Contents

Obtain A Google Analytics measurement ID

First, go to the Google Analytics website: https://analytics.google.com.

On the landing page, press the Set up for free button (or whatever specific messaging the button has) to begin the setup process.

Google Analytics Homepage

On the create account page, enter the name you want to give your account and the type of data you will allow Google to collect.

Hit the Next button when you're done.

Google Analytics Create Account

Google will then ask you for some information about your website.

When you're done entering that information, hit the Create button to create your new Google Analytics account.

They may also ask you to accept their Terms of Service before you can move on. So, scroll through that and accept their terms and press the I Accept button.

Google Analytics Property Details Terms of Service Agreement

If the process was successful, you'll be redirected to the dashboard for your new Google Analytics account.

They should automatically bring you to a page labeled "Set up a data stream to start collecting data".

On that page, click the Web button to set up a web stream.

That will take you to a page where you can enter the URL for your website and give the stream a name.

Google Analytics Setup a Web Stream Page

When you've entered your URL and given the stream a name, click the Create stream button to create the new stream.

On the next page, your measurement ID will be shown on the page.

Google Analytics Web Stream Details Page

Copy that ID and keep it handy.

We'll use it in the next step when we configure Google Analytics on your Next.js website.

Advertisement
Build A Hacker News Clone
Learn how to build and deploy a full-stack, production-ready application with Next.js, Node.js, and MongoDB.
View Course

Add The Measurement ID To Your Website

Now we're ready to get Google Analytics tracking your website using the unique measurement ID provided by Google.

Each time a page loads on your website, we'll want to call a script that sends data about the user's activity to Google Analytics. Your unique measurement ID needs to be included in that script so Google knows what account the data belongs to.

To do this, create a new file in your Next.js project named googleAnalytics.js:

    
      touch googleAnalytics.js
    
  

This file will hold a React.js component, so it should be placed alongside the other components for your application.

Open the new file in your editor and add this code to it:

    
      import { Component } from "react"
      import Head from "next/head"

      export default class extends Component {
        render() {
          return (
            <>
              {
                process.env.NODE_ENV === "production" && process.browser ?
                <Head>
                  <script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_MEASUREMENT_ID"></script>
                  <script
                    async
                    dangerouslySetInnerHTML={{
                      __html: `window.dataLayer = window.dataLayer || [];
                      function gtag(){dataLayer.push(arguments);}
                      gtag("js", new Date());

                      gtag("config", "YOUR_MEASUREMENT_ID");`
                    }}
                  />
                </Head> : null
              }
            </>
          )
        }
      }
    
  

In this code, we create a React component that will only render if the process.env.NODE_ENV environment variable is equal to "production". We only want Google Analytics to track data when the application is running in production mode.

If the code is running in production mode, we place the code for the component inside the <Head> element. This will add the code to the head metadata section of any page the component is applied to.

We also instruct the component to only render if the process.browser value is true. This ensures that the code only runs in the browser environment (as opposed to the code Next.js runs on the client-side).

By doing this, we stop the script from being called more than once on each page load.

Then, we use a <script> tag to initiate the Google Tag Manager script:

    
      <script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_MEASUREMENT_ID"></script>
    
  

This will make the Google Tag Manager script available to the component.

Make sure you replace the YOUR_MEASUREMENT_ID portion of the script's src with your measurement ID.

After that, we use the dangerouslySetInnerHTML() method to inject the Google Analytics script into the page.

That code is what will send the data to Google Analytics.

    
      <script
        async
        dangerouslySetInnerHTML={{
          __html: `window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag("js", new Date());

          gtag("config", "YOUR_MEASUREMENT_ID");`
        }}
      />
    
  

Make sure you replace the YOUR_MEASUREMENT_ID in that code with your measurement ID.

This component can now be imported and used on any page you want Google Analytics to track.

Serving as an example, let's implement the function on the homepage of your website.

Open the homepage (i.e. /pages/index.js) file in your editor.

First, import the /components/googleAnalytics.js file:

    
      import GoogleAnalytics from "../components/googleAnalytics.js"
    
  

Then, add the component to the file:

    
      <GoogleAnalytics />
    
  

To ensure that the script is properly placed in the <Head> section of the web page, position the component as the first element inside the return () method.

Serving as an example, view the sample React page code below:

    
      import { Component } from "react"

      import GoogleAnalytics from "../components/googleAnalytics.js"

      export default class extends Component {
        render () {
          return (
            <>
              <GoogleAnalytics />

              // Your page's content goes here.

            </>
          )
        }
      }
    
  

Using the homepage as an example, you'll need to make the same code updates for each page on your website that you want to be tracked in Google Analytics.

When you're done making the code updates for each page, save your changes and deploy them to whatever production environment your application runs in.

After you've deployed your code changes to production, go back to the Google Analytics dashboard in your browser and view the "Realtime" page.

You should see visitor data displayed on that page.

Google Analytics Dashboard Summary

Google Analytics is now up and running for your website.

As always, thanks for reading and happy coding!