Sub topic 11
Implementing E-commerce Events with the GTM dataLayer
Assume you understand GA4 properties and data streams, JavaScript objects and arrays, and the basic flow of a web shop. This chapter focuses on how Google Tag Manager (GTM) moves e-commerce data from a page into a GA4 event tag.
The GTM dataLayer is a JavaScript array used to pass structured information to GTM. A push normally contains:
event: the name that triggers a GTM tagecommerce: the GA4 event parametersitems: an array of products
window.dataLayer = window.dataLayer || [];
// Remove data from a previous ecommerce push.
dataLayer.push({ ecommerce: null });
dataLayer.push({
event: 'view_item',
ecommerce: {
currency: 'USD',
value: 24.99,
items: [
{
item_id: 'SKU_1001',
item_name: 'Trail Running Shoe',
item_brand: 'Acme',
item_category: 'Shoes',
item_variant: 'blue',
price: 24.99,
quantity: 1
}
]
}
});The first push clears the previous ecommerce object. This matters because some data layer implementations merge objects. Without the reset, an old coupon, value, or item list can remain available to a later event.
Connect the dataLayer to GTM
In GTM, create Data Layer Variables for the values your GA4 tag needs:
ecommerce.currencyecommerce.valueecommerce.items
Then create a Custom Event trigger. Set its event name to view_item. Create a GA4 Event tag with:
- Event name:
{{Event}}, or a fixed name such asview_item currency:{{DLV - ecommerce.currency}}value:{{DLV - ecommerce.value}}items:{{DLV - ecommerce.items}}
Publish the container only after testing the tag in Preview mode. Repeat this pattern for view_item_list, select_item, add_to_cart, begin_checkout, and purchase. Each event needs the correct custom event trigger and its own event data.
Common errors
A data layer push does not send data to GA4 by itself. A matching trigger and GA4 tag must process it. Also check that items is an array, prices and quantities are numbers, and the event name matches exactly. For a purchase, include a stable, unique transaction_id so a page reload does not create another transaction.
Use GTM Preview to inspect the event, variable values, and tag status. Then use GA4 DebugView to confirm that GA4 received the event and its parameters.
Exercise
Why should the ecommerce object be cleared before a new product event is pushed?
Show answer
Clearing it prevents values from an earlier event, such as items, coupons, or currency, from carrying into the new event.