Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Google Tag Manager to a NextJS website

From this answer and this article I've added a <Script> in order to add Google Tag Manager to my NextJS website:

components/layout.tsx:

 import React from "react";
 import Head from "next/head";
 import Script from 'next/script'

 <!-- skip some code -->

 <Head>
    <link rel="preconnect" href="https://cdn.sanity.io/" />
    <link rel="dns-prefetch" href="https://cdn.sanity.io//" />
  </Head>
  <Script id="google-tag-manager" strategy="afterInteractive">
    {
      (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=%27+i+dl;f.parentNode.insertBefore(j,f);
      })(window,document,'script','dataLayer','GTM-xxxx');
    }
  </Script>

However, the script is not present on the front end.

components/layout.tsx is the only file on my website with a <Head> or <head>.

The Google Tag Manager <noscript> is present on the front end, used in app/layout.tsx:

 <body className="antialiased text-gray-800 dark:bg-black dark:text-gray-400">
    <noscript
      dangerouslySetInnerHTML={{
        __html: <iframe src="https://www.googletagmanager.com/ns.html?id=xxxx" height="0" width="0" style="display: none; visibility: hidden;" />,
      }}
    />

so I know I've saved all changes.

Help appreciated.

Update

I am new to NextJS, and all of this code is from a NextJS/Sanity template, which works locally and on a Vercel staging site.

My only problem is not being able to load Google Tag Manager properly before publishing to my domain.

There is no _app.js in the project.

There is /app/(website)/layout.tsx:

import "@/styles/tailwind.css";
import { Providers } from "./providers";
import { cx } from "@/utils/all";
import { Inter, Lora } from "next/font/google";

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-inter"
});

const lora = Lora({
  subsets: ["latin"],
  variable: "--font-lora"
});

export default function RootLayout({
  children
}: {
  children: React.ReactNode;
}) {
  return (
    <html
      lang="en"
      suppressHydrationWarning
      className={cx(inter.variable, lora.variable)}>
       <body className="antialiased text-gray-800 dark:bg-black dark:text-gray-400" >
        <noscript
          dangerouslySetInnerHTML={{
            __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-xxxx" height="0" width="0" style="display: none; visibility: hidden;" />`,
          }}
        />
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

This is /app/(website)/providers.tsx:

"use client";

import { ThemeProvider } from "next-themes";

    export function Providers({ children }) {
      return (
        <ThemeProvider attribute="class" defaultTheme="light">
          {children}
        </ThemeProvider>
      );
    }

If I search VSCode for RootLayout, nothing calls it, so I am a bit confused about which is the main file.

If you'd like access to the Github repo, I can provide it.

like image 635
Steve Avatar asked Sep 07 '25 15:09

Steve


1 Answers

Check out new NextJs Third-Parties Component

After watching the NextJS Conf2023, they released @next/third-parties because of people reporting in the past months after they followed the Google Analytics Documentation, it made bad perfomance issues on Lighhouse.

After following NextJs documentation guide, I was able to fully setup Google Analytics on NextJs 14.

1. To load Google Tag Manager for all routes, include the component directly in your root layout:

app/layout.tsx

import { GoogleTagManager } from '@next/third-parties/google'

export default function RootLayout({children}: {children: React.ReactNode}) {
    return (
        <html lang="en">
            <body>{children}</body>
            <GoogleTagManager gtmId="GTM-XYZ" />
        </html>
     )
}

2. To load Google Tag Manager for a single route, include the component in your page file:

app/page.js

import { GoogleTagManager } from '@next/third-parties/google'

export default function Page() {
    return <GoogleTagManager gtmId="GTM-XYZ" />
}

Note: This is the Official NextJs Documentation.

like image 64
Anda Hanise Avatar answered Sep 09 '25 04:09

Anda Hanise