Sub topic 10
Implementing e-commerce events with gtag.js
This chapter assumes you know the GA4 event and parameter model, the structure of the items array, and how currency and value work. It also assumes you can read JavaScript objects and arrays. Here you will wire those pieces together on a web page with gtag.js.
How gtag.js sends an event
gtag.js is Google's JavaScript library for sending data to GA4 and other Google products. You load it once per page. After that, you call the gtag() function to configure the library and to send events.
The base snippet looks like this. Replace G-XXXXXXX with the measurement ID of your web data stream.
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
</script>The gtag() function does not send anything by itself. It pushes its arguments onto the dataLayer array, and the loaded library reads that queue and sends the hits. This is why you can call gtag() before the library finishes loading. The calls wait in the queue.
An event call has three parts:
- The command name,
'event'. - The event name, such as
'add_to_cart'. - An object of parameters, such as
currency,value, anditems.
Sending add_to_cart
The add_to_cart event fires when a visitor puts a product in the cart. Send currency, value, and an items array.
gtag('event', 'add_to_cart', {
currency: 'USD',
value: 49.98,
items: [
{
item_id: 'SKU_1001',
item_name: 'Trail Running Shoe',
item_brand: 'Acme',
item_category: 'Shoes',
item_variant: 'blue',
price: 24.99,
quantity: 2
}
]
});The value here is the sum of price times quantity for every item in the event: 24.99 × 2 = 49.98. The currency is a three-letter ISO 4217 code. Without it, GA4 cannot interpret value as money, and the amount will not show up in revenue metrics.
Sending purchase
The purchase event is the one that creates revenue, so it needs the most care.
gtag('event', 'purchase', {
transaction_id: 'T_12345',
currency: 'USD',
value: 49.98,
tax: 4.00,
shipping: 5.99,
coupon: 'SUMMER_SALE',
items: [
{
item_id: 'SKU_1001',
item_name: 'Trail Running Shoe',
price: 24.99,
quantity: 2,
index: 0
}
]
});Check these points before you ship it:
transaction_idmust be unique for each order. GA4 uses it to ignore repeated purchase events that carry an ID it has already seen.valueis a number. Send49.98, not'$49.98'or'49.98 USD'.taxandshippingare separate parameters. Whethervalueincludes them is a decision you make once and apply to every purchase. The example here uses the items total only.priceis the unit price, andquantitymultiplies it. Do not put the line total inprice.
Where to fire each event
Each event belongs to a moment in the shopper's journey, and each moment usually maps to a page or a user action.
| Event | Typical trigger |
|---|---|
| `view_item_list` | A category or search results page renders its product list |
| `select_item` | The visitor clicks a product in that list |
| `view_item` | A product detail page loads |
| `add_to_cart` | The visitor clicks the add button and the cart accepts it |
| `begin_checkout` | The visitor starts checkout |
| `purchase` | The order confirmation is displayed after the order is saved |
Building events from real data
Hard-coded values are fine for learning, but a shop builds events from its own product data. A small helper keeps the calculation of value in one place.
function buildItem(product, quantity) {
return {
item_id: product.sku,
item_name: product.name,
item_brand: product.brand,
item_category: product.category,
item_variant: product.variant,
price: product.price,
quantity: quantity
};
}
function trackAddToCart(product, quantity) {
const item = buildItem(product, quantity);
const value = Math.round(item.price * item.quantity * 100) / 100;
gtag('event', 'add_to_cart', {
currency: 'USD',
value: value,
items: [item]
});
}
document.querySelector('#add-button').addEventListener('click', function () {
trackAddToCart(
{
sku: 'SKU_1001',
name: 'Trail Running Shoe',
brand: 'Acme',
category: 'Shoes',
variant: 'blue',
price: 24.99
},
2
);
});The rounding step guards against floating-point results such as 0.1 * 3 giving 0.30000000000000004. Keeping money in a single helper also means every event type uses the same rules.
Single-page applications
On a traditional site, each page load starts a fresh JavaScript context, so a purchase call on the confirmation page runs once. In a single-page application (SPA), the page does not reload when the route changes, and your code decides when to fire events.
- Fire
view_itemandview_item_listfrom the route or component that shows the content, not from a global script that runs once. - Guard against components that render more than once. A framework that re-renders can send the same
view_itemseveral times. - For
purchase, persist a flag keyed bytransaction_id, for example insessionStorage, so that a refresh of the confirmation view does not send the event again.
function trackPurchaseOnce(order) {
const key = 'ga_purchase_' + order.id;
if (sessionStorage.getItem(key)) {
return;
}
sessionStorage.setItem(key, '1');
gtag('event', 'purchase', {
transaction_id: order.id,
currency: order.currency,
value: order.itemsTotal,
tax: order.tax,
shipping: order.shipping,
items: order.items
});
}GA4 also deduplicates by transaction_id, but a client-side guard stops the extra hits from being sent at all and keeps other reports, such as event counts, clean.
Common errors
- The library is blocked. Ad blockers and consent tools can stop gtag.js from loading. Events then queue in
dataLayerand are never sent. - Events fire before the item data exists. If the call runs while a price is still
undefined, GA4 receives an incomplete item. Fire the call after the data is available. valueanditemsdisagree. GA4 does not recomputevaluefromitems. If your code sums them wrongly, reports show the wrong revenue.- Stale parameters. When you call
gtag('set', ...), the values persist for later events on the page. Do not usesetfor per-event data such as items. - Missing
currency. The event is recorded, but its money fields are not usable for revenue.
Checking your work
After adding calls, confirm them in the browser before relying on reports. Open DebugView (covered in a later chapter), or open your browser's Network tab and filter for collect. Each request to google-analytics.com/g/collect carries the event name in the en parameter and the transaction in ep.transaction_id-style fields. Check that every event in the funnel appears once, with the expected values.
Exercise
A shop's order confirmation page is a single-page view. A tester refreshes it three times and sees three purchase requests leave the browser, all with transactionid 'T9001'. What two measures prevent the extra hits, and why is the second one not enough on its own?
Show answer
Persist a flag keyed by transactionid, such as in sessionStorage, and skip the gtag call if the flag exists, so the extra hits are never sent. The other measure is to always send a unique transactionid, which lets GA4 ignore repeated purchases with an ID it has already seen. Relying only on GA4's deduplication is not enough because the repeated events still leave the browser and can inflate event counts in other reports, while the client-side guard keeps the data clean at the source.
Exercise
You call gtag('event', 'addtocart', { value: 49.98, items: [...] }) and revenue-related reports show nothing for it. What is missing, and what else should you check about value?
Show answer
The currency parameter is missing, so GA4 cannot interpret value as money. Also check that value is a number and equals the sum of price times quantity for the items, because GA4 does not calculate it from the items array.