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.
I think you need to change some stuff to be ready to go, but I will also give you some suggestions regarding implementation.