Next.js Discord

Discord Forum
\n \n \n `,\n }}\n />\n \n {children}\n \n \n \n );\n}I would really appreciate your help","dateCreated":"2023-11-16T18:06:00.000Z","answerCount":3,"author":{"@type":"Person","name":"Dovekie"},"suggestedAnswer":{"@type":"Answer","text":"I think you mixed your code a bit up. First things first: there is no head in app dir root layout: https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-requiredSecond: everything that will be passed into a

GTM not working in NextJS13 App router

Unanswered
Dovekie posted this in #help-forum
Open in Discord
DovekieOP
Hello everyone, I'm in a huge rush cuz our company is losing valuable data. I'm trying to make GTM work but for some reason it doesnt. When I go to the chrome console and try to log dataLayer its undefined. Here is the code:


export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const GTM_ID = "GTM-XXXXXXXX";

  return (
    <html lang="en" className="h-full">
      <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_ID}');
          `}
        </Script>
      </Head>
      <body className="min-h-screen bg-background h-full">
        <noscript
          dangerouslySetInnerHTML={{
            __html: `<iframe src="https://www.googletagmanager.com/ns.html?id=${GTM_ID}" height="0" width="0" style="display: none; visibility: hidden;" />`,
          }}
        />
        <ClerkProvider>
          <SideNav>{children}</SideNav>
        </ClerkProvider>
      </body>
    </html>
  );
}


I would really appreciate your help

3 Replies

I think you mixed your code a bit up. First things first: there is no head in app dir root layout: https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required

Second: everything that will be passed into a <Script>-Tag will be automatically placed inside the head. Let me know if this works for you
@Dovekie does it help?
Saltwater Crocodile