Page-View using GA and GTM

2022.03.08

Introduction

Whenever a Single Page Application (SPA) is built, it’s always hard for the developers and product managers to track the user interaction with the website or web application. There are a lot of web tracking tools that won’t work as expected for a SPA. These tools were written only for traditional websites where the tracking code works only when the page loads.

Google Analytics is the omnipresent solution for analytics that pairs well with SPAs and with GTM configurations the procedure is made yet simpler.

GTM provides three ways in-order to collect page view.

  • Built-in tracking of GA 4 (Enhanced measurement).
  • Using a history change listener (within GTM).
  • With the Developer’s help, to push pageview data to the data layer on each navigation by the user.

The below content explains the procedure to achieve page tracking goals with the developer’s support. (method 3)

PageView React Setup

Step 1:

Make sure that the initial set up of GA and GTM into React is working fine, for further reference please check out this blog

Step 2:

Here is the code for pushing pageview data into the Data-layer every time a user navigates from one page to another.

ga.ts

export const pageview = (location: Location) => {
  const extractedTitle = location.pathname.split('/').slice(1).shift();
  window.dataLayer.push({
    event: 'pageview',
    page: {
      url: location.pathname,
      title: extractedTitle?.toUpperCase() ?? location.pathname,
    },
  });
};

Rather than implementing the above code on each page, create a custom component that invokes each time with the location change.

SetGoogleAnalytics.ts

import { useEffect, VFC } from 'react';
import { useLocation } from 'react-router-dom';
import { pageview } from '../util/ga';

export const SetGoogleAnalytics: VFC = () => {
  const location = useLocation();

  useEffect(() => {
    pageview(location);
  }, [location]);

  return null;
};

Now place the SetGoogleAnalytics component under the BrowserRouter in the root of your application.

src/app.ts

const App: VFC = () => {
  return (
    <BrowserRouter>
      <SetGoogleAnalytics />
      <Routes>/** routes */</Routes>
    </BrowserRouter>
  );
};

Step 3:

Verify if the data is being sent to the data layer using the global dataLayer variable window.dataLayer.

Here we are collecting event names, page URLs, and page titles. Every time a user goes to a particular section of your page, our little piece of JavaScript code will push the event name, URL and title to the Data-layer.

The below picture depicts the event pageview's data being pushed to the data layer when the user landed on the members-card page.

PageView GTM Setup

The above action is set as a triggering condition in GTM that collects the title and page path which in turn is reflected in the GA.

Complete the following steps to achieve pageView:

Step 1: Create a GA4 configuration tag:

Create a tag that enables us to configure GTM with Google Analytics 4 property on a particular page of the application. Take the reference of the image below to create the tag. For the measurement ID, refer to the data streams of your GA account. For more information check this blog's step 2 of the GA Setup Section.

Step 2: Create variables for the page title and page URL

Page title variables:

Create a JavaScript variable called document.title as in the image reference below.

Create the data layer variable page.title which reflects the data layer variable from the React application, and set the default value to the document.title variable.

Page URL variables:

Create a custom JavaScript variable called backup document location as in the image reference below.

Below is the custom code that helps GTM pull the Page URL:

function () {
  return document.location.origin + document.location.pathname + document.location.search;
}

Now, Create the data layer variable page.url which reflects the data layer variable from the React application, and set the default value to the backup document location variable.

Step 3: Create a trigger for collecting data, on the window.dataLayer.push()

Set up triggers that help us listen to the events sent on the data layer. example event: 'pageview'

Note: Make sure that the trigger's event name matches with the event name sent from the React application to the data layer.

Step 4: Create a Tag to handle and publish pageView in GA

The last step in GTM is to create tags. Fill the fields as shown in the image. Set the tag type to GA4 event. Link to your configuration tag that was created in step 1. Fill in a meaningful Event name for displaying of this event in GA. Link the event parameters and triggers that were created.

Finally, save all the changes, preview the modifications.With satisfactory results, you are good to submit your version on GTM.

Happy learning.