Search code examples
next.jsgoogle-tag-managerdotenv

Google Tag Not Found


I'm using this next.js repository as a guide: https://github.com/vercel/next.js/tree/canary/examples/with-google-tag-manager

The problem: When I put the Google Tag Manager ID direct in the scripts below it works perfectly. When I put the GTM ID inside the .env.local and then call them using ${process.env.NEXT_PUBLIC_GTM_ID} it returns me that the tag could not be found.

Can someone help me?

my _app.js:

<Script
        id="gtag-base"
        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', '${process.env.NEXT_PUBLIC_GTM_ID}');
          `,
        }}
      />

my _document.js:

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

my .env.local:

NEXT_PUBLIC_GTM_ID=GTM-XXXXXXX

I replaced the ID as it is personal information.


Solution

  • I think you need to change some stuff to be ready to go, but I will also give you some suggestions regarding implementation.

    1. Make sure your .env file is at the root folder and not inside ./src/
    2. Remove NEXT_PUBLIC_ from the key, leaving just GTM_ID (do not expose keys with NEXT_PUBLIC_)
    3. Wherever you use the key change it to be process.env.GTM_ID
    4. Change the strategy to be lazyOnLoad instead of afterInteractive
    5. If you server is running, stop it and then run again