OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to add Google Tag Manager to a NextJS website

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Guest
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:

Code:
 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:

Code:
 <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:

Code:
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:

Code:
"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.

<p>From <a href="https://stackoverflow.com/a/68739242/667903">this answer</a> and <a href="https://morganfeeney.com/guides/how-to-integrate-google-tag-manager-with-nextjs" rel="noreferrer">this article</a> I've added a <code><Script></code> in order to add Google Tag Manager to my NextJS website:</p>
<p><code>components/layout.tsx:</code></p>
<pre><code> 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='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-xxxx');
}
</Script>
</code></pre>
<p>However, the script is not present on the front end.</p>
<p><code>components/layout.tsx</code> is the only file on my website with a <code><Head></code> or <code><head></code>.</p>
<p>The Google Tag Manager <code><noscript></code> is present on the front end, used in <code>app/layout.tsx:</code></p>
<pre><code> <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;" />,
}}
/>
</code></pre>
<p>so I know I've saved all changes.</p>
<p>Help appreciated.</p>
<p><strong>Update</strong></p>
<p>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.</p>
<p>My only problem is not being able to load Google Tag Manager properly before publishing to my domain.</p>
<p>There is no <code>_app.js</code> in the project.</p>
<p>There is <code>/app/(website)/layout.tsx</code>:</p>
<pre><code>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>
);
}
</code></pre>
<p>This is <code>/app/(website)/providers.tsx</code>:</p>
<pre><code>"use client";

import { ThemeProvider } from "next-themes";

export function Providers({ children }) {
return (
<ThemeProvider attribute="class" defaultTheme="light">
{children}
</ThemeProvider>
);
}
</code></pre>
<p>If I search VSCode for <code>RootLayout</code>, nothing calls it, so I am a bit confused about which is the main file.</p>
<p>If you'd like access to the Github repo, I can provide it.</p>
 

Latest posts

Top