A Comprehensive Guide to Embedding Google Tag Manager in Next.js Sitecore Projects

Streamlining user interaction tracking in headless CMS environments

February 22, 2024

By Sohrab Saboori

In the dynamic world of web development, incorporating analytics tools such as Google Tag Manager is crucial for monitoring user interactions and gauging website performance. However, the landscape becomes more challenging with headless CMS architectures like those in Next.js Sitecore SXA or XM Cloud. The traditional methods of integration are often inadequate due to the lack of a _document file in these headless environments, necessitating the exploration of alternative strategies for effective integration.

This guide will dive into the complexities of integrating Google Tag Manager and Google Analytics with Next.js Sitecore SXA or XM Cloud. We will examine various available methods, highlight their advantages and disadvantages, and provide detailed instructions for a smooth setup. Whether you are an experienced developer or new to headless CMS, this guide aims to provide the necessary insights to successfully incorporate these essential analytics tools into your Next.js Sitecore projects despite the absence of the conventional _document approach.

Method 1: Using Custom React Components

Step 1: Create the CustomScript Component

Create a file named CustomScript.tsx in your components directory. This component will be responsible for injecting the GTM script into your application.

import Head from 'next/head';
import Script from 'next/script';

const CustomScripts = ({ locale }) => {
  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtm.js?id=${process.env.NEXT_PUBLIC_GTM_ID}`}
        strategy="afterInteractive"
      />
      <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','${process.env.NEXT_PUBLIC_GTM_ID}');
          `,
          }}
        />
      </Head>
    </>
  );
};

export default CustomScripts;

 

In this component, we're using the next/script component to load the GTM script asynchronously after the page becomes interactive. We also use the dangerouslySetInnerHTML prop to inject the GTM initialization script into the of the document.

The CustomScripts component provides a centralized location for managing all your third-party scripts, including Google Tag Manager, cookie consent scripts, and other analytics or marketing tools. By consolidating these scripts into a single component, you can easily add, remove, or update them as needed, ensuring a more organized and maintainable codebase. This approach not only simplifies script management but also enhances the overall performance and security of your Next.js Sitecore XM Cloud or SXA project.

Step 2: Create the GTMNoscript Component

Create a file named GTMNoscript.tsx in your components directory. This component will add the GTM noscript fallback for users who have JavaScript disabled in their browsers.

const GTMNoscript = () => (
  <noscript
    dangerouslySetInnerHTML={{
      __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${process.env.NEXT_PUBLIC_GTM_ID}"
          height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
    }}
  />
);

export default GTMNoscript;

Step 3: Include the Components in _app.tsx

Open your _app.tsx file and import the CustomScripts and GTMNoscript components. Then, include these components inside the I18nProvider component, ensuring they are rendered on every page of your application.

import CustomScripts from 'components/CustomScript';
import GTMNoscript from 'components/GTMNoscript';

function App({ Component, pageProps }: AppProps<SitecorePageProps>): JSX.Element {
  const { dictionary, ...rest } = pageProps;

  return (
    <I18nProvider lngDict={dictionary} locale={pageProps.locale}>
      <>
        <CustomScripts locale={pageProps.locale} />
        <GTMNoscript />
        <Component {...rest} />
      </>
    </I18nProvider>
  );
}

export default App;

By following these steps, you will successfully integrate Google Tag Manager into your Next.js Sitecore XM Cloud or SXA project, allowing you to track user interactions and analyze website performance effectively.

Method 2: Using a Third-Party GoogleTagManager Component

For a more streamlined approach, you can utilize a third-party GoogleTagManager component or create a custom one to handle the integration. This method simplifies the process by encapsulating the GTM script logic within a reusable component.

Step 1: Install or Create the GoogleTagManager Component

If you're using a third-party library that provides a GoogleTagManager component, install the library according to its documentation. Alternatively, if you've created your own custom component, ensure it's properly set up to include the GTM script and noscript fallback.

//https://www.npmjs.com/package/@next/third-parties
npm i @next/third-parties

Step 2: Import the GoogleTagManager Component

Include the GoogleTagManager component in your _app.tsx file, passing in your GTM ID as a prop. Place it outside the main component to ensure it's rendered on every page.

import { GoogleTagManager } from '@next/third-parties/google';
function MyApp({ Component, pageProps }) {
  return (
    <>
      <GoogleTagManager gtmId="GTM-XYZ" />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

By using this method, you simplify the integration process and keep your codebase organized. The GoogleTagManager component can be easily reused across different projects or environments, making it a convenient solution for adding GTM to your Next.js Sitecore XM Cloud or SXA project.

Mastering GTM Integration in Next.js Sitecore Projects

Integrating Google Tag Manager (GTM) into a Next.js Sitecore XM Cloud or SXA project is essential for effective analytics and tracking. While the headless nature of these platforms presents unique challenges, such as the absence of a traditional document file, there are still viable methods to achieve this integration. Whether you choose to manually create custom components or leverage a third-party GoogleTagManager component, both approaches offer a way to incorporate GTM into your project, enabling you to track user interactions and gain valuable insights into your website's performance. By following the steps outlined in this guide, you can ensure a seamless setup of GTM in your Next.js Sitecore project, ultimately enhancing your site's analytics capabilities and providing a better understanding of your audience's behavior. Remember, the key to successful integration lies in choosing the method that best aligns with your project's structure and your team's expertise.

Photo of Fishtank employee Sohrab Saboori

Sohrab Saboori

Senior Full-Stack Developer

Sohrab is a Senior Front-End Developer with extensive experience in React, Next.js, JavaScript, and TypeScript. Sohrab is committed to delivering outstanding digital solutions that not only meet but exceed clients' expectations. His expertise in building scalable and efficient web applications, responsive websites, and e-commerce platforms is unparalleled. Sohrab has a keen eye for detail and a passion for creating seamless user experiences. He is a problem-solver at heart and enjoys working with clients to find innovative solutions to their digital needs. When he's not coding, you can find him lifting weights at the gym, pounding the pavement on the run, exploring the great outdoors, or trying new restaurants and cuisines. Sohrab believes in a healthy and balanced lifestyle and finds that these activities help fuel his creativity and problem-solving skills.