Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up Google Analytics through Google Tag Manager for Next-Js?

formerly I was using react-ga npm module to insert google analytics in my next js app. and It was simply like this:

import ReactGA from 'react-ga'

export const initGA = () => {
  ReactGA.initialize('UA-*******-*', {
    titleCase: false
  })
}

export const logPageView = () => {
  if (window.location.href.split('?')[1]) {
    ReactGA.set({page: window.location.pathname + '?' + window.location.href.split('?')[1]})
    ReactGA.pageview(window.location.pathname + '?' + window.location.href.split('?')[1])
  } else {
    ReactGA.set({page: window.location.pathname})
    ReactGA.pageview(window.location.pathname)
  }
}

and then I was calling logPageView function in my header(that was inserted to every page of my app) like this:

  componentDidMount () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }
  componentWillReceiveProps () {
    if (!window.GA_INITIALIZED) {
      initGA()
      window.GA_INITIALIZED = true
    }
    logPageView()
  }

now I want to use Google Tag Manager to handle Analytics page view . How could I do this?

like image 312
Soorena Avatar asked Aug 23 '17 19:08

Soorena


People also ask

How do I add Google Tag Manager to next JS?

To get up and running you'll need to add the tag manager script to the <head> of each page, Google recommend adding it as high up in the DOM as possible. Prior to Next. js v11. 0.0 the simplest way to do this was by using the custom _document .

Can you have Google Analytics and Tag Manager?

Google Tag Manager is a free tool that allows you to effortlessly add and update your Google Analytics code and other tags on your site without having to manually write a single line of code. In this article, we'll show you the Google Tag Manager setup with Google Analytics.


2 Answers

In order to use Google Tag Manager you should inject your tag manager script on every page. since _document.js is the wrapper for every page, you should add the GTM script to _document.js in the head section like this:

<Head>
  <script dangerouslySetInnerHTML={{
    __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','GTM-*****');`,
  }}>
  </script>
  ...
</Head>

Now you are all set to use Google Tag Manager in your next-js app. You should only proceed to handle pageview and other analytics related stuff from your GTM dashboard.

To set up google analytics pageview for single page applications(like nextjs) you can follow these steps.

like image 55
Soorena Avatar answered Oct 11 '22 06:10

Soorena


There is no need for any special library and some answers here look uncomplete. Just add the script to <Head> and noscript to <body> in _document.js

import Head from 'next/document'  

<Head>
  <script dangerouslySetInnerHTML={{__html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
            j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
            'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
          })(window,document,'script','dataLayer','GTM-XXXXXX');`}} />
</Head>
    
<body style={{ margin: 0 }}>
   <noscript dangerouslySetInnerHTML={{ __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
        height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
      }}
    />
    <Main />
    <NextScript />
</body>
like image 28
Black Avatar answered Oct 11 '22 08:10

Black