Skip to content

[Notes] React x Google Tag Manager: Monitoring page views and history changes

Google Analytics(GA) and Google Tag Manager(GTM) are very useful tools to leverage for analytics in early stage React apps. This is a note; so I will directly jump into the tutorial part and be concise about the steps.

Step 1: Setup GA4 in Google Analytics (Create Account -> Create Property -> GA4), have a data stream ready, e.g. a website configured

Step 2: In GTM, create new workspace and configure the website too

Step 3: In Triggers Tab, add a new trigger: History Change is available as a default type of trigger, which uses HTML5 history APIs to get url changes. We need this in additional to traditional GA since react is a Single Page App. Optionally can set up a filter on page hostname to get results only in production environment.

Step 4: In Tags Tab, add a new tag: for tag type select Google Analytics: GA4 Configuration. And paste in GA4’s measurement ID got from GA. For associated triggers: select All Page View (by default) and History Change.

Step 5: In react app, npm install react-gtm-module --save

Step 6: My case is next.js so I added following code in _app.tsx

import React, { useEffect } from 'react';
import type { AppProps } from 'next/app';

import TagManager from 'react-gtm-module';
import ReactGA from 'react-ga'; // GA only, not necessary

const tagManagerArgs = {
  gtmId: "GTM-XXX",
}

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    TagManager.initialize(tagManagerArgs);
    ReactGA.initialize("UA-XXX-1"); // GA only, not necessary
  }, []);

  return <Component {...pageProps} />
}

export default MyApp

Step 7: back to GTM page, start preview mode and enter the url will start the debugger; having any url change will fire the history change. Check if it works and we are done tracking history changes! One use case is to track users and views on different page paths.

Step 8: Don’t forget to publish the changes! And then back in GA if we select the right view then we are able to see the results either in RealTime tab or Life Cycle: Engagement -> Pages and Screens

1 thought on “[Notes] React x Google Tag Manager: Monitoring page views and history changes”

Leave a Reply to Chad Cancel reply

Your email address will not be published. Required fields are marked *