Resetting the Data Layer in Google Tag Manager

The data layer in Google Tag Manager (GTM) is probably one of its best features. It helps easily pass data to your tags and triggers in a simple key:value method that creates a powerful data store.

The flip side to using this method is that it can create a data bloat that can quickly get out of hand. For example, look at this screenshot from Next – they pushed 37 different data layer events 😱

Why does this matter?

Website speed is a critical factor for conversion rates. I don’t think I need to convince you of this at this point. So removing any extra fat that can slow down your site is important. The Next example is rather radical; they keep pushing these events with every click on the website, which can amass a large data set.

A more common example is Single Page Applications (SPA) or Progressive Web Apps (PWA) which are popular today, especially in the field of Headless Commerce. In these types of websites, the user doesn’t navigate to a new page, which persists the data layer between pages.

This can result in a bloated data layer that contains data from dozens of pages visited throughout the current sessions and the events triggered on them.

Additionally, this can lead to misattributed events – i.e. event data from a previous page sent on the current page.

Solving the bloat

Luckily enough, the solution is relatively simple. A the script below can be triggered to reset the data layer.

<script>
window.dataLayer.push(function() {
  this.reset();
})
</script>

Manual implementation

One option is to ask your developer to trigger this on a page load of your SPA/PWA site (aka route change). This script should be fired before the pageview event you’re triggering (if you’re using a triggered pageview event as I recommend).

If you’re tracking pageviews using the history change trigger in GTM, make sure to trigger the script before the route change action.

Google Tag Manager Implementation

Since you’re already using GTM you can obviously use it to trigger this script. A simple way to go about this is to set the script as a Custom HTML tag that fires immediately before the Google Analytics Pageview tag. This way the new page loaded get a fresh start.

This tag should have no trigger attached to it.

In your Google Analytics Pageview tag, expand the Advanced Settings section and the expand Tag Sequencing. Check Fire a tag before… and then select the tag you’ve created in the previous step.

In the Custom HTML tag it will reflect in this way:

Leave a Reply

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

Related Posts