How to set up Google Analytics through Google Tag Manager for Next-Js?
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>
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.