How to add google analytics to your Next.js application

Prefer to watch a video? This tutorial is now available on YouTube.

To add google analytics to your Next.js application, first add a new environment variable. You may also need to add this variable where you are hosting your site.

.env
GOOGLE_ANALYTICS="<your ga tag goes here>"

Then, either in your _app.js, or if you have one, _document.js file, add the following in the Next.js Head tag:

_app.js
<Script
  strategy="lazyOnload"
  src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GOOGLE_ANALYTICS}`}
/>

<Script id="ga-script" strategy="lazyOnload">
  {`
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '${process.env.GOOGLE_ANALYTICS}', {
      page_path: window.location.pathname,
    });
        `}
</Script>

And there you have it, you have added google analytics to your Next.js application!


Image of the Author, Ryan Carmody

About the Author

Open for work

Hi, I'm Ryan from Adelaide, South Australia.

I'm a web developer and computer science tutor. I also rock climb, play wheelchair basketball and brew beer.

Check out some of the games I made

Smug Chicken

Smug Chicken

The daily AI art word game.

Searchle

Searchle

How does google autocomplete this search?

WhereTaken

WhereTaken

Guess the country from a photo.

Retro Snake Game

Retro Snake

Eat the food but don't hit the walls or your own body!