Skip to main content

Command Palette

Search for a command to run...

Track User Behaviour On Your Website With Google Analytics & Next.JS

How To Set Up Google Analytics With Next.JS Script Component

Published
β€’5 min read
Track User Behaviour On Your Website With Google Analytics & Next.JS
J

A software engineer turned developer relations engineer in the web3 space, from Australia πŸ‡¦πŸ‡Ί.

Introduction

In this blog post, we'll go through how to set up Next.JS with Google Analytics using the latest versions (Next.JS 11 and Google Analytics 4).

As part of Next.JS 11, the new Script Component was added, to automatically prioritize loading of third-party scripts to improve performance.

Google Analytics is a great, free way to track the performance of your web and mobile applications. If you'd like to learn more about the new features in Next.JS 11, check out my previous blog post here:

For Video Lovers 😍

TLDR:

If you've already got your site and your Google Analytics account set-up, simply add the below code snippet in your _app.js file, and replace the G-XXXXXXXXXX with your Google Analytics measurement ID.

If you haven't got everything prepared yet, let's continue on to the first step of setting up Google Analytics with Next JS, below this snippet.

_app.js:

import Script from "next/script";

// ...

// This code belongs ABOVE the <Head> tag in your _app.js file's return.

{/* Global Site Tag (gtag.js) - Google Analytics */}
<Script
  strategy="lazyOnload"
  src={`https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX`}
/>

<Script strategy="lazyOnload">
  {`
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'XXXXXXXXXX', {
        page_path: window.location.pathname,
      });
  `}
</Script>

Step 1: Creating a Google Analytics Property

The absolute first thing we'll need to do for those starting from scratch is to create a Google Analytics Property.

To do that, you'll first need to go to Google Analytics and sign in with your Google Account.

Before creating a Property, you'll need to create an account within Google Analytics.

image.png

The next step will allow you to create a property within your newly created Google Analytics account:

image.png

Set up your Google Analytics 4 property with the settings to your liking, and meet us at the next step!

Step 2: Creating a Data Stream in Google Analytics

Once you have successfully created your Google Analytics property, we'll need to create a Data Stream to start collecting data from our website.

image.png

Since we're using Next.JS, I'll create a Web Data Stream.

Enter a Name and the url of your website, and click Create Stream:

image.png

Once you've created the stream, you'll hopefully be shown the tag to put into your application, copy this code somewhere because we'll be coming back to it later. image.png

Step 3: Setting Up The Next.JS Project.

If you already have an existing Next.JS Project you'll need to upgrade to Next.JS version 11 to use the Script component, to do that, run:

npm install react@latest react-dom@latest

npm install next@latest

For those starting with a new Next.JS project, we'll create a new project by running:

npx create-next-app my-app-name

Step 4: Placing the Script Components

Open up your newly created project in the text editor of your choice.

_app.js

Next.js uses the App component to initialize pages. You can override it and control the page initialization.

_app.js Allows you to write code that will impact ALL of your pages - so it is the perfect place for us to create the Script components.

Our default _app.js file looks like this:

import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Let's modify it to place our Google Analytics tracking tags on every page.

Firstly we will need to import the Script component from Next.

import Script from 'next/script'

Then, modify our return code to look like this:

Replacing XXXXXXXXXX with your real Measurement ID.

return (
    <>
      <Script
        strategy="lazyOnload"
        src={`https://www.googletagmanager.com/gtag/js?id=XXXXXXXXXX`}
      />

      <Script strategy="lazyOnload">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'G-XXXXXXXXXX');
        `}
      </Script>

      <Component {...pageProps} />
    </>
  );

Awesome! Now let's test out our code to make sure it's working correctly.

Step 5: Testing The Tags

To run your application on a web environment, run :

npm run dev

from the root of your project's directory.

This will bring up your web application at localhost:3000.

There are a number of checks we can make to ensure we have set up Google Analytics correctly.

The first one being opening up the Chrome Console by hitting the F12 key.

Type dataLayer into the console to see the events that have been sent by the analytics tag, like this:

image.png

Next, we can check our Real-time Overview in our Google Analytics Property. Here, you should see events coming through with information about which pages user's are visiting on your site.

image.png

Bonus: Environment Variables

To keep your Google Analytics measurement ID hidden from the public, you can utilize environment variables.

To use environment variables, create a .env.local file at the root of your project.

Create an entry into that file like this:

NEXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX

Then rather than hard-coding your measurement ID into the script, change it to reference that environment variable, like so:

return (
    <>
      <Script
        strategy="lazyOnload"
        src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
      />
      <Script strategy="lazyOnload">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', ${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS});
        `}
      </Script>
      <Component {...pageProps} />
    </>
  );

Conclusion

The new Script Component and the utilization of the lazyOnload strategy, is a great way to set-up Google Analytics without hurting the performance of your website, in Next.JS 11.

With next/script, you no longer need to use the _document.js or dangerouslySetInnerHTML, and also no longer need to include your scripts as part of the <Head> tag.

Next.JS's recent addition of the Script component is an amazingly simple way to implement Google Analytics across all of the pages in your Next.JS application.

Connect With me!

Buy me a coffee β˜•

YouTube: youtube.com/channel/UCJae_agpt9S3qwWNED0KHcQ

Twitter: twitter.com/JarrodWattsDev

GitHub: github.com/jarrodwatts

LinkedIn: linkedin.com/in/jarrodwatts

Website: jarrodwatts.com

O
offline4y ago

Hey, I was getting a compilation error with this because Script requires an id. So after giving it an id, everything worked. Putting this here, if that helps anyone.

But even doing so, I get undefined when typing dataLayer in Dev tools. So I'm kinda stuck ATM.

edit: FIXED the issue. If anyone is having similar issues, follow these instructions:

  1. Give the Script any id string value.
  2. Set the strategy to afterInteractive instead of lazyOnLoad
A
Avi R4y ago

For some reason I got the following error :

Unhandled Runtime Error SyntaxError: Invalid or unexpected token

I had to change the code to :

<Script strategy="lazyOnload">{`
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

   gtag('config','${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}');
    `}
</Script>

to fix the error. I could have said that your code has an issue but then your video did not show any issues.

H

Hey Jarrod Wattsthanks very much for this. A question, is this the same as setting up google tag manager or that is a different thing?

E

Nice article Jarrod Watts, thanks. Quick Note: I think the XXXXXXXXXX in the gtag('config', ... line also needs to be prefixed with G- making it G-XXXXXXXXXX. Thanks.

T
Thys4y ago

How would you track router changes with this solution?

1
J

This tag gets applied on every page since we're using it in the _app.js file - hopefully that answers your question

A

Great article you reminded me that I have not checked the analytics for my website in a very long time. I imagine I have a lot more traffic now that I am more active in the community.

1
J

Thanks Andrew! For sure, I should definitely check my own analytics more too.

I've got GA setup for my Hashnode blog.jarrodwatts.com domain, which lets me know how much time people are spending on average on each of my posts which is a great feature.

I find that quite a meaningful measure of how much people are engaged with the content.

Glad you enjoyed the article!

K

Really good article Jarrod Watts, we all need our fix of analytics!

2
J

Thanks Kieran! Haha, it can be scary but it's worth the small time required :)

More from this blog

Jarrod Watts' Blog

34 posts

I'm a software engineer turned developer relations engineer currently focussed on web3. I write a combination of opinion pieces of trends in the space and detailed tutorials to create real apps!