vercel / next.js

The React Framework
https://nextjs.org
MIT License
126.88k stars 26.97k forks source link

script tag in next/head avoids loading of google tag manager #40957

Open nadinetetz opened 2 years ago

nadinetetz commented 2 years ago

Verify canary release

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6000
Binaries:
  Node: 16.13.2
  npm: 8.1.2
  Yarn: 1.22.17
  pnpm: 7.0.1
Relevant packages:
  next: 12.3.2-canary.10
  eslint-config-next: 12.3.1
  react: 18.2.0
  react-dom: 18.2.0

What browser are you using? (if relevant)

Chrome 105.0.5195.125

How are you deploying your application? (if relevant)

No response

Describe the Bug

I followed the example of how to add the google tag manager to a nextjs application. This works, but when I add a custom script tag via next/head the google tag manager is no longer added and the <meta charset="utf-8"> is duplicated.

Expected Behavior

The custom script and the google tag manager are in the head and no meta tags are duplicated.

Link to reproduction

https://github.com/nadinetetz/nextjs-gtm-issue

To Reproduce

eob commented 1 year ago

I believe we are seeing this bug as well; was a resolution ever found?

jahilldev commented 10 months ago

I think we're running into this too. We're including GTM via the <Script /> component, but once the GTM script has loaded, none of the custom HTML tags are ever run. The GTM debugger shows the tags as having "fired", but the logic within is never executed.

My working theory is:

  1. GTM initialises, fires the tags, and injects the scripts in the document
  2. Next.js / React decides to re-render for whatever reason
  3. As the scripts injected by GTM are not known to React, they're removed in the reconciliation
  4. End result is that it seems like these GTM tag scripts are never being run

This seems related to the following: https://github.com/vercel/next.js/issues/11012

A possible fix is here: https://github.com/vercel/next.js/pull/47938

Has anyone found a solution to this? My last resort is to update Next to 13.5.3, but I'd prefer not to as that will involve quite a bit of extra work at this point.

EDIT Our issue actually stemmed from something completely different.. an engineer had patched Node.prototype.insertBefore in a non-compliant way, causing GTM to be unable to write to the DOM. Hence, no tags were executed. Took a while to identify. Moral of the story... NEVER modify native browser API's people..