Implementing Google Analytics and Google Tag Manager into a Nextjs App

Raazesh Prajapati
readytowork, Inc.
Published in
3 min readFeb 20, 2023
fig:Nextjs+google tag manager + google analytics

Recently I was assigned a task to implement Google Tag Manager on my ongoing office project to collect user behavior data in Google Analytics. This was new for me. Then I started my RnD on GA and GTM. In this article, we gonna discuss my finding on implementing GA and GTM.

Terminology

  • GA — Google Analytics, now Google Universal Analytics a.k.a. “GUA”
  • GTM — Google Tag Manager

First of all, what are GA and GTM?

Google Analytics (GA) is a free tool or service by Google, that provides services for us(owners) to use it for business purposes, marketing, tracking, and analyzing website traffic and user behavior on our website. Basically, it is used to analyze our website and visitor help to enhance our business.

Google Tag Manager (GTM) is another free tool offered by Google to manage and deploy tracking tags on our websites without modifying our website’s source code. A tag is a code to collect data and send it to a third-party analytics tool, or marketing and advertising tool in our case it is Google Analytics (GA).

In simple words, GA is used by the owner, management team, and marketing team whereas GTA is used by the developer, software engineer, and coding team.

IMPLEMENTING GTA IN OUR PROJECT

In my task, I was provided a code snippet that looks like this:

<!-- Google Tag Manager -->
<script>(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 ID>');</script>
<!-- End Google Tag Manager -->

Basically, this code is only accessed by the GTM admin(in my case my boss), he copied this from the Admin > Install Google Tag Manager section in GTM.

Then I follow the instructions provided by Google:

Google suggested Implementation:

Step1:
If we don’t have a Nextjs app we can create it by the command:
npx create-next-app@latest
# or
yarn create next-app
# or
pnpm create next-app

We can find more of Nextjs here.

Step2:Changing provided code snippet to fit jsx/tsx.

Then we can change the provided code snippet to something like this:

<!-- Google Tag Manager -->
<script
type="text/javascript"
async
dangerouslySetInnerHTML={{
__html: `
(function(w, d, s, l, i) {
w[l] = w[l] || []
w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" })
const 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 ID>")`,
}}
/>
<!-- End Google Tag Manager -->

This is done to fit code snippets in jsx/tsx.

Step3:

Paste the above code snippet inside of the <Head> of “next/document” in _document.tsx or <Head> of “next/head” in _app.tsx

Step4:

Additionally, paste this code immediately in the <body> section of _app.tsx:

<!-- Google Tag Manager (noscript) -->
<noscript>
<iframe
src={`https://www.googletagmanager.com/ns.html?id=<GTM ID>`}
height="0"
width="0"
style={{ display: "none", visibility: "hidden" }}
></iframe>
</noscript>
<!-- End Google Tag Manager (noscript) -->

In a pinch, you can take this code snippet above and swap out “<GTM ID>” with your own GTM ID.

Alternate Implementation(Implementating with the help of react-gtm-module package)

If you don’t want the above hectic method there is an easy method in which we use a package named react-gtm-module.

Step1:Installing react-gtm-module package

We can install react-gtm-module by the command:

npm install react-gtm-module --save
# or
yarn add react-gtm-module

Step2:Inserting the tracking code

You can paste the below code in _app.tsx inside useEffect hook, which looks something like this:

function MyApp({ Component, pageProps }) {
useEffect(() => {
TagManager.initialize({ gtmId: '<GTM ID>' });
}, []);
return <Component {...pageProps}/>
}
export default MyApp

Conclusion

Here we discuss the implementation of Google Analytics and Google Tag manager in two different ways, there are so many other methods available on the internet we can use any of them. The above method doesn’t track internal page navigations, for that we have to add a history change trigger which we will discuss in upcoming articles. Thank you!!!

Happy Coding!!!

--

--