Tailwind Logo

Setting up Google Tag Manager in Next.js - XM Cloud Edition

XM CloudNext.jsHeadless SXA

Published: 2022-12-12

You have published your XM Cloud site externally. To integrate with other services, we will first set up Google Tag Manager.

Configure Google Tag Manager in Next.js

We have blogged about this before, but this time we will implement it in a slightly different way.

We used to use react-gtm-module, but we will implement it without it. First, create the file src\sxastarter\src\lib\gtm.ts.

TypeScript
type PageViewEvent = {
  event: string;
  page: string;
};

type WindowWithDataLayer = Window & {
  dataLayer: PageViewEvent[];
};

declare const window: WindowWithDataLayer;

export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID;

export const pageview = (url: string) => {
  if (typeof window.dataLayer !== 'undefined') {
    window.dataLayer.push({
      event: 'pageview',
      page: url,
    });
  } else {
    console.log({
      event: 'pageview',
      page: url,
    });
  }
};

Then create a new component as src\sxastarter\src\components\GoogleTagManager.tsx

TypeScript
// components/GoogleTagManager.tsx
'use client';

import { GTM_ID, pageview } from 'lib/gtm';
import { usePathname, useSearchParams } from 'next/navigation';
import Script from 'next/script';
import { useEffect } from 'react';

export default function GoogleTagManager() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (pathname) {
      pageview(pathname);
    }
  }, [pathname, searchParams]);

  return (
    <>
      <noscript>
        <iframe
          src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
          height="0"
          width="0"
          style={{ display: 'none', visibility: 'hidden' }}
        />
      </noscript>
      <Script
        id="gtm-script"
        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}');
  `,
        }}
      />
    </>
  );
}

Then edit the file that imports the script: CdpPageView and Google Tag Manager side by side.

TypeScript
import CdpPageView from 'components/CdpPageView';
import GoogleTagManager from 'components/GoogleTagManager';

const Scripts = (): JSX.Element => {
  return (
    <>
      <CdpPageView />
      <GoogleTagManager />
    </>
  );
};

export default Scripts;

Finally, the value of the GTM_ID should be entered in the src\sxastarter\.env file.

Plain Text
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=

This completes the preparation.

Retrieve values from Google Tag Manager

Launch Google Tag Manager for use and obtain the necessary tags. First, go to the Tag Manager administration page.

gtm02.png

Click on Install Google Tag Manager and you will see the tags.

gtm03.png

As we have confirmed so far, there is no problem if the value set for NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID is the value displayed on the Google Tag Manager administration screen.

Set values for Vercel projects

Add the values obtained above as Vercel environment variables. Use the values in the table above and set them as they are.

gtm04.png

After setting up the above, I expanded the development branch and ran the build on Vercel again, and when I accessed it after completion, I was able to confirm that the tags had been added.

gtm05.png

Confirmation

Click the Preview button on the Google Tag Manager administration page.

gtm06.png

The Tag Assistant screen will then appear, as shown in the following screen. In this dialog, set the Web site for which you have already set a tag and click the `Connect` button.

gtm07.png

After a few moments, another window will launch and a dialog will appear on the lower right screen if the tag has been installed.

gtm08.png

Summary

You have successfully implemented Google Tag Manager on your site. Now you can use the tag manager to distribute tags as needed, such as Google Analytics settings, Moosend JavaScript, and so on. I am sure that you can find information about tag manager settings on various blogs, so please take a look at other blogs and use them as a reference.

Update Information

  • Sep 11, 2023 - Google Tag Manager code changed.

Tags