Guide · Tracking and data

The Shopify data layer: events and code for Google Tag Manager

What a data layer is, which ecommerce events a Shopify store should push for Google Tag Manager, code for each page type and checkout, and how to test it.

Updated · 9 min read

By the ROASaurus team

The short answer
  • A data layer is the window.dataLayer list into which your store pushes structured events, such as a product view with its id and price, for Google Tag Manager to read.
  • Shopify themes do not push ecommerce events by default; you add them with Liquid and JavaScript on the storefront, and with a custom pixel for checkout.
  • Use Google's GA4 ecommerce format (view_item, add_to_cart, begin_checkout, purchase with an items array), so GA4, Google Ads and other tags can share one data layer.
  • Item ids must match the ids in your product feeds, or remarketing and product reports cannot connect them.
  • Test every event in GTM preview on the storefront and in each platform's test view for checkout, where preview mode does not work.

Google Tag Manager reads data; it does not create it. Every tag that needs a product id, a price or an order value gets it from the data layer. On Shopify there is no ecommerce data layer out of the box, so a store that runs GTM has to build one or install an app that does. This guide explains what to push, on which page, in which format, with code you can adapt, and how to test it.

What a data layer is

The data layer is a JavaScript array, window.dataLayer, that sits on every page. Your store pushes objects into it as things happen. GTM watches the array: an object with an event key can fire triggers, and its other keys become data layer variables that tags read.

Page or actionA product page loads, or the shopper adds to cart.
PushThe theme pushes { event: "add_to_cart", ecommerce: { … } }.
TriggerA GTM custom event trigger matches add_to_cart.
TagsGA4, Google Ads, Meta and TikTok tags read the values and send them.
One push feeds every tag. Without it, each tag scrapes the page in its own way.

Why it matters: values read from the page (a price in a heading, a title in a meta tag) break when the theme changes and differ between tags. A data layer gives every tag the same, structured values from Shopify's own objects.

What you need before you start

  • GTM installed on the storefront (see our guide to Google Tag Manager on Shopify).
  • Access to the theme code: layout/theme.liquid and the product, collection, cart and search templates or sections.
  • A decision on item ids: SKU, variant id, or the id format of your Merchant Center and Meta catalogue feeds.
  • A decision on value: with or without tax, shipping and discounts, the same for every event.
  • A consent setup, so tags that read the data layer still wait for the visitor's choice.

The events to push

Use Google's recommended GA4 ecommerce events. GA4 understands them directly, Google Ads dynamic remarketing reads the same items array, and Meta and TikTok tags can map them to their own names.

EventWhenMain parameters
view_item_listCollection and search result pagesitem_list_name, items
select_itemClick on a product in a listitem_list_name, items
view_itemProduct page, and on variant changecurrency, value, items
add_to_cartA product added (form, quick add, cart drawer)currency, value, items with quantity
remove_from_cartA line removed or reducedcurrency, value, items
view_cartCart page or drawer openedcurrency, value, items
searchSearch submittedsearch_term
begin_checkoutCheckout started (custom pixel)currency, value, items
add_shipping_info / add_payment_infoCheckout steps (custom pixel)shipping_tier / payment_type
purchaseOrder completed (custom pixel)transaction_id, value, tax, shipping, items
Each item carries item_id, item_name, item_brand, item_category, item_variant, price and quantity. Use the same item_id everywhere.

Swipe the table sideways to see every column.

Besides events, a page-level push can carry context that tags use: page type (home, collection, product, cart), the store currency, the market, and whether the visitor is a logged-in customer. Push it once per page, before the GTM container's triggers need it.

Code blocks for the storefront

These examples use Liquid, Shopify's template language. Prices in Liquid are in cents, so divide by 100. Clear the previous ecommerce object before each push, as Google recommends, so values from one event do not leak into the next.

Product page: view_item

In the product template or main product section
<script>
  window.dataLayer = window.dataLayer || [];
  {%- assign v = product.selected_or_first_available_variant -%}
  window.dataLayer.push({ ecommerce: null });
  window.dataLayer.push({
    event: 'view_item',
    ecommerce: {
      currency: {{ cart.currency.iso_code | json }},
      value: {{ v.price | divided_by: 100.0 }},
      items: [{
        item_id: {{ v.sku | default: v.id | json }},
        item_name: {{ product.title | json }},
        item_brand: {{ product.vendor | json }},
        item_category: {{ product.type | json }},
        item_variant: {{ v.title | json }},
        price: {{ v.price | divided_by: 100.0 }},
        quantity: 1
      }]
    }
  });
</script>

Collection page: view_item_list

In the collection template; limit the list to what is shown
<script>
  window.dataLayer.push({ ecommerce: null });
  window.dataLayer.push({
    event: 'view_item_list',
    ecommerce: {
      item_list_name: {{ collection.title | json }},
      items: [
        {%- for p in collection.products limit: 20 -%}
        { item_id: {{ p.selected_or_first_available_variant.sku | default: p.selected_or_first_available_variant.id | json }},
          item_name: {{ p.title | json }}, price: {{ p.price | divided_by: 100.0 }}, index: {{ forloop.index0 }} }{% unless forloop.last %},{% endunless %}
        {%- endfor -%}
      ]
    }
  });
</script>

Add to cart

Themes add products in different ways: a classic form post, a fetch request to /cart/add.js, a quick-add button, a cart drawer. The robust way is to listen to the cart request itself and push when it succeeds:

In theme.liquid, after the data layer is defined
<script>
  (function () {
    var origFetch = window.fetch;
    window.fetch = function (input, init) {
      var url = typeof input === 'string' ? input : input.url;
      return origFetch.apply(this, arguments).then(function (res) {
        if (/\/cart\/add(\.js)?/.test(url) && res.ok) {
          res.clone().json().then(function (item) {
            var line = item.items ? item.items[0] : item;
            window.dataLayer.push({ ecommerce: null });
            window.dataLayer.push({ event: 'add_to_cart', ecommerce: {
              currency: window.Shopify && Shopify.currency ? Shopify.currency.active : undefined,
              value: line.final_line_price / 100,
              items: [{ item_id: line.sku || String(line.variant_id), item_name: line.product_title,
                        item_variant: line.variant_title, price: line.final_price / 100, quantity: line.quantity }]
            } });
          });
        }
        return res;
      });
    };
  })();
</script>

Cart: view_cart and remove_from_cart

On the cart page, push view_cart with every line from the Liquid cart object. For removals, compare the cart before and after a change request to /cart/change.js or /cart/update.js and push remove_from_cart with the lines that went down.

Checkout and purchase: a custom pixel

Theme code does not run in Shopify's checkout. The checkout events come from Shopify's Web Pixels API, inside a custom pixel under Settings › Customer events. The pixel loads its own copy of GTM and pushes to the data layer inside its sandbox.

Purchase in a custom pixel; begin_checkout works the same with checkout_started
analytics.subscribe('checkout_completed', (event) => {
  const c = event.data.checkout;
  window.dataLayer.push({ ecommerce: null });
  window.dataLayer.push({
    event: 'purchase',
    ecommerce: {
      transaction_id: c.order.id,
      value: Number(c.subtotalPrice.amount),
      tax: Number(c.totalTax.amount),
      shipping: Number(c.shippingLine?.price.amount ?? 0),
      currency: c.currencyCode,
      items: c.lineItems.map((li) => ({
        item_id: li.variant.sku || li.variant.id,
        item_name: li.title,
        item_variant: li.variant.title,
        price: Number(li.variant.price.amount),
        quantity: li.quantity,
      })),
    },
  });
});

The sandbox has limits: GTM's preview mode cannot connect to it, and Google does not support it for conversion measurement. Our guides to GTM on Shopify and checkout extensibility explain them.

Reading the data layer in GTM

  1. Create triggers

    One Custom Event trigger per event name: view_item, add_to_cart, begin_checkout, purchase.

  2. Create variables

    Data Layer Variables for ecommerce.value, ecommerce.currency, ecommerce.transaction_id and ecommerce.items.

  3. GA4 event tags

    Tick "Send ecommerce data" with the data layer as source; GA4 reads the ecommerce object as it is.

  4. Other platforms

    Map the values in each tag: Meta's content_ids from the item ids, value and currency; TikTok's contents array; Google Ads remarketing items with id and google_business_vertical.

  5. Consent

    Set each tag's consent requirements, so it waits for the visitor's choice.

Test the data layer

  • Open GTM preview on the storefront and walk through: collection, product, variant change, add to cart, cart, remove.
  • For each event, check the data layer tab: right event name, prices in units not cents, currency, item ids in the feed format.
  • Type dataLayer in the browser console to see every push in order.
  • For checkout, publish a container version and place a test order; check GA4 DebugView and each platform's test view.
  • Repeat with marketing cookies declined: the pushes may still happen, but tags must not fire.

Common mistakes

  • Prices in cents. A €40 product pushed as 4000 inflates revenue a hundredfold.
  • Ids that do not match the feed. A SKU in the data layer and shopify_NL_123_456 in Merchant Center cannot be joined for remarketing.
  • No ecommerce reset. Items from a view_item end up in the next add_to_cart.
  • Events pushed twice. An app and the theme both push add_to_cart, so every add counts double.
  • Purchase from the Thank you page in the theme. Theme code does not run there any more; use the pixel.
  • Personal data in the data layer without a reason. Push hashed values only where a tag needs them and consent allows.
  • Markets and currencies ignored. Use the active currency, not the store's base currency, when the shopper browses in another one.

The data layer and ROASaurus

ROASaurus can fill the storefront part of the data layer for you. Its storefront script, already on the store for server-side tracking, captures page and product views, collection and search pages, searches and cart changes. With one store setting, which is off by default, it also pushes those events into window.dataLayer in Google's GA4 ecommerce format, so your web GTM tags can read them without the theme code above.

What is pushedDetails
page_viewPage type, market, country, currency and language
view_item, view_item_list, searchItems with item_id (the variant id), item_group_id (the product id), name, SKU, price and quantity; on lists the list name and position; the search term
add_to_cart, remove_from_cart, view_cartThe items, value and currency
generate_lead, page_not_foundSite forms, and pages that do not exist
Each push first clears the previous ecommerce object and carries the event id ROASaurus sent to the server, for deduplication in your tags.

What it does not do:

  • No checkout events on Shopify. Shopify's checkout and Thank you page run outside the theme, so begin_checkout, the checkout steps and the purchase are not pushed there. ROASaurus's checkout pixel still sends them to your destinations server-side; for web GTM checkout and purchase tags, keep the custom pixel above.
  • No customer identifiers. No email, customer id or other identifier is pushed, only items, values and page details.
  • No product clicks or variant changes. select_item and a view_item on variant change are not detected; add them with theme code if your tags need them.
  • Feed ids are yours to map. The item_id is the Shopify variant id. If your Merchant Center feed uses another format, build it in the tag from the variant and product ids.

Events are pushed only for visitors the store's consent mode allows to be tracked, like every other ROASaurus event. The setting links a ready GTM container to import, with a Google tag for your GA4 measurement id and one GA4 event tag for these events, with the event id as a parameter. See the data layer feature page.

In ROASaurusSettings › Store
  1. Install the ROASaurus Shopify app; its storefront script captures the events.
  2. Open Settings › Store, tick "Push storefront events to the data layer for Google Tag Manager" and save.
  3. Import the GTM container linked under the setting, or use the events in your own triggers and variables.
  4. Open GTM preview on the storefront, walk through a product, a collection and an add to cart, and check the pushes in the data layer tab.
  5. For checkouts and purchases, add the destinations you send server-side under Connections › Tracking & destinations, and check Data quality › Deliveries to see each event per destination.

Start freeOpen the live demo14-day trial of every feature, no credit card.

Sources

  1. Google for Developers: The data layer
  2. Google for Developers: Measure ecommerce (GA4)
  3. Shopify Dev: Web pixels API standard events
  4. Shopify Help Center: Create a Google Tag Manager custom pixel
  5. Google Ads Help: Dynamic remarketing events and parameters

More guides on tracking and data · All guides

FAQ

Questions, answered

More answers in the FAQ and the help center.

What is a data layer on Shopify?

It is the window.dataLayer array into which a store pushes structured events, such as product views and purchases with ids and prices, for Google Tag Manager and its tags to read.

Does Shopify have a data layer by default?

No. Shopify themes do not push ecommerce events into window.dataLayer. You add the pushes with Liquid and JavaScript, or use an app that does it.

Which events should a Shopify data layer include?

At least view_item, add_to_cart, view_cart, begin_checkout and purchase in Google's GA4 ecommerce format, plus view_item_list, remove_from_cart and search for fuller reports.

How do I push the purchase to the data layer on Shopify?

Through a custom pixel under Settings › Customer events that subscribes to checkout_completed and pushes a purchase event into the data layer inside the pixel. Theme code does not run on the Thank you page.

Which item id should I use in the data layer?

The id your product feeds use. For Google Merchant Center feeds from Shopify's Google & YouTube app that is a combined id with country, product id and variant id; for many Meta catalogues it is the variant id.

Should I put the customer's email in the data layer?

Only if a tag needs it, hashed where possible, and only for visitors whose consent allows the tag to use it. Anything in the data layer can be read by every script on the page.

Can ROASaurus fill the data layer on Shopify?

Yes, for storefront events. With "Push storefront events to the data layer for Google Tag Manager" ticked under Settings › Store (off by default), its storefront script pushes page views, product and list views, searches and cart changes in GA4's ecommerce format. Checkout events and purchases in Shopify's checkout are not pushed; they reach your destinations server-side.

What are the steps to set up a data layer?

Decide ids and values, add the storefront pushes to the theme, add a custom pixel for checkout events, create triggers and variables in GTM, then test in preview and with test orders.

Every sale, traced to the ad that earned it

Server-side tracking, profit and lifetime value in one app. Free plan, no credit card.