GTM Data Layer Explained: Setting Up dataLayer.push Right
What is the GTM data layer and how do you set it up? dataLayer.push, Data Layer Variables, Custom Event triggers, the GA4 ecommerce schema and testing.
The GTM data layer is a JavaScript array called window.dataLayer that carries your site’s events and business data to Google Tag Manager. Your page code writes a form submission or a purchase to this array with dataLayer.push. GTM reads the message, fires tags and passes the values on to GA4, Google Ads or Meta.[1]
In this post I explain how I set up the data layer, how I read it in GTM and the mistakes I see most often. Because I moved from software development into performance marketing, I look at it from both sides: the team writing the code and the team using the data.
What is the GTM data layer and why do you need it?
The GTM data layer is a machine-readable data channel that is independent of how the page looks. GTM can capture clicks and page views without a data layer. But business data such as order value, product ID, currency or lead type often does not sit anywhere reliable on the page.
Setups without a data layer usually read these values from the page’s HTML with DOM Element variables. A DOM Element variable is a GTM variable that reads the text or an attribute of an HTML element on the page. This method breaks silently when the design changes or a CSS class is renamed. The tag still fires, but it sends a wrong or empty value.
HTML scraping (DOM variable)
- The value is read from page text
- Breaks silently when the design changes
- Currency and format arrive inconsistently
- Hidden data such as product IDs is missing
Data layer
- The value is written directly from code
- Unaffected by design changes
- Numbers and currency use a standard format
- Order and product IDs can be included
A data layer is close to mandatory in two situations. The first is ecommerce tracking; GA4 ecommerce events expect a specific ecommerce object.[2] The second is advanced setups such as value-based bidding and deduplication. Fields like order ID and event_id are not visible on the page and only come from code. They are the foundation of setups such as Meta event deduplication and Enhanced Conversions.
How does the data layer work?
The data layer works like an array where messages are added in sequence, and GTM processes each new message as it arrives. According to Google’s documentation, GTM processes messages pushed to the data layer on a first-in, first-out basis, in the order they are received.[1] Each time a message is processed, GTM’s internal data model is updated and the triggers tied to that message are evaluated.
A push can carry two kinds of information. The event key says that something happened and fires triggers. The other keys carry the data for that event. In Google’s example, variables and the event name are sent together in a single push.[1]
dataLayer.push({
event: 'form_submitted',
form_type: 'contact',
form_location: 'footer'
});
GTM overwrites an existing value when a new value is sent under the same name. Google states this behavior explicitly in its documentation.[1] That is why key names must have a single meaning across the whole site. If pageCategory carries the page type on one page and the product category on another, your reports get mixed up.
How do you set up a data layer?
Short answer
How do you set up a GTM data layer?
To set up a GTM data layer, you first define events and keys in a schema. Then you initialize the window.dataLayer array once, before the GTM code, and write page data and user events with dataLayer.push. Finally, you create variables and triggers in GTM and test them in Preview mode.
- Define the events and keys to track in a schema document.
- Initialize the window.dataLayer array once, before the GTM container code.
- Push page data above the container code.
- Write user interactions with dataLayer.push at the moment they happen.
- Create Data Layer Variables and Custom Event triggers in GTM.
- Test every event and value in Preview mode, then publish.
The most critical line of the setup is the array initialization. Google recommends initializing the data layer as high in the page source as possible, above the GTM container code, with window.dataLayer = window.dataLayer || [];.[1] This expression keeps the array if it already exists and creates a new one if it does not.
<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
page_type: 'product',
language: 'en',
user_status: 'guest'
});
</script>
<!-- The Google Tag Manager container code goes below this -->
Data that tags need while the page loads is pushed above the container code like this. Google notes that for variables to persist across pages, this push must be repeated on every page load.[1] The data layer resets when the page reloads; a value written on one page does not carry over to the next on its own.
User interactions are written at the moment they happen. When a form is submitted successfully, a product is added to the cart or checkout is completed, the relevant code calls dataLayer.push. The push should be tied to the successful result of the action, not to the button click. Otherwise forms that fail are also counted as conversions.
How does GTM read data layer data?
GTM uses data layer information through two tools: variables read the values and triggers catch the events. When the two do not work together, the tag either never fires or sends an empty value.
A Data Layer Variable is a user-defined variable that reads the value of a pushed key.[4] When you create it, you type the key name exactly as it appears in the push. Nested objects use dot notation, for example ecommerce.value or ecommerce.transaction_id. The default Version 2 supports this nested reading.
A Custom Event trigger fires a tag when a push with a specific event value arrives.[3] The event name in the trigger must match the value in the push. If you need to catch several similarly named events with one trigger, you can use regex matching. Use it with care, though, because it can also catch events you did not intend.
- Create the variable
Go to Variables > User-Defined Variables > New, choose Data Layer Variable as the type and enter the key name, for example form_type.
- Create the trigger
Go to Triggers > New, choose Custom Event as the type and enter the event value from the push as the event name, for example form_submitted.
- Connect it to the tag
In the GA4 event tag, set the event name, add the variable as a parameter and select the trigger.
- Verify in Preview
Submit the form in Preview mode, select the form_submitted event in the event list on the left and check the value in the Variables tab.
This flow is also the basis of GA4 conversion tracking setups. Once the event reaches GA4 with the right parameters, all that is left is marking it as a key event in GA4.
What should the data layer look like for GA4 ecommerce?
For GA4 ecommerce events, the data layer should follow Google’s defined event names and ecommerce object structure exactly. Google’s ecommerce guide for GTM lists events such as view_item, add_to_cart, begin_checkout and purchase, along with the fields each one expects.[2] Sticking to these names lets GA4 reports and GTM’s built-in ecommerce settings work out of the box.
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'purchase',
ecommerce: {
transaction_id: 'ORD-10482',
value: 1249.90,
currency: 'TRY',
items: [
{ item_id: 'SKU-001', item_name: 'Sample product', price: 1249.90, quantity: 1 }
]
}
});
The first line clears the ecommerce object left over from the previous event. Google’s ecommerce examples include this clearing push before every event.[2] Without it, products from an item list view can leak into the next add-to-cart event.
For stores in Turkey I follow three formatting rules. The value must be a number with no thousands separator and a dot for decimals, not text like "1.249,90 TL". The currency must be written as the ISO 4217 code TRY. And transaction_id must be unique for every order and must not resend the same order when the thank-you page is refreshed.
Before sending the purchase value to ad platforms, also decide whether it is gross, excluding VAT or including shipping. Value-based bidding learns from this number. Writing the decision into the schema document ends the debate between teams before it starts.
Data layer and personal data: what to watch for under KVKK?
The data layer is an array open to anyone running the browser; anyone who types dataLayer in the browser console can see its contents. Writing personal data such as email, phone number or full name to the data layer therefore needs a separate decision. Under KVKK (Turkey’s personal data protection law) and the GDPR, transferring this data to ad platforms requires explicit consent and a privacy notice.
Setups such as Enhanced Conversions need user data. In that case, the safer route is to write the data only for users who consented, only at the moment of conversion and, where possible, hashed with SHA-256. Consent status also needs to be read from the data layer; this ties directly into a Consent Mode v2 setup.
Moving tracking from the browser to a server is another option. With server-side tracking, the data layer is still the source, but sensitive fields can be enriched on the server. For the detailed setup, see my server-side GTM setup guide.
What are the most common data layer mistakes?
Most data layer errors start not in the code but in communication between teams. The development team writes an event under a different name, the marketing team expects the old name in GTM and the tag silently stops. The mistakes I see most often are:
- Reassigning the array: A
dataLayer = []line in a theme or plugin cuts off the array GTM is watching.[1] - Inconsistent event names: Using
formSubmitin one place andform_submitin another. Names are case-sensitive. - Tying the push to a click: Failed form submissions are counted as conversions too.
- Not clearing the ecommerce object: Products from the previous event leak into the next one.[2]
- Sending numbers as text: Values like
"1.249,90"are read incorrectly in GA4 and Google Ads. - No data layer schema: Without a shared document defining events and keys, nobody knows which event broke after a site update.
How do you test a data layer?
A data layer is tested using GTM’s Preview mode together with the browser console. GTM Preview mode opens your site through Tag Assistant and shows each data layer message as a separate row in the event list on the left.[5] When you select an event, you see which tags fired, the current value of each variable and the contents of the data layer.
Typing dataLayer in the console also shows the current state of the array. It is a quick way to see whether a push happened at all. I do the final check on the destination platform: GA4 DebugView, conversion diagnostics in Google Ads or the test events screen in Meta Events Manager.
Conclusion and next step
The GTM data layer is the data contract between the marketing and development teams. Initializing the array correctly, tying events to successful results and fixing keys in a schema makes most of your tracking robust. Following the GA4 ecommerce schema makes sure reports and bidding strategies are fed with the right data.
As a next step, list the existing events on your site in a table and compare them against the checklist above. I describe how I build the whole measurement stack on my performance marketing page, and how I approach this work at the intersection of software and marketing in my marketing engineering post.
Key terms
- Data Layer Variable
- A Data Layer Variable is a GTM user-defined variable type that reads the value of a key pushed to the dataLayer. In Turkish it is called veri katmanı değişkeni. It is how values such as order value or form type reach your tags.
- Custom Event trigger
- A Custom Event trigger is a GTM trigger type that fires tags when a push with a specific event name reaches the dataLayer. In Turkish it is called özel etkinlik tetikleyicisi. The event name must match the event value in the push exactly.
- Data layer schema
- A data layer schema is a shared document that defines which events a site writes to the dataLayer, with which keys and data types. It works as a contract between the development and marketing teams. The schema keeps event names and value formats consistent across every page.
Frequently asked questions
Do I need a data layer to use GTM?
No, GTM can track basic events such as page views and clicks without a data layer. But to capture business data like order value, product ID or form type reliably, you need one. Variables that scrape the page's HTML break silently when the design changes.
What is the difference between dataLayer.push and dataLayer = []?
dataLayer.push adds a new message to the existing array, and GTM listens for that message. dataLayer = [] creates the array from scratch. If it runs after GTM has loaded, the array GTM is watching is lost and tags stop firing. That is why Google recommends initializing the array once with window.dataLayer = window.dataLayer || [].
Why does my Data Layer Variable return undefined?
The most common reason is that the key name does not exactly match the name in the push; names are case-sensitive. The second reason is that the tag fires on an event that happens before the data is pushed. Selecting the event in Preview mode and checking the Data Layer tab usually reveals the problem.
Can I put an email address or phone number in the data layer?
Technically yes, but the data layer is an array anyone can read in the browser. Personal data should only be written for users who have given explicit consent, and only for the tag that needs it. Use a SHA-256 hashed value where possible and update your privacy notice accordingly.
Why push ecommerce: null before every ecommerce event?
GTM keeps the objects it receives in the data layer by merging them. Products from a previous event can leak into the next one. Google's GA4 ecommerce examples include a push that clears the ecommerce object with null before each event.
Sources
The full topic: Tracking guide ↗