Adding GTM to Your Next.js Website: A Guide

In today's digital age, data is everything. It provides valuable insights into your website's performance, user behavior, and marketing campaigns. But collecting this data can be a complex and time-consuming process, especially if you have to manually insert tracking codes into your website's codebase. This is where Google Tag Manager (GTM) comes in. GTM is a powerful tool that simplifies the process of managing and deploying tracking tags, allowing you to collect valuable data without the need for manual code changes. In this article, we'll explore how to implement a GTM container on your website and how it can help improve your website's tracking and analytics capabilities.

Before we dive into how to set up Google Tag Manager (GTM) for your Next.js website, there are a few prerequisites you'll need to meet. First and foremost, you'll need a Next.js website up and running. Secondly, you'll need a GTM account, which you can sign up for free on the Google Tag Manager website. Once you have your account, you'll be provided with a GTM ID, which you'll need to access your container.

It's important to note that if you're setting up GTM for a single-page app (SPA), like a Next.js website, you'll need to manually track pageviews. This is because SPAs don't reload the entire page when users navigate through the website, making it difficult to track user behavior through traditional pageview tracking. However, this can be easily achieved through GTM with a little bit of configuration.

Now that we've covered the prerequisites, let's dive into how to set up GTM for your Next.js website.

Step 1: Setup helper functions in your Next.js project

The first step in setting up GTM for your Next.js website is to create two helper functions. The first one will store your GTM ID in a variable, and the second one will help track pageviews.

export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID // GTM-XXXXXXX

export const pageview = (url) => {
  window.dataLayer.push({
    event: 'pageview',
    page: url,
  })
}

Step 2: Add GTM script to the head of your Next.js project

The next step is to add the GTM script to the head of your Next.js project. This will allow GTM to track pageviews and other user behavior on your website. To do this, you'll need to use the _app.js file in your Next.js project. This file is used to initialize pages. You can learn more about it in the Next.js documentation.

import { GTM_ID, pageview } from '@/lib/gtm'
import { useEffect } from 'react'

export default function App({ Component, pageProps, router }) {
  // Track pageviews when route changes
  useEffect(() => {
    router.events.on('routeChangeComplete', pageview)
    return () => {
      router.events.off('routeChangeComplete', pageview)
    }
  }, [router.events])

  return (
    <>
      {/* Google Tag Manager - Global base code */}
      <Script
        id="gtag-base"
        strategy="afterInteractive"
        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_ID}');
          `,
        }}
      />
      {/* End Google Tag Manager - Global base code */}

      <main>
        <Component {...pageProps} />
      </main>
    </>
  )
}

Step 3: Add GTM script to the body of your Next.js project

The final step is to add the GTM script to the body of your Next.js project. This will allow GTM to To do this, you'll need to use the _document.js file in your Next.js project. This file is used to add global styles and scripts to your Next.js project. You can learn more about it in the Next.js documentation.

import Document, { Html, Head, Main, NextScript } from 'next/document'
import { GTM_ID } from '@/lib/gtm'

export default function Document() {
  return (
    <Html className="h-full antialiased" lang="en">
      <Head />
      <body>
        <noscript>
          <iframe
            src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
            height="0"
            width="0"
            style={{ display: 'none', visibility: 'hidden' }}
          />
        </noscript>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

That's it! You've successfully set up GTM for your Next.js website. To verify that everything is working as expected, you can check either the console in the browser for 'dataLayer' or the GTM preview mode in your GTM console.