How to: Data Layers in Google Tag Manager

Tayo Sadique
Hacktive Devs
Published in
9 min readJul 28, 2023

If you want to take your website analytics and tracking to the next level, there’s no better tool than Google Tag Manager (GTM). With its data layers feature, you can achieve pinpoint accuracy and efficiency in your tracking efforts.

A data layer is a JavaScript object that captures key information about a user’s interaction with your site, including product views, page visits, and other relevant data points. By leveraging data layers in GTM, you’ll be able to set up more precise tracking tags and triggers and gain deeper insights into user behavior on your site. Check out this article for a closer look at how data layers work in GTM, and discover some best practices for using them effectively.

The data layer is a middle layer between your website and google tag manager, it serves as a central repository of structured data for your google tag manager container.

If you want to send information or variable into google tag manager, you first need to send it to the datalayer. You need to understand that the datalayer is not a default part of your website, rather it is accompanied by your Google tag manager container implementation and is initialized when the tag container loads.

How the data layer works

In the context of google tag manager, a datalayer is defined as an array of a single object. It is defined;

<script>
dataLayer = [{}];
</script>

Looking at the script presented above, the dataLayer is an array judging from the “[]” and then an object is contained within that array denoted by the “{}”. Hence in google tag manager, the dataLayer array should not have more than one object within it.

Within the object, you can have different elements of the same or different types. Example of a dataLayer with one element in the object

<script>
dataLayer = [{'variable_name' : 'variable_value' }];
</script>

The elements within a dataLayer are called variables. The Variable is formatted as “ ‘key’ : ‘value’ ” pairs. In the example presented above, ‘variable_name’ is the key, and ‘variable_value’ is the value associated with the key. An example of a datalayer with more than one element with different types is presented in the example below.

<script>
dataLayer = [{ 'event' : 'signup',
'origin_country' : 'united states',
'Purchase_info' : { 'purchase_cuurency' : 'USD',
'purchase_amount' : 2000 }

}];
</script>

How is information added or modified in the dataLayer?

There are two ways to add or push data into a dataLayer:

  1. Hardcoded dataLayer variables: The hardcoded dataLayer variables are pushed before runtime. It is recommended to add hardcoded dataLayer variables before the tag container snippet in the head section of your website. However, if the values in the hardcoded dataLayer are needed before the page loads, it is required to place the hardcoded dataLayer in the head section of the website above the tag container snippet. This ensures that the dataLayer initializes before the tag is initialized.
  2. Dynamic dataLayer variables: The dynamic dataLayer variable is a dataLayer variable pushed dynamically into the dataLayer during runtime. This can be used to pass information into the dataLayer such as events and variables associated with such events. This method is suitable when you intend to push information into the dataLayer on any event other than the page load event.

Initializing the dataLayer

To use the dataLayer in your code, you need to initialize it. Initializing the dataLayer is as simple as setting up variables in your dataLayer. As such any of the code blocks presented above is sufficient to initialize your dataLayer as long as a variable is contained in the element passed into the dataLayer.

The “=” operator assigns the values in the object to your dataLayer array.

<script>
dataLayer = [{'variable_name' : 'variable_value' }];
</script>

Note: Multiple initialization of a dataLayer overwrites the dataLayer, therefore, ensure to initialize your dataLayer once on each webpage or application.

Do not initialize a dataLayer more than once on the same webpage

Let’s talk about “Scope” in Javascript

When writing javascript code, there are two types of scopes that determine the accessibility of variables in your javascript code, namely;

  1. Local scope: These are variables declared within a javascript function and can only be accessed within the function where it was declared.
  2. Global scope: These are variables declared outside any function and can be accessed by any function. Hence, Global variables can be used by any function even though it was not declared within said function.

The ‘Push’ method

The ‘push’ method is used to dynamically add object elements into your dataLayer. An example of a dataLayer push is presented below;

<script>
dataLayer.push({'variable_name' : 'variable_value'});
</script>

For an already existing dataLayer, use the dataLayer.push() method to add the new variable into the dataLayer.

Using the “window” scope to localize your dataLayer scope

It is best practice to use the ‘window.datalayer’ when declaring or using dataLayer variables to prevent any conflict with any other local javascript array that uses the dataLayer name. It is also recommended that the ‘dataLayer’ name is reserved for Google tag manager dataLayer to prevent conflicts. Going forward, we will use the window.dataLayer instead of dataLayer.

Push information to the dataLayer to avoid multiple initializations.

To push information into the dataLayer whilst avoiding multiple declarations which might overwrite the dataLayer, it is important to set a condition that only creates a new dataLayer if there is no existing dataLayer and appends to the existing dataLayer is a dataLayer already exists. This is achieved using the code presented below:

<script>
window.datalayer = window.dataLayer || [];
window.dataLayer.push({ 'variable_name' : 'variable_value'});
</script>

In the code block shown above, dataLayer is assigned to an existing dataLayer if the dataLayer exists, or if the dataLayer doesn’t exist, a new dataLayer is created with an empty array. The ‘||’ / ‘OR’ operator executes the function if either of the conditions is satisfied.

Overwriting an existing dataLayer Variable

Overwriting a dataLayer variable is different from overwriting a dataLayer. The distinction lies in that overwriting a dataLayer clears all information in the dataLayer and assigns new key-value pairs into said dataLayer. On the other hand, overwriting a dataLayer alters the value of a key-value pair within a datalayer. The dataLayer.push() method is also used to achieve this as presented in the code block below.

//dataLayer declared and initialized in the head section of the website
<script>
window.datalayer = [{'url_path' : 'website.com'}];
</script>

......

//changing the value in the 'url_path' variable in the datalayer in the body section

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'url_path' : 'deepbux.xyz'});
</script>

How to use the dataLayer elements in Google tag manager

The elements (key-value pairs) in your dataLayer array can be accessed and used in your Google tag manager in various ways. However, to access the information in the dataLayer to do something in google tag manager you need to assign it to a variable or use it as an event trigger. The variables or events can then be used in your tags, triggers, or variables.

Using dataLayer variables as datapoints within GTM:

Let’s create a code example of a dataLayer variable that adds the purchase value of a subscription event when a customer subscribes to a plan.

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'purchase_value' : '29',
'purchase_currency' : 'USD'});
</script>

In google tag manager, we can use the purchase_value and purchase_currency variables in the dataLayer by creating a dataLayer variable in google tag manager from the variables tab. Follow the steps below to create the variables.

Step 1: Click on the variables tab in google tag manager

Step 2: Create a user-defined variable and Name your variable with a suitable name to ensure you can refer to it when you need it

Step 3: Click on variable configuration and from the side panel scroll down to choose the dataLayer variable option

Step 4: In the variable name section, add the variable name or variable key. This field is case-sensitive, thus ensure you are inputting the correct variable name in this field. Save the dataLayer variable.

Now you are done adding the variable to your google tag manager and you can use it anywhere else within google tag manager in your tags, triggers or other variables.

Using dataLayer variables as event triggers within GTM:

Let’s create a code example of a dataLayer variable that triggers a purchase of a subscription event when a customer subscribes to a plan.

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({'event' : 'purchase'});
</script>

In google tag manager, we can use the event variables in the dataLayer as a trigger by creating a dataLayer variable in Google tag manager from the trigger tab. Follow the steps below to create the variables.

Step 1: Click on the triggers tab in google tag manager

Step 2: Create and Name your trigger with a suitable name to ensure you can refer to it when you need it

Step 3: Click on add trigger and from the side panel scroll down to choose the custom event option

Step 4: In the event name section, add the variable value. This field is case-sensitive, thus ensure you are inputting the correct variable value in this field.

Step 4 (b): Set the event trigger condition to trigger on some custom events, then paste your customer event name from the event name section.

Now you are done adding the event to your google tag manager trigger and you can use it anywhere else within google tag manager in your tags, triggers, or other variables.

Using dataLayer variables with variables and event triggers within GTM:

Let’s create a code example of a dataLayer variable that triggers a purchase event and then create a variable of the customer attributes when a customer subscribes to a plan.

<script>
dataLayer = [{ 'event' : 'purchase',
'origin_country' : 'united states',
'Purchase_info' : { 'purchase_cuurency' : 'USD',
'purchase_amount' : 2000 }

}];
</script>

The variables in the code block presented above can be used as variables in google tag manager and the event variable can also be used as an event trigger in google tag manager as well.

Data layers give your website tracking superpowers.

Here is how you can use dataLayers to boost your website tracking capabilities.

  1. Create precise and expandable website tracking systems specifically tailored to your requirements by utilizing unique data in the dataLayer.
  2. Save time on configuration and management, while improving tracking and data collection clarity.
  3. Improve the accuracy of conversion tracking and increase the sophistication of the data you collect.
  4. Write and edit code in the GTM interface.
  5. Pass data into third-party applications.
  6. Use dataLayer variables to fire tags.

Some real-life use cases include:

  1. Set, delete, or update 1st party cookies on your website
  2. Trigger conversion tags and pass variables into the tag as additional information.
  3. Implement Google Analytics 4 e-commerce features.
  4. Manage cookie consent
  5. Collect and send custom dimensions and metrics for GA4 or other analytics software.
  6. Encrypt data automatically.

There are several use cases of the dataLayer in Google tag manager, the use cases mentioned above merely scratch the surface.

In the separate articles over the next few weeks, I will discuss some interesting use cases, server-side implementation of GTM dataLayer for e-commerce, and transforming data in the dataLayer to further extend the capabilities of Google tag manager.

In conclusion, the implementation of a data layer in Google Tag Manager can greatly enhance the accuracy and efficiency of tracking website data. By providing a standardized format for data collection, it reduces the risk of errors and allows for easier integration with other tools and platforms. Additionally, the use of a data layer can improve the speed and performance of a website, leading to a better user experience. Overall, the adoption of a data layer in Google Tag Manager is a valuable investment for businesses looking to optimize their website analytics.

--

--

Tayo Sadique
Hacktive Devs

I love selling tech products. I am on a quest to offer value-able products to those who need them. I build & fly drones and code for fun.