Search code examples
javascriptreactjsnext.jsgoogle-tag-manager

Scripts duplicating within Google Tag Manager & React/Next


So, I'm currently working with Google Tag Manager and React + Next.js for the first time and it's proving an interesting experience as I haven't used GTM a great deal and React even less so, but it's not necessarily a bad experience and I am gradually figuring out the nuances.

However, I'm having to use GTM to add some custom elements to a site because it's using a set platform and CMS which I can't change. I was initally having an issue with the elements being removed upon a history change because React doesn't treat it as a new page load, so the elements added via GTM would get removed but the tags wouldn't fire again.

I've managed to use the datalayer to make it so that tags will fire when they need to upon a history change, so the elements get added back in. But one thing I haven't been able to figure out though is stopping these tags getting injected multiple times into the site.

To elaborate, upon initial arrival on the site my tag scripts will get loaded in fine:

GTM scripts on site load

However, if I navigate to another page then the history change will trigger the tags again and load up the content again. But it will also add the scripts in to the footer AGAIN and I end up with duplicates because the React site will change the body but the header and footer code remains, and I end up with duplicate scripts tags, and then on each history change it will happen over and over.

GTM scripts duplicated upon history change

(Note: I obscured a couple of lines of code in the screenshot as it gave away some details that might break a NDA.)

I tried playing around with the tag firing options (once per page, once per event, etc.) to see if that helps but it didn't. So I'm not sure how to get these tags to fire when they should, but then not to inject the script over and over again.

Is it possible to fire the tag without it injecting the code over again? Am I missing something obvious?

Any help or insights would be appreciated.


Solution

  • Came up with my own solution in the end. I gave all custom scripts that were being injected an ID that began with "gtmScript", and then when the history change happens the scripts get removed before being injected again. This stops the repetition of scripts:

    var gtmScriptTag = document.querySelectorAll("[id^='gtmScript']");
    var i = 0;
    
    while (i < gtmScriptTag.length) {
        gtmScriptTag[i].remove();
        i++;
    }
    

    Might not be the most robust way of doing things, but it works and now I can move on.