Track Custom Events with Google Analytics 4 and Google Tag Manager

Track Custom Events with Google Analytics 4 and Google Tag Manager

Let's look at how to track user actions on your React app with custom event tracking using Google Analytics 4 and Google Tag Manager.

Rahul Raj's photo
Rahul Raj

Published on Aug 3, 2021

7 min read

If you have ever tried to set up any sort of custom event tracking on your web app, you must have heard of Google Analytics.

Google Analytics is one of the best free tools that you can use to track and analyze traffic on your website or web app. Google Tag Manager takes it a step further by allowing you to integrate third-party data collection and analytics tools with your app.

This post will cover how to implement custom event tracking on a React app. We will set up Google Tag Manager triggers, variables, and tags, and report custom events to Google Analytics. While we are using React in this example here, the process would be almost identical for every client-side application.

In a hurry? πŸ€“

πŸ‘‰πŸ» Skip ahead to custom event tracking implementation

πŸ‘‰πŸ» Straight to the example code repo on GitHub

Terminology

  • GA - Google Analytics
  • GTM - Google Tag Manager

Google Analytics 4

The latest iteration of Google’s web analytics platform, Google Analytics 4 was released in October 2020.

One of the main features it brought with it was new Custom Events. The most notable difference regarding events is 4 parameters that you could send together with every event.

In the previous Google Analytics version; Universal Analytics, you could only send 4 defined parameters with your custom event.

{
  eventCategory: "Category",
  eventAction: "Action",
  eventLabel: "Label",
  eventValue: "Your Value",
}

In Google Analytics 4, the data model for custom events is much more flexible which allows you to structure your events in any way you want. There is only one required parameter the Event Name, and you can add up to 25 additional parameters with your event.

{
  event: "my_custom_event", // Event Name
  // ...upto 25 parameters per event
}

Connecting Google Analytics with Tag Manager

I won't go into details on how to set up and connect GA with GTM. Here's a detailed blog post that should help you get started.

Adding GTM Script

The first step would be to add your GTM script to your React app. You can either directly add your GTM script to your index.html or choose to use a package.

We'll be using the script provided by GTM and add it to the index.html. If you don’t already have the code, you can copy it from the Admin > "Install Google Tag Manager section in GTM.

It should look something like this.

<head>
// ...other tags
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->
</head>

You can validate this by using preview mode in GTM. You should now be able to see the automatically tracked events and Events tracked via Enhanced Measurement (if enabled) being logged in the preview mode.

automatically tracked events bein logged on gtm

Custom Event Tracking πŸ”Ž

GTM adds a global dataLayer array on a window object. Which we can push the custom events to the dataLayer and those events would be sent to GTM.

If we want to send a simple custom event we can do that like so

window.dataLayer.push({
    event: "customClickEvent",
    // custom event params
 });

You can check your custom event being received by GTM using the preview mode, it should look something like this.

custom click event being logged on gtm

Now, You can set up a trigger and tag in GTM to send this custom event to GA.

This is pretty simple, right? But this can get pretty tedious if you have to set up a tag for each event. Instead, we can use GTM variables to make our tag a little more dynamic to track multiple click events with a single tag.

Tracking User Events

Let's have a look at it using a simple Todo app example. We have a few events we want to report to GA. Adding, Deleting, and Checking a Todo list item.

Since we don't want to add 3 different tags and triggers to GTM for our 3 custom events. We need to set up some data layer variables.

Let's create a reusable trackEvent function first that we can call across our app to send a custom event.

const trackEvent = (eventType) => {
  window.dataLayer.push({
    event: "customClickEvent", // Event name that will activate trigger
    eventType, // event type which would be sent to GA.
    appVersion: packageJson.version, // App version; Just an example for additional param.
    // You can enrich your events with additional params For better reporting and goal tracking in GA.
  });
};

Adding GTM Variables

We need to add custom user-defined data layer variables in GTM which we could use across our tags on GTM.

Let's create a couple of data layer variables for our eventType and appVersion

Go to Variables menu β†’ New User-Defined Variables β†’ Configure Variable Type β†’ Select Data Layer Variable.

Then configure your Data Layer Variable Name and give your variable a name.

custom event type configuration

app version configuration

Once you're done defining variables you should be able to see your User-Defined Variables.

user defined variables list

Triggers

We need to set up a Trigger that would listen to all the events and fire our Tag when it receives the customClickEvent

Go to Triggers β†’ Add New β†’ Trigger Configuration β†’ Select Custom Event

Then configure the Trigger with an Event name and give your Trigger a name.

custom trigger configuration

Creating Tags

This is the last bit of setup we need, We'll create a Tag that would be triggered via the custom Trigger we set up above. This Tag would be responsible to send custom event data to Google Analytics.

Go to Tags β†’ Add New β†’ Configure Tag β†’ Select "Google Analytics: GA4 Event" β†’ Choose a Configuration Tag.

You need to give your event a name. This is the event that would be sent to GA. This is where we want to use the eventType variable we just created.

We'll also add the appVersion parameter to our event for better insights into analytics reports. We will use the appVersion variable for that.

Lastly, We need to add a firing trigger to the Tag. We will choose the custom event trigger that we created above.

Your Tag should look something like this.

custom tag configuraion

Tracking Events on user actions

Let's call our reusable trackEvent function to report events to GTM.

We have a few functions defined which handle the actions user performs on the Todo app.

We can call the trackEvent function with the eventType argument and a custom event will be reported to Google Analytics.

// Reusable trackEvent function
const trackEvent = (eventName) => {
  window.dataLayer.push({
    event: "customClickEvent",
    eventName,
    app_version: packageJson.version,
  });
};

const handleToggleTodo = (index) => {
  // Report a custom "toggle_todo" event when user toggles the todo item
  trackEvent("toggle_todo");
  toggleTodo(index);
};

const handleDeleteTodo = (index) => {
  // Report a custom "delete_todo" event when user deletes the todo item
  trackEvent("delete_todo");
  deleteTodo(index);
};

const handleAddTodo = (inputValue) => {
  // Report a custom "add_todo" event when user adds the todo item
  if (inputValue !== "") {
    trackEvent("add_todo");
    addTodo(inputValue);
  }
};

This is all you need to do to track your custom events in Google Analytics 4 with Google Tag Manager.

Just for better organizational purposes, We can create an Object with all our event types and use it like so.

const EVENT_TYPES = {
  TOGGLE_TODO: "toggle_todo",
  DELETE_TODO: "delete_todo",
  ADD_TODO: "add_todo",
};

// Reusable trackEvent function
const trackEvent = (eventName) => {
  window.dataLayer.push({
    event: "customClickEvent",
    eventName,
    app_version: packageJson.version,
  });
};

const handleToggleTodo = (index) => {
  // Report a custom "toggle_todo" event when user toggles the todo item
  trackEvent(EVENT_TYPES.TOGGLE_TODO);
  toggleTodo(index);
};

const handleDeleteTodo = (index) => {
  // Report a custom "delete_todo" event when user deletes the todo item
  trackEvent(EVENT_TYPES.DELETE_TODO);
  deleteTodo(index);
};

const handleAddTodo = (inputValue) => {
  // Report a custom "add_todo" event when user adds the todo item
  if (inputValue !== "") {
    trackEvent(EVENT_TYPES.ADD_TODO);
    addTodo(inputValue);
    setInputValue("");
  }
};

Final Validation βœ…

This is all the setup you needed to start tracking custom events on your Single Page Application.

You can now run GTM Preview Mode and go to Debug View on Google Analytics. Perform the user actions on your App and you should see the events being reported to Google Analytics in real-time πŸŽ‰

debug view real time events being logged.png

Events, Tags, Triggers... What? πŸ˜•

Custom Event Tracking with Google Analytics 4 and Google Tag Manager can be quite confusing for developers trying it out for the first time.

Google Analytics 4 is still relatively new and lacks developer-focused resources to help us understand custom events tracking. Especially the resources that talk about the code and implementation details for Single Page Applications.

I, too, struggled quite a bit when I had to add custom events on a React App, so I wrote this post for anyone who is trying to figure out custom events on GA4. Good luck!

This is the first-ever post I've written and I would love to hear what you think about it. Let's hang out on Twitter.

Β 
Share this