How to add google analytics to a Next.js app

Last updated on May 27, 2021 by Suraj Sharma



In this tutorial, you'll learn two ways to add google analytics to your next.js app,

  1. Using React dangerouslySetInnerHTML attribute,

  2. Using react-ga React library to setup Google Analytics,

  3. Using react-gtm-module React library to setup Google Tag Manager


A typical Google Analytics script looks like this


<script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', ${YOUR_TRACKING_ID});
</script>


1. Using dangerouslySetInnerHTML attribute


Adding the above script directly inside the Head component on your Next app does not work because React converts it to a string before rendering, which helps prevent cross-site-scripting attack.

However, you can use dangerouslySetInnerHTML attribute to add the GTM script inside your <head> element


First, Open your _document.js file and then use the below code to insert the script into <Head /> component


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

export default class MyDocument extends Document {
  render() {
    return (
      <html lang="en">
        <Head>
          <script async src="https://www.googletagmanager.com/gtag/js?id=${YOUR_TRACKING_ID}"></script>
          <script
            async
            dangerouslySetInnerHTML={{
              __html: `window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
            
              gtag('config', ${YOUR_TRACKING_ID});`
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}


2. Using React Google Analytics library


If you don't want to use dangerouslySetInnerHTML attribute to inject google analytics script into the <head> element then,

First, you can install react-ga library

Install react-ga npm module,

npm install --save react-ga

Next copy and paste the below code in your _app.js


import ReactGA from 'react-ga;

export default class MyApp extends App {
  componentDidMount() {
    ReactGA.initialize(`${YOUR_TRACKING_ID}`);
    ReactGA.pageview(window.location.pathname + window.location.search);
    ...
  }
  ...
}


3. Using React Google Tag Manager library


If your requirement is to setup google analytics using Google Tag Manager then, you can install react-gtm-module npm library


npm install --save react-gtm-module

After installing it, open your _app.js file and paste the following code,


import App from 'next/app';

import TagManager from 'react-gtm-module';

const tagManagerArgs = {
  gtmId: ${YOUR_GTM_ID}
}

export default class MyApp extends App {
  componentDidMount() {
    TagManager.initialize(tagManagerArgs);
    ...
  }
  ...
}

Now when you reload your website you can notice one 'Active Users right now' on your google analytics dashboard.


add google analytics to nextjs website



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.