Skip to content

Instrument analytics add to cart event

time to complete
10 minutes

This example publishes an add-to-cart analytics event from a custom add-to-cart interaction. It’s one of two focused, independent examples that build on the shared helper script from Instrument analytics events without drop-ins — complete that tutorial first if you haven’t already.

Define the cart context and publish function

Section titled “Define the cart context and publish function”

Suggested file: blocks/product-details/product-details.js (the appropriate location depends on your project’s structure)

Because this event is specific to the cart, setShoppingCartContext and publishAddToCartEvent are defined here rather than in the shared scripts/acdlHelper.js — this file only imports the low-level setContext and pushEvent primitives it actually needs.

Call publishAddToCartEvent after a successful response from your add-to-cart API, passing the full updated cart — not just the item that was added:

blocks/product-details/product-details.js
import { setContext, pushEvent } from '../../scripts/acdlHelper.js';
const SHOPPING_CART_CONTEXT = 'shoppingCartContext';
const ADD_TO_CART = 'add-to-cart';
/**
* Sets the shopping cart context in the Adobe Client Data Layer (ACDL).
*
* @param {Array<{
* id: string, - Unique cart line item identifier
* quantity: number, - Quantity in cart (min 1)
* prices: {
* price: {
* value: number, - Numeric price value
* currency?: string, - ISO 4217 currency code
* }
* },
* product: {
* productId: number, - Numeric product ID
* name: string, - Product display name
* sku: string, - Product SKU
* topLevelSku: string, - Parent/base product SKU
* mainImageUrl?: string|null
* },
* }>} items - Line items currently in the cart
*
* @param {{
* id?: string|null, - Cart identifier
* totalQuantity?: number, - Total item quantity (derived from items if omitted)
* prices?: {
* subtotalExcludingTax?: { value: number, currency?: string },
* subtotalIncludingTax?: { value: number, currency?: string }
* },
* possibleOnepageCheckout?: boolean,
* giftMessageSelected?: boolean,
* giftWrappingSelected?: boolean,
* source?: string, - UI component or page that triggered the cart action
* discountAmount?: number
* }} [cartDetails={}] - Cart-level metadata
*/
function setShoppingCartContext(items, cartDetails = {}) {
if (!Array.isArray(items)) {
throw new TypeError('items must be an array');
}
for (const [index, item] of items.entries()) {
const missingFields = ['id', 'prices', 'product', 'quantity']
.filter((field) => item[field] === undefined);
if (missingFields.length) {
throw new Error(`Cart item [${index}] is missing required fields: ${missingFields.join(', ')}`);
}
if (item.quantity < 1) {
throw new Error(`Cart item [${index}]: quantity must be at least 1`);
}
const missingProductFields = ['productId', 'name', 'sku'].filter((field) => item.product[field] === undefined);
if (missingProductFields.length) {
throw new Error(`Cart item [${index}].product is missing required fields: ${missingProductFields.join(', ')}`);
}
}
const totalQuantity = cartDetails.totalQuantity ?? items.reduce((sum, item) => sum + item.quantity, 0);
setContext(SHOPPING_CART_CONTEXT, {
...cartDetails,
totalQuantity,
items,
});
}
function publishAddToCartEvent(items, cartDetails = {}) {
setShoppingCartContext(items, cartDetails);
pushEvent(ADD_TO_CART);
}
const sampleCartItem = {
id: 'SNK-001-WHT-cart-1',
quantity: 1,
prices: {
price: { value: 129.99, currency: 'USD' },
},
product: {
productId: 1001,
name: 'Classic Leather Sneaker',
sku: 'SNK-001-WHT',
topLevelSku: 'SNK-001-WHT',
mainImageUrl: 'https://example.com/images/snk-001-wht.jpg',
},
};
// Called on button click — in production this fires after your add-to-cart API responds
publishAddToCartEvent([sampleCartItem]);
  1. Open your browser’s developer tools and check the Console tab.
  2. Confirm window.adobeDataLayer exists and contains a shoppingCartContext entry and an add-to-cart event.
  3. If Adobe Experience Platform (AEP) forwarding is configured, use the AEP Debugger Events view to confirm the event arrives — see Analytics instrumentation.

In this tutorial, you learned how to publish an add-to-cart event with the full updated cart from a custom add-to-cart interaction.