What is the Data Layer (dataLayer)? How is it used?

Understand how the dataLayer enables seamless tracking and tag execution across websites and apps with customizable event signaling.

Ceyhun Enki Aksan
Ceyhun Enki Aksan Entrepreneur, Maker

A JavaScript object can be described as enabling information exchange between a website and its Google Tag Manager container.

The information passed can be managed, controlled, and customized using variables and triggers provided by Google Tag Manager.

tip

For advisory regarding Tag Management and Data Layer, please contact support via support request.

When Google Tag Manager (GTM) is installed on a web page or mobile app, and the data layer structure is created (where gtag.js creates the dataLayer object, see Google Analytics E-Commerce Reports and Setup), the next step is to determine which data elements should be evaluated within the layer. DataLayer is a JavaScript object designed to facilitate seamless information exchange between users and services.

At the moment GTM is loaded, it processes three events and passes them via the dataLayer.

gtm.js
: It is created the moment the GTM code is loaded. You can associate specific events—such as a page view—triggered when a user visits a page using this event.

gtm.dom
: It is created the moment the DOM is loaded.

gtm.load
: It is created when the page and all its elements (images, CSS and JavaScript files, etc.) have been loaded. The gtm.load event is used when actions or operations are performed on page elements.

You can view the content of the dataLayer object in your browser’s console by typing dataLayer. So, what data can we collect and use thanks to these events and the data layer?

  • Product data (especially on e-commerce sites: product name, price, categories, type and variants, etc.)
  • Marketing campaigns (campaign name, medium, source, campaign, promotion, etc.)
  • Transaction details (shopping cart content, add/remove from cart, payment methods, transaction dates, etc.)
  • Customer information (new or returning customer, registered user, etc.)

datalayer operations are defined in the following structure:

  dataLayer = [];
  dataLayer = [{
    // ...
  }];
  dataLayer.push({'variableName': 'variableValue'});

If information is to be processed in response to an action or event, it is pushed to the data layer using dataLayer.push().

<a href="#" onclick="dataLayer.push({'variableName': 'variableValue'});">Link</a>

We’ll provide an example for both cases.

dataLayer = [{
  'bookCategory': 'Fiction',
  'bookTitle': 'Jonathan Livingston Seagull',
  'bookAuthor': 'Richard Bach'
}];
<a href="#" onclick="dataLayer.push({'bookCategory': 'Fiction', 'bookTitle': 'Jonathan Livingston Seagull', 'bookAuthor': 'Richard Bach'});">Link</a>
warning

Important note: The data layer must always be defined before the GTM snippet. This ensures that GTM and other snippets have access to the data content they need. If for any reason you are unable to load the data layer content before the GTM snippet, you can instead trigger the data via the push method or by re-evaluating the triggering process between gtm.dom and gtm.load1.

GTM Events
GTM Events

GTM Variable Definition

The first step in the definition process should be clearly defining which data elements will be used for what purpose. Afterward, you can easily use and customize the required parameters within your desired structures. Otherwise, you’ll end up with just a clutter of data.

GTM Variables
GTM Variables

After defining a name/title under Variables > User-Defined Variables > New Variable in the GTM container, you can configure the variable through the Variable Configuration section. Upon clicking the relevant field, you’ll encounter various sub-options under the Choose variable type header, including different types and especially specific options (HTTP Referrer, Custom JavaScript, Data Layer Variable, DOM Element, Constant, and more). For our purposes, the Data Layer Variable option is particularly important.

GTM Tag Manager
GTM Tag Manager

A name must be created for the Data Layer Variable for its usage. Here, we must pay attention to the fact that we will be able to access this data layer through the name we have defined. Therefore, we will proceed from the above example code and assign the bookTitle header. It is important that there is no variation in spelling. For instance, if you assign a header such as book title or book_Title, we will not be able to access the relevant information. In most cases, the Data Layer Version is predefined as Version 2. I will discuss any variations in data layer version under a different heading2.

dataLayer
dataLayer

Now, we can confirm the variable definition process by clicking the Save button and proceed to create other fields such as bookCategory and bookAuthor3. In addition to the book example, let’s also create a user-defined value on a page level.

  dataLayer = [{
    'pageCategory': 'signup',
    'visitorType': 'high-value'
  }];

Our example assigns a value to users based on membership and uses this value within the data layer. That is, if a user has signed up, they will now have the 'visitorType': 'high-value' value for 'pageCategory': 'signup', and thus we can use this information in many purposes within subsequent activities. Of course, we can expand our examples further. For instance, we can include HTML events.

dataLayer.push({'event': 'etkinlikAdi'});

etkinlikAdi can represent user-related (such as link or button clicks) events. You can customize the link1-click expression in the following example as you see fit.

<a href="#" name="button1" onclick="dataLayer.push({'event': 'link1-click'});" >Link 1</a>

For this purpose, we will use the predefined event variable. You can see in my article titled Contact Form 7 Transformation Definition how I was able to track a WordPress plugin named CF7 form.

Data Layer Definition

In the examples above, we implemented the data layer definition using dataLayer4. However, this is not a rule, and we can also perform similar data transmission operations using different names. All we need to do is indicate the name we have chosen in the GTM environment as well5.

  yeniLayerAdi = [{
    // ...
  }];
  yeniLayerAdi.push({'degiskenAdi': 'degiskenDegeri'});

After the name change, to access the information, we will need to select the name of the data layer we defined under the Use Data Layer option in the Google Analytics setup and other areas. You can find the relevant instructions in the visual under the Data Layer Definition heading.

Using Data Layer Without JavaScript Support

When the GTM installation encounters a JavaScript issue with the iframe or when JavaScript support is unavailable, it ensures the processing of the GTM container. Within the GTM usage framework, we can also transmit data through the iframe using the data layer, even without JavaScript support6.

As shown in the example above, the definitions id=GTM-XXXX, degiskenAdi=degiskenDegeri, and degiskenAdi2=degiskenDegeri2 are present. We have pointed to our GTM container using the id, and we are sending the subsequent values to this defined ID.

Transaction Data Transmission

At the beginning of the article, I mentioned that we can share transaction data through the data layer. When sharing these transactions via Google Analytics, we can proceed through two main types: Standard ecommerce and Enhanced ecommerce. Additionally, you may also refer to my article titled Google Tag Manager dataLayer and E-Commerce Events.

Standard Ecommerce

In the Standard ecommerce setup, Google Analytics tracks the purchasing process and payment actions directly from the website and/or app. From the dashboard, you can easily monitor product and payment-related information along with conversion rates. To enable these transactions, you must activate the ecommerce feature during the Google Analytics installation.

dataLayer
dataLayer

Then, within the Setup, select the Tracking Type as Transaction and specify the URL of the payment confirmation page under the Firing Trigger. This way, we can send the following transaction data to Google Analytics reports.

Transaction Data

Transaction data is associated with the page. Therefore, it is sent when the page loads. If the transaction needs to be processed outside of page load, it should be triggered alongside an event.

Variable NameDescriptionData Type
transactionId (required)Transaction identifierstring
transactionAffiliation (optional)Partner or store namestring
transactionTotal (required)Total transaction amountnumeric
transactionShipping (optional)Shipping feenumeric
transactionTax (optional)Taxes and similar additional feesnumeric
transactionProducts (optional)Products involved in the transactionarray of product objects

For example, the table might look like this:

window.dataLayer = window.dataLayer || [];
dataLayer.push({
   'transactionId': '1234',
   'transactionAffiliation': 'Acme Clothing',
   'transactionTotal': 38.26,
   'transactionTax': 1.29,
   'transactionShipping': 5,
   'transactionProducts': [{
       'sku': 'DD44',
       'name': 'T-Shirt',
       'category': 'Apparel',
       'price': 11.99,
       'quantity': 1
   },{
       'sku': 'AA1243544',
       'name': 'Hat',
       'category': 'Apparel',
       'price': 9.99,
       'quantity': 2
   }]
});

Notably, when examining the transactionProducts field, you can see that the product’s subdata has been included. This feature is made possible thanks to Version 2 in the aforementioned Data Layer Version field. Let’s display the product data in a separate table format.

For UA, this transaction is referred to as a purchase. The id represents a unique transaction ID value7.

dataLayer.push({
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': 'T12345',
        'affiliation': 'Online Store',
        'revenue': '35.43',
        'tax': '4.90',
        'shipping': '5.99',
        'coupon': 'SUMMER_SALE'
      },
      'products': [{
        'name': 'Triblend Android T-Shirt',
        'id': '12345',
        'price': '15.25',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Gray',
        'quantity': 1,
        'coupon': ''
       },
       {
        'name': 'Donut Friday Scented T-Shirt',
        'id': '67890',
        'price': '33.75',
        'brand': 'Google',
        'category': 'Apparel',
        'variant': 'Black',
        'quantity': 1
       }]
    }
  }
});

For GA4, the object structure should be as follows8.

dataLayer.push({
  'event': 'purchase',
  'ecommerce': {
    'purchase': {
      'transaction_id': 'T12345',
      'affiliation': 'Online Store',
      'value': '35.43',
      'tax': '4.90',
      'shipping': '5.99',
      'currency': 'EUR',
      'coupon': 'SUMMER_SALE',
      'items': [{
        'item_name': 'Triblend Android T-Shirt',
        'item_id': '12345',
        'item_price': '15.25',
        'item_brand': 'Google',
        'item_category': 'Apparel',
        'item_variant': 'Gray',
        'quantity': 1,
        'item_coupon': ''
      }, {
        'item_name': 'Donut Friday Scented T-Shirt',
        'item_id': '67890',
        'item_price': '33.75',
        'item_brand': 'Google',
        'item_category': 'Apparel',
        'item_variant': 'Black',
        'quantity': 1
      }]
    }
  }
});
Product Data
Variable NameDescriptionData Type
name (required)Product namestring
sku (required)Product SKU (Stock Keeping Unit / Stock Tracking Unit) numberstring
category (optional)Product categorystring
price (required)Product pricenumeric
quantity (required)Product quantitynumeric

Enhanced Ecommerce

When using Enhanced ecommerce, we can enhance standard ecommerce transactions by including more comprehensive data in reports; for example, cart operations, payment process steps, and the user’s status within the payment process. To implement enhanced ecommerce events on GTM, we can use two methods: the first being the Data Layer, and the second being a Custom JavaScript variable9. The Data Layer is generally the preferred method, as ecommerce data is passed directly through the data layer. When using a Custom JavaScript variable, the data to be placed in the data layer is sent as an object within a new Custom JavaScript variable10. An example of a Custom JavaScript variable content is as follows:

function() {
 var ecommerceData = {
   'ecommerce' : {
     currencyCode : 'TRY',
     // additional parameters as needed
   }
 };
 return ecommerceData;
}

The ecommerceData variable in the example can be modified. You can review the examples and related technical details in the [Enhanced Ecommerce (UA) Developer Guide]7 and [Ecommerce (GA4) Developer Dveloper Guide]8 pages.

*[DOM]: Document Object Model
*[GTM]: Google Tag Manager
*[CSS]: Cascading Style Sheets

Footnotes

  1. About Ecommerce. Analytics Help
  2. Data layer. Tag Manager Help
  3. The data layer. Tag Manager Help
  4. Simo Ahava. (2014). The Data Layer
  5. Himanshu Sharma. Google Tag Manager Data Layer Tutorial with examples. Optimize Smart
  6. Developer Guide. Google Tag Manager
  7. Measuring Purchases. Enhanced Ecommerce (UA) Developer Guide. Google Tag Manager 2
  8. Measure purchase. Google Tag Manager. Ecommerce (GA4) Developer Guide 2
  9. Julius Fedorovicius. (2020). Complete Google Tag Manager Data Layer Tutorial. Analytics mania.
  10. Universal Analytics ecommerce. Tag Manager Help