Skip to content
Faisal Mahmud TusherDigital marketing, SEO & analytics
with Faisal Tusher

Marketing Analytics › Google Tag Manager

The Data Layer

What the data layer is, how pushes and events work, structuring objects for GA4 and ads tags, timing, single-page apps, the developer contract and validation.
Guideintermediate10 min readUpdated

What the data layer is

In the browser, the data layer is nothing more than a global array, named dataLayer unless the container snippet was configured with another name. The site declares it before the container snippet runs, so that any value pushed during page construction is already there when the container loads:

window.dataLayer = window.dataLayer || [];

The container snippet creates the array if the page has not, but a site that relies on that has already lost the chance to push page-level context first. From the container's side, the array is a queue of messages. As each message arrives the container reads it, updates an internal model of the page's state from its keys, and if the message carries an event key, evaluates every trigger against it. Variables of the data layer type read from that model, not from the raw array, which is why a value pushed on one message is still readable on a later one.

The alternative to a data layer is scraping: reading values out of the page's HTML with DOM variables and custom JavaScript. Scraping works until a designer renames a class or a developer restructures a template, and it fails silently when it does. The data layer is a deliberate interface. The site says, in a structure agreed in advance, "a purchase just happened and here is what was in it", and the container does not need to know how the page is built. Google's data layer documentation, listed in the sources, describes the mechanism; the rest of this guide is about using it well.

Pushes, events and variables that read them

A push appends one object to the array. A push without an event key updates the container's model and nothing else; a push with one does that and then runs the trigger evaluation that the tags, triggers and variables guide describes, so that custom event triggers whose name matches can fire their tags. The simplest interaction push, sent by the site after a visitor completes registration, looks like this:

window.dataLayer.push({
  event: "sign_up",
  method: "email"
});

A data layer variable in the container named method reads the second key, and a custom event trigger on sign_up fires a GA4 event tag that sends both. Nested values are reached with a dot path: a variable named ecommerce.transaction_id reads inside the ecommerce object. Every data layer variable can carry a default value for when the key is absent, which keeps tags from sending the literal word "undefined" to a report.

Two behaviours surprise people. First, the default variable mode merges nested objects across pushes rather than replacing them, so context pushed early persists and a key omitted from a later push keeps the old value. That is why Google's e-commerce guidance tells you to push a reset that sets ecommerce to null immediately before each new e-commerce push: without it, items from the last event can leak into the next. Second, a push made just before the browser navigates away, such as on a link click, may not give tags time to send. The push can include an eventCallback function, which the container calls once the tags for that event have fired, and an eventTimeout as a safety net; the site then navigates from the callback rather than immediately. The debugging tutorial shows the data layer view in preview mode, where every message and the resulting state can be inspected.

Structuring data layer objects

A few conventions make pushes readable, reusable across tools and cheap to wire into tags.

  • One event per push, named in snake_case. Where GA4 documents a name (purchase, add_to_cart, generate_lead), use it; where it does not, follow the same style and keep the name a verb phrase.
  • Use GA4's parameter names for keys where a parameter exists. A key named value or currency maps to a tag field without translation; a key named orderTotal needs a variable and a mapping that someone must maintain.
  • Scalars at the top level for simple events, objects for entities. A sign-up has a method; a purchase has a transaction and a list of items. Nest the entity, keep the rest flat.
  • Type values correctly. Numbers as numbers, not strings; currency as the three-letter code; booleans as booleans. Tags do not coerce types for you.
  • Push context before the container, events after. Page type, template, logged-in state and content category go in the first push; interactions come later with an event key.
  • Never push personal data. Names, email addresses and phone numbers do not belong in the data layer, and most measurement tools prohibit receiving them.
Illustrative example — not a real result

Context push and purchase push for a homeware shop

The shop's page template emits a context push before the container snippet, and the order confirmation page emits a reset followed by the purchase. The analyst's variables read page_type, ecommerce.transaction_id, ecommerce.value and ecommerce.items, and the same push feeds the GA4 event tag and the Google Ads conversion tag with no further mapping.

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  page_type: "order_confirmation",
  logged_in: true,
  customer_segment: "returning"
});
window.dataLayer.push({ ecommerce: null });
window.dataLayer.push({
  event: "purchase",
  ecommerce: {
    transaction_id: "HW-20481",
    value: 148.50,
    currency: "GBP",
    shipping: 4.95,
    tax: 24.75,
    coupon: "SPRING10",
    items: [
      { item_id: "LAMP-220", item_name: "Arc floor lamp", item_category: "lighting", price: 119.00, quantity: 1 },
      { item_id: "BULB-E27-4", item_name: "Warm bulbs, pack of 4", item_category: "lighting", price: 12.25, quantity: 2 }
    ]
  }
});

Over the first month the shop records 1,340 purchases with a mean value of 93.40, and because value arrives as a number rather than a string, the average order value (AOV) in GA4 matches the shop's own finance export to within rounding.

The full item schema, the other recommended e-commerce events and the deduplication rules are the subject of the GA4 e-commerce tutorial; this guide stops at the shape of a push.

Timing: before the container, on interaction, on route change

When a push happens decides whether a tag can use it. There are three moments.

MomentWhat goes in the pushHow tags read it
Before the container snippetPage and user context: page type, template, logged-in state, content categoryThe built-in page load triggers fire after the push, so page-level tags read the values without an event key
On interaction, after the action succeedsThe event and its parameters: a confirmed form submission, an item added, a video playedA custom event trigger matching the event key
On route change in a single-page applicationA view event with the new page location, title and path, plus refreshed contextA custom event trigger, or the history change trigger if the site cannot push

The first moment is the one most often missed. If the context push runs after the snippet, the container's first events have already fired and page-level tags read defaults or nothing. The second moment has a subtler trap: pushing on the click rather than on the confirmation. A form that fails validation, a cart call that the server rejects, a payment that bounces: each produces an event if the push is wired to the attempt, and the reports then count outcomes that never happened. Push when the thing is true, not when it is tried. The third moment is the subject of the next section, because single-page applications break the assumption that a page load means a page view.

A related timing question is whether the push should wait for the container at all. It should not. The array exists whether or not the container has loaded, and the container reads everything already in it when it starts, so the site pushes whenever it has the data and never checks for Tag Manager's presence.

Single-page applications and history changes

In a single-page application the first page load is normal: the snippet runs, the built-in load events fire, the context push is read. Every view after that changes the URL through the browser's history API without reloading, so none of the page-load events fire again and, left alone, the container sees one page view per session. There are two ways to tell it otherwise. The container's history change trigger listens for those URL changes and fires a built-in event when it hears one. Or the application's router pushes an explicit view event, carrying the new location, title and path and any context that changed with the route.

The explicit push is the better design. The history change trigger fires whenever the URL changes, including changes that are not views, such as a modal opening or a filter being applied with a URL parameter, and it cannot carry the fresh context the new route needs. A push from the router fires exactly when the application considers a view to have happened and can include whatever the view knows. Whichever route is chosen, the GA4 side must be made consistent with it: GA4's enhanced measurement can also generate page views from history events, and running that alongside a manual view event doubles every view after the first. The GA4 through GTM tutorial covers the configuration setting that stops the automatic page view, and the GA4 events guide covers what enhanced measurement collects. One more consequence of the merging behaviour described earlier: entity-level keys from the previous route persist unless the router resets them, so a product page's item details can appear on the category page that follows it. Reset what should not carry over as part of the route-change push.

The developer contract and validation

The data layer fails most often not in the code but in the hand-off, when the analyst assumed one key name and the developer wrote another. The remedy is a written specification that both sides work from, and the natural home for it is the tracking plan, whose structure and lifecycle the tracking plan guide describes. For each event the contract needs:

ColumnWhat it recordsWhy it matters
Event nameThe exact event valueA one-character mismatch means no trigger fires
Trigger momentThe user action or system state that causes the push, and the condition that must be true firstSeparates attempts from outcomes
Keys and typesEvery key, its type, whether it is required, and allowed valuesLets a developer write it and a tester check it
Example pushA complete, literal exampleRemoves ambiguity that prose leaves
ConsumersWhich tags and reports depend on itShows what breaks if it changes
Owner and statusWho approved it, whether it is live, and its versionChange control

Validation has three layers. In the browser, preview mode's data layer view shows every message as it arrives and the state after each one, which is how the analyst confirms the push matches the contract on a real page. In the codebase, the site's automated tests can assert that an action produces a push with the expected shape, so a refactor that drops a key fails the build rather than the report. In the organisation, no push changes without the tracking plan changing first, which gives analytics a chance to update the container before the site deploys. A measurement plan that stops at the list of events and never reaches this level of detail produces a container that works on launch day and drifts from then on.

When a variable built on these pushes reads undefined on the event that fires its tag, the diagnosis page for an undefined data layer variable traces where the value was lost.

Common mistakes

  • Context pushed after the snippet. Page type and user state arrive too late for the page-level tags. Declare the array and push context above the container snippet.
  • Pushing on the attempt. Leads counted on click, purchases counted before payment clears. Push when the outcome is confirmed.
  • No reset before e-commerce pushes. Items from the last event leak into the next. Set ecommerce to null first, every time.
  • Numbers as strings. An order value wrapped in quotation marks is text to the tag, not an amount. Type values as the consuming tool expects.
  • Home-grown key names when a documented one exists. Every renamed key is a mapping someone must maintain. Use GA4's names where they apply.
  • Personal data in the push. Email addresses in the data layer end up in tools that forbid them. Keep identifiers hashed or out entirely.
  • A contract in someone's head. The developer and the analyst each believed the other agreed. Write the table above into the tracking plan, and start from the Tag Manager hub for the rest of the section.

Frequently asked questions

Does every data layer push need an event key?

No, but pushes without one only update the container's model of the page; they do not cause triggers to be evaluated. That is fine for page-level context pushed before the container loads, because the built-in page load events will read it. For anything that happens after load, include an event key, otherwise no custom event trigger can respond and the data sits unread until the next event arrives.

Why do values from an earlier push show up in a later event?

Because the default data layer variable merges nested objects across pushes rather than replacing them. That behaviour is useful for context that should persist, such as the page type or the logged-in state, but it means a key left out of a later push keeps its old value. For objects that must be fresh each time, such as the e-commerce object, push a reset that sets the key to null immediately before the new push.

Who owns the data layer, developers or marketing?

Both, which is why it needs a written contract. Marketing and analytics own what is measured: the event names, the keys and what each must mean. Developers own how and when the pushes happen, and they are the only people who can change them. The contract is the document both sides sign off, and the tracking plan is where it lives and is versioned.

Terms used on this page

Frameworks

Where this page is used

Part of these learning paths

Also related

Sources

  1. The data layer — Google Tag Platform

Related