How to fix incorrect Page Title for pageviews sent using history listener (React & Next.js)

While I was implementing Netlify form tracking on a Next.js app, I stumbled on a problem when tracking page views with Google Analytics and Google Tag Manager.

First, you can’t use (just) the built-in “All Pages” trigger because it only fires once the user lands on the page of the website and not on every subsequent page. More info about how SPA’s work in this article that gave me the idea for a solution in the first place.

So the problem with the incorrect Page Title in GA started when I used the “History Change” trigger in GTM alongside the “All Pages” trigger for tracking page views. This is the exact problem I was facing, basically while browsing around the site, I saw correct page paths in GA real-time report but the Page Titles were recorded incorrectly, I would see the page titles that would match the previous page.

Step 1: Incorrect Page Title solution

The solution was to implement the virtual “pageview” event that could be used to trigger GA pageviews and correctly record the proper Page Title.

// make sure to import the useEffect hook if not already
import { useEffect } from "react";

const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        event: "pageview",
        pageTitle: document.title,
      });
    };

    router.events.on("routeChangeComplete", handleRouteChange);

    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off("routeChangeComplete", handleRouteChange);
    };
  }, []);

Next.js offers a route component that can be used to track the state of the URL. It allows us to change the URL, add queries to it but in this case, we are using it to listen to events.

We can see a list of router events that we can listen to, we are looking for routeChangeComplete so we can detect a successful page change.

In the layout of our entire app, we can use the useEffect react hook to initialize on load listener for our event. Once the event has been triggered we can get the document title and push it using our dataLayer

Step 2: Use the data layer variable to assign page title value

So now when we have the correct page title in the data layer, we need to fetch it with the GTM data layer variable like this:

Correct page title data layer variable

We can now use this variable to send the correct page title with the Google Analytics tag (I’m using the UA tag in this example) like so:

Send the page title as a custom field to GA

We are setting the field “title” to the value of whatever the data layer from the previous step holds – if everything is done right, it should contain the correct page title.

Hope this solution works for you, if not feel free to reach out and hire me for any custom tracking needs you might have 🙂

5 thoughts on “How to fix incorrect Page Title for pageviews sent using history listener (React & Next.js)”

  1. Hi,
    it still showing me the previous page tile after I snip your code into this one “https://github.com/vercel/next.js/tree/canary/examples/with-google-tag-manager “

    Reply
    • Hi thank you for the feedback, turns out I forgot to add a very important step in this tutorial – grabbing the page title in the data layer variable and using it with Google Analytics page view tag, I’ll fix it now!

      Reply
  2. Hi

    I Solved this by using a different method.

    [Solution]

    1. Untick “Send a page view event when this configuration loads ” from GA4 Configuration
    2. Enable Enhanced measurement from Google Analytics Data Stream. (Enable everything)
    3. Now on your _app.js add
    useEffect(() => {
    window.dataLayer.push({
    event: “Page Loaded”,
    // page: url,
        });
      }, []);
    4. Now go to Google Tag Manager Add a Trigger “Custom Event” and add Page Loaded as the event
    5. Now Add a Tag in Google Tag Manager “GA4 Event” and add page_view as the event name and attach a custom trigger “Page Loaded”.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.