Tailwind Logo

Setting up Google Tag Manager in Next.js (App Router)

Next.js

Published: 2023-09-01

I would like to set up Google Tag Manager for the Next.js App Router sample I created last time. By using this, we can easily integrate with other Sitecore products as well as analytics.

Articles introduced so far

We have introduced two methods of setting up Google Tag Manager in Next.js. Both of them are based on Page Router, not App Router.

In this issue, we will check how to set up GTM when using Next.js' App Router introduced in the previous issue.

Creating .env file

Create an .env file to manage Google Tag Manager keys. In this case, we will create a key with the following name

Plain Text
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=your-GTM-key

Install dotenv in the root of the project so that this value can be read.

Plain Text
npm install dotenv

Now you can load the key. Next, create a library to load Google Tag Manager as follows

TypeScript
// lib/gtm.ts
type WindowWithDataLayer = Window & {
  dataLayer: Record<string, any>[];
};

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,
    });
  }
};

Next, create a component to display Google Tag Manager tags.

TypeScript
// components/Analytics.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 Analytics() {
  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}');
  `,
        }}
      />
    </>
  );
}

Now you are almost ready. Finally, add the following to layout.tsx

TypeScript
import { Suspense } from "react";
import Analytics from "@/components/Analytics";

Rewrite body as follows

TypeScript
      <body>
        <Suspense>
          <Analytics />
        </Suspense>
        {children}
      </body>

This completes the work.

Operation check

Check to see if the code is reflected correctly. Please execute as follows.

PowerShell
npm run dev

If you check the code from your browser, you will see that the GTM code is displayed.

nextjsgtm.png

We have made the sample code available for reference below.

Summary

We were able to successfully add a tag manager. This also enabled Google Analytis and others, so we can check if there is traffic to the site, although it is not much.

Related article

Tags