Ignite Online
Ignite Online

Reputation: 26

Google Tag Manager not functioning on page change in Next.js using 'react-gtm-module'

I am working on a Next.js application and have integrated Google Tag Manager (GTM) using the react-gtm-module package. Everything functions correctly upon the initial load of the application in debugging mode, regardless of which page it starts on. However, when I navigate to a different page within the application, the tags stop working. Google Tags does detect the page change, but it displays a strikethrough on the tag / event with no additional information provided.

I have set up triggers in GTM to detect all page changes. Below is the code structure I am using to initialize GTM and to trigger events:

import GTM from 'react-gtm-module';

useEffect(() => {
  const tagManagerArgs = {
    gtmId: 'GTM-NTFG983',
    // Other optional GTM parameters
  };
  GTM.initialize(tagManagerArgs);
}, []);

export function gtmEvent(event: string) {
  if (!window.dataLayer) return;
  window.dataLayer.push({ event });
}

I have confirmed through logs that the code is being triggered at the appropriate times. Additionally, I have ensured that the script and noscript tags have been correctly added to my code as per the documentation of react-gtm-module. Using the network inspector, I verified that the initialization and additions to the data layer are going through successfully with a 200 status response. Despite these verifications, the tags do not function as expected on page change.

I am seeking guidance on how to troubleshoot this issue, or any insights on why this might be happening and how to rectify it. Is there anything specific with Next.js, react-gtm-module, or GTM that might cause this behavior? Any help or suggestions would be greatly appreciated.

Upvotes: 0

Views: 4223

Answers (1)

Davin
Davin

Reputation: 239

Your setup sounds similar to ours with React and Next.js. We had a similar problem a while back. For us, our website behaved as a single-page application, so the first page view fires because it's a regular page load; subsequent page views don't trigger because, even though the URL changes, it's not a true pageview, at least not in the same sense that tag manager understands.

Our solution was to set additional triggers to fire scripts again based on history changes. We created these two triggers one for push, which fires after a button or link on the page is clicked: enter image description here and pop to track back and forward button clicks. enter image description here

And then we added them to all tags that we needed to fire on every page view: enter image description here

I'm unsure if it's the best solution, but it's worked for us for a couple of years now.

Upvotes: 3

Related Questions