Add to Cart Event
Track when users add products to their shopping cart. This event maps to Facebook AddToCart
and TikTok AddToCart standard events, enabling retargeting audiences, cart abandonment recovery,
and conversion funnel analysis.
When to Use This Event
The product.addToCart event should be triggered whenever a user adds a product to their shopping cart.
This includes:
- Clicking "Add to Cart" button on a product page
- Adding items from a product listing/category page
- Adding items from a quick-view modal
- Increasing quantity in the cart (treat as a new add event)
- Adding items from wishlist to cart
Add to Cart is a key mid-funnel event. The typical e-commerce funnel tracked by AxiTrace is:
page.view → product.view → product.addToCart → begin_checkout → transaction.charge
SDK Loading
Load the AxiTrace SDK synchronously in your <head> before any tracking calls:
<!-- In <head> -->
<script src="https://stat.axitrace.com/axitrack.js"></script>
<script>
Axitrace.init({
publicKey: 'pk_live_YOUR_PUBLIC_KEY'
});
</script>
The SDK is ~11 KB gzipped. Loading synchronously in <head> ensures
Axitrace._instance is available when your add-to-cart handler fires.
Client-Side vs Server-Side Tracking
For each add-to-cart action, use either the JavaScript SDK or the server-side API — not both.
The JavaScript SDK automatically fires Facebook and TikTok pixels with a matching
eventID, then sends the event to the AxiTrace backend which forwards it to CAPI.
Facebook/TikTok deduplicates using the shared eventID, counting one event.
If you also send the same event via the server-side PHP SDK, it generates a different
eventID — causing Facebook/TikTok to count the event twice.
Recommendation: Use the JavaScript SDK for add-to-cart events triggered by button clicks. Reserve server-side tracking for events where JavaScript may not execute (e.g., in-app browsers, mobile apps, or server-to-server integrations where no browser is involved).
Request Parameters
Required Fields
| Field | Type | Description |
|---|---|---|
label |
string | Human-readable label (e.g., product name). Required for the direct API endpoint. The JavaScript SDK auto-fills this from the page title — you don't need to set it manually. |
client |
object | User identification object. Must contain at least one identifier. |
params.sku |
string | Unique product identifier (Stock Keeping Unit). Required, non-empty. |
Client Object
The client object identifies the user. At least one of these fields is required:
| Field | Type | Description |
|---|---|---|
customId |
string | Your custom user identifier (e.g., database user ID) |
uuid |
string | Anonymous device/browser identifier (auto-generated by SDK) |
email |
string | User's email address (improves Facebook CAPI match quality) |
phone |
string | User's phone number (improves Facebook CAPI match quality) |
id |
integer | Numeric user ID |
For server-side events, you must pass the same user identifiers that the JavaScript SDK generates. The SDK stores these in cookies:
vt_vid— Visitor ID (persistent anonymous identifier → use asuuid)vt_sid— Session ID (current browsing session → use assessionId)vt_uid— User ID (set viaidentify()→ use ascustomId)
Read these cookies and pass them in your server-side events to properly link all events to the same user profile. See the User Identification guide for complete details.
Optional Fields
| Field | Type | Description |
|---|---|---|
sessionId |
string | Session identifier. The JavaScript SDK auto-fills this from the vt_sid cookie. |
time |
ISO 8601 | Event timestamp. If not provided or in the future, server time is used. |
eventSalt |
string | Unique event ID for deduplication. The SDK auto-generates a UUID for each track() call — this same ID is passed to Facebook/TikTok pixels for pixel-CAPI deduplication. |
Product Parameters (params object)
| Field | Type | Required | Description |
|---|---|---|---|
sku |
string | Required | Unique product identifier (e.g., WIDGET-001) |
name |
string | Optional | Product name. Maps to Facebook content_name and TikTok content_name |
value |
number | Recommended |
Monetary value of the cart addition. Maps directly to Facebook value and TikTok value.
Required for value-based optimization in ad platforms. Use the total value (unit price × quantity).
|
currency |
string | Recommended | ISO 4217 currency code (e.g., USD, EUR). Required when value is provided. Maps to Facebook/TikTok currency |
quantity |
number | Optional | Quantity added to cart. Must be > 0. Defaults to 1. Maps to Facebook num_items and TikTok quantity |
category |
string | Optional | Product category. Maps to Facebook content_category and TikTok content_category |
categories |
array | Optional | Array of category hierarchy (e.g., ["Electronics", "Gadgets", "Widgets"]) |
brand |
string | Optional | Product brand or producer (e.g., WidgetCo) |
url |
string | Optional | Product page URL |
The SDK passes the value field directly to Facebook and TikTok pixels for ad optimization.
If you only send price without value, the pixels will not receive
monetary data and value-based optimization won't work.
Always include value alongside price if you want Facebook/TikTok
to optimize for purchase value. Both fields are stored by AxiTrace, but only value is
forwarded to ad platform pixels.
Facebook & TikTok Pixel Parameters
When using the JavaScript SDK, you can also pass pixel-native parameter names directly. The SDK maps these to the correct format for each platform:
| SDK Parameter | Facebook Pixel | TikTok Pixel |
|---|---|---|
value |
value |
value |
currency |
currency |
currency |
content_id or productId |
content_ids (array) |
content_id |
name or content_name |
content_name |
content_name |
content_type |
content_type |
content_type |
category or content_category |
content_category |
content_category |
quantity or num_items |
num_items |
quantity |
contents |
contents |
contents |
Pricing Parameters
AxiTrace supports detailed pricing structures to track discounts and sales effectiveness:
| Field | Type | Description |
|---|---|---|
finalUnitPrice |
object | The actual price the customer pays per unit |
finalUnitPrice.amount |
number | Price amount (e.g., 79.99). Must be >= 0 |
finalUnitPrice.currency |
string | ISO 4217 currency code. Must be non-empty if provided |
regularUnitPrice |
object | Original/regular price before any discounts |
regularUnitPrice.amount |
number | Regular price amount. Must be >= 0 |
discountedUnitPrice |
object | Discounted price (if product is on sale) |
discountedUnitPrice.amount |
number | Discounted price amount. Must be >= 0 |
If you don't need to track regular vs discounted prices separately, you can use the price
field instead of the finalUnitPrice object:
{
"params": {
"sku": "WIDGET-001",
"price": 99.99,
"currency": "USD",
"value": 99.99
}
}
Note: price is stored by AxiTrace for analytics, but only value
is forwarded to Facebook/TikTok pixels. Always include both if you want pixel-based optimization.
Additional Parameters
| Field | Type | Description |
|---|---|---|
offline |
boolean | Whether this was an offline/in-store cart addition (for omnichannel tracking) |
source |
string | Source of the cart addition (e.g., product_page, quick_view, recommendation) |
Pixel Deduplication
When using the JavaScript SDK, product.addToCart events are automatically deduplicated
between browser pixels and server-side CAPI:
- SDK generates a unique
eventSalt(UUID) for eachtrack()call - SDK fires
fbq('track', 'AddToCart', params, {eventID: eventSalt})in the browser - SDK fires
ttq.track('AddToCart', params, {event_id: eventSalt})in the browser - SDK sends the event (with the same
eventSalt) to the AxiTrace backend - Backend forwards the event to Facebook CAPI and TikTok Events API with the same
eventSaltas the event ID - Facebook/TikTok matches the pixel event and CAPI event by
eventIDand counts it once
This happens automatically — you don't need to manage event IDs manually.
Server-Enriched Fields
The following fields are automatically added by the server:
| Field | Description |
|---|---|
ip |
Client IP address (extracted from X-Forwarded-For, CF-Connecting-IP, etc.) |
userAgent |
Browser User-Agent string |
timestamp |
Server timestamp (ISO 8601 format) |
Examples
JavaScript SDK (Recommended for Browser Events)
// Basic add to cart — includes value for Facebook/TikTok optimization
Axitrace._instance.track('product.addToCart', {
sku: 'WIDGET-001',
name: 'Premium Widget',
quantity: 1,
price: 99.99,
value: 99.99,
currency: 'USD'
});
// Full add to cart with pixel-optimized parameters
Axitrace._instance.track('product.addToCart', {
// AxiTrace parameters
sku: 'WIDGET-001',
name: 'Premium Widget',
quantity: 2,
category: 'Electronics',
categories: ['Electronics', 'Gadgets', 'Widgets'],
brand: 'WidgetCo',
url: window.location.href,
finalUnitPrice: {
amount: 79.99,
currency: 'USD'
},
regularUnitPrice: {
amount: 99.99,
currency: 'USD'
},
source: 'product_page',
// Pixel parameters — forwarded to Facebook & TikTok
content_id: 'WIDGET-001',
content_type: 'product',
value: 159.98, // Total: 79.99 × 2
currency: 'USD'
});
The SDK accepts multiple name formats that all map to the same event:
product.addToCart, addToCart, add_to_cart, product_addToCart.
All are normalized to product.addToCart internally and map to Facebook/TikTok AddToCart.
Server-Side (cURL)
# Server-side add to cart — use when JS SDK is not available
# Read SDK cookies (vt_vid, vt_sid, vt_uid) and pass as client identifiers
curl -X POST https://stat.axitrace.com/v1/product/addToCart \
-u "sk_live_YOUR_SECRET_KEY:" \
-H "Content-Type: application/json" \
-d '{
"label": "Premium Widget",
"client": {
"customId": "value-from-vt_uid-cookie",
"uuid": "value-from-vt_vid-cookie"
},
"sessionId": "value-from-vt_sid-cookie",
"params": {
"sku": "WIDGET-001",
"name": "Premium Widget",
"quantity": 2,
"value": 159.98,
"currency": "USD",
"finalUnitPrice": {
"amount": 79.99,
"currency": "USD"
},
"regularUnitPrice": {
"amount": 99.99,
"currency": "USD"
},
"category": "Electronics",
"brand": "WidgetCo"
}
}'
Server-Side (PHP)
<?php
$secretKey = getenv('AXITRACE_SECRET_KEY');
// Read AxiTrace SDK cookies — CRITICAL for user profile linking
$visitorId = $_COOKIE['vt_vid'] ?? null; // Persistent visitor ID
$sessionId = $_COOKIE['vt_sid'] ?? null; // Current session ID
$userId = $_COOKIE['vt_uid'] ?? null; // Authenticated user ID (if identified)
// Get product and cart data from your application
$product = getProductById($_POST['product_id']);
$quantity = (int)$_POST['quantity'];
$totalValue = $product->getFinalPrice() * $quantity;
$data = [
'label' => $product->name,
'client' => [
'customId' => $userId ?? $visitorId,
'uuid' => $visitorId,
],
'sessionId' => $sessionId,
'params' => [
'sku' => $product->sku,
'name' => $product->name,
'quantity' => $quantity,
'category' => $product->category,
'categories' => $product->getCategoryPath(),
'brand' => $product->brand,
'url' => $product->getUrl(),
'value' => $totalValue,
'currency' => 'USD',
'finalUnitPrice' => [
'amount' => $product->getFinalPrice(),
'currency' => 'USD',
],
'regularUnitPrice' => [
'amount' => $product->getRegularPrice(),
'currency' => 'USD',
],
'source' => $_POST['source'] ?? 'product_page',
]
];
// Remove null values
$data['params'] = array_filter($data['params'], fn($v) => $v !== null);
$data['client'] = array_filter($data['client'], fn($v) => $v !== null);
$ch = curl_init('https://stat.axitrace.com/v1/product/addToCart');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_USERPWD => $secretKey . ':',
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'User-Agent: MyApp/1.0'
],
CURLOPT_POSTFIELDS => json_encode($data)
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200) {
$result = json_decode($response, true);
// Event tracked successfully
}
Server-Side (Python)
import os
import requests
from flask import request # Example using Flask
secret_key = os.environ.get('AXITRACE_SECRET_KEY')
# Read AxiTrace SDK cookies — CRITICAL for user profile linking
visitor_id = request.cookies.get('vt_vid') # Persistent visitor ID
session_id = request.cookies.get('vt_sid') # Current session ID
user_id = request.cookies.get('vt_uid') # Authenticated user ID (if identified)
# Get product data from your application
product = get_product_by_id(request.form['product_id'])
quantity = int(request.form.get('quantity', 1))
total_value = float(product.get_final_price()) * quantity
response = requests.post(
'https://stat.axitrace.com/v1/product/addToCart',
auth=(secret_key, ''),
headers={
'Content-Type': 'application/json',
'User-Agent': 'MyApp/1.0'
},
json={
'label': product.name,
'client': {
'customId': user_id or visitor_id,
'uuid': visitor_id,
},
'sessionId': session_id,
'params': {
'sku': product.sku,
'name': product.name,
'quantity': quantity,
'category': product.category,
'brand': product.brand,
'url': product.get_absolute_url(),
'value': total_value,
'currency': 'USD',
'finalUnitPrice': {
'amount': float(product.get_final_price()),
'currency': 'USD',
},
'regularUnitPrice': {
'amount': float(product.regular_price),
'currency': 'USD',
},
'source': request.form.get('source', 'product_page'),
}
}
)
if response.status_code == 200:
result = response.json()
print(f"Event tracked: {result['eventId']}")
Response
Success Response (200 OK)
{
"success": true,
"eventId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"action": "product.addToCart"
}
Error Responses
| Status | Error | Description |
|---|---|---|
400 |
label is required |
The label field is missing or empty |
400 |
client must have at least one identifier (customId, id, uuid, or email) |
No user identifier provided in the client object |
400 |
params is required for product.addToCart event |
The params object is missing entirely |
400 |
params.sku is required for product.addToCart event |
SKU is missing from params |
400 |
params.sku must be a non-empty string |
SKU is empty or not a string |
400 |
params.quantity must be a number |
Quantity is not a valid number |
400 |
params.quantity must be > 0 |
Quantity is zero or negative |
400 |
params.finalUnitPrice must be an object |
finalUnitPrice is not a JSON object |
400 |
params.finalUnitPrice.amount must be a number |
Price amount is not a valid number |
400 |
params.finalUnitPrice.amount must be >= 0 |
Price is negative |
400 |
params.finalUnitPrice.currency must be a non-empty string |
Currency code is empty or not a string |
400 |
params.regularUnitPrice must be an object |
regularUnitPrice is not a JSON object |
400 |
params.regularUnitPrice.amount must be a number |
Regular price amount is not valid |
400 |
params.regularUnitPrice.amount must be >= 0 |
Regular price is negative |
400 |
params.discountedUnitPrice must be an object |
discountedUnitPrice is not a JSON object |
400 |
params.discountedUnitPrice.amount must be a number |
Discounted price amount is not valid |
400 |
params.discountedUnitPrice.amount must be >= 0 |
Discounted price is negative |
401 |
unauthorized |
Invalid or missing API key |
E-commerce Integration Examples
WooCommerce (WordPress)
WooCommerce supports AJAX add-to-cart. Listen for the jQuery event to track after the item is added:
<?php
// Add tracking data to the page (in wp_head or wp_footer)
add_action('wp_head', function() {
if (!is_product()) return;
global $product;
if (!$product) return;
$categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'names']);
?>
<script>
// Store product data for add-to-cart tracking
window.__axiProduct = {
sku: '<?php echo esc_js($product->get_sku()); ?>',
name: '<?php echo esc_js($product->get_name()); ?>',
price: <?php echo (float) $product->get_price(); ?>,
regularPrice: <?php echo (float) ($product->get_regular_price() ?: $product->get_price()); ?>,
category: '<?php echo esc_js($categories[0] ?? ''); ?>',
currency: '<?php echo get_woocommerce_currency(); ?>',
url: '<?php echo esc_js(get_permalink()); ?>'
};
// Track on WooCommerce AJAX add-to-cart success
jQuery(document.body).on('added_to_cart', function(e, fragments, cart_hash, $button) {
var p = window.__axiProduct;
var qty = parseInt($button.closest('form').find('[name="quantity"]').val()) || 1;
if (typeof Axitrace !== 'undefined' && Axitrace._instance) {
Axitrace._instance.track('product.addToCart', {
sku: p.sku,
name: p.name,
quantity: qty,
category: p.category,
value: p.price * qty,
currency: p.currency,
content_id: p.sku,
content_type: 'product',
finalUnitPrice: { amount: p.price, currency: p.currency },
regularUnitPrice: { amount: p.regularPrice, currency: p.currency },
url: p.url
});
}
});
</script>
<?php
});
Shopify
// Add to your theme's JavaScript file
// Intercept add to cart form submissions
document.addEventListener('DOMContentLoaded', function() {
const addToCartForms = document.querySelectorAll('form[action*="/cart/add"]');
addToCartForms.forEach(form => {
form.addEventListener('submit', function(e) {
// Get product data from the page (set in Liquid template)
const productData = window.currentProduct;
const quantity = parseInt(form.querySelector('[name="quantity"]')?.value || 1);
if (productData && typeof Axitrace !== 'undefined') {
Axitrace._instance.track('product.addToCart', {
sku: productData.sku,
name: productData.title,
quantity: quantity,
category: productData.type,
brand: productData.vendor,
content_id: productData.sku,
content_type: 'product',
value: (productData.price / 100) * quantity,
currency: window.Shopify?.currency?.active || 'USD',
finalUnitPrice: {
amount: productData.price / 100, // Shopify prices are in cents
currency: window.Shopify?.currency?.active || 'USD'
},
url: window.location.href
});
}
});
});
});
// Set product data in your product.liquid template:
// <script>
// window.currentProduct = {
// sku: '{{ product.selected_or_first_available_variant.sku | escape }}',
// title: '{{ product.title | escape }}',
// type: '{{ product.type | escape }}',
// vendor: '{{ product.vendor | escape }}',
// price: {{ product.price }}
// };
// </script>
React/Next.js
// useCart.js — Custom hook for cart functionality
import { useCallback } from 'react';
export function useCart() {
const addToCart = useCallback((product, quantity = 1) => {
// Your cart logic here
addItemToCart(product, quantity);
// Track with AxiTrace
if (typeof Axitrace !== 'undefined' && Axitrace._instance) {
Axitrace._instance.track('product.addToCart', {
sku: product.sku,
name: product.name,
quantity: quantity,
category: product.category,
brand: product.brand,
content_id: product.sku,
content_type: 'product',
value: (product.salePrice || product.price) * quantity,
currency: 'USD',
finalUnitPrice: {
amount: product.salePrice || product.price,
currency: 'USD'
},
regularUnitPrice: {
amount: product.price,
currency: 'USD'
},
source: 'product_page'
});
}
}, []);
return { addToCart };
}
// Usage in a component:
// const { addToCart } = useCart();
// <button onClick={() => addToCart(product, quantity)}>Add to Cart</button>
Best Practices
- Always include
valueandcurrency— These are forwarded to Facebook/TikTok for value-based ad optimization. Without them, platforms can't optimize for purchase value. - Always include SKU — Required. Should match the SKU used in product views and transactions for funnel analysis.
- Include quantity — Track the actual quantity added, not just "1" for each event. Set
valueto the total (unit price × quantity). - Pass
content_idandcontent_type— These improve Facebook catalog matching and dynamic retargeting. - Use matching user identifiers — For server-side tracking, read SDK cookies (
vt_vid,vt_sid) and pass them to link events to the same user profile. - Don't double-track — Choose either JS SDK or server-side for each event. Sending both creates duplicate events with different eventIDs.
- Track the source — Know where users add items from (product page, quick view, recommendations) for conversion analysis.
Tracking add-to-cart events is essential for cart abandonment analysis. AxiTrace can help you identify:
- Products frequently added but not purchased
- Users who abandon carts (add to cart but no transaction)
- Time between add-to-cart and purchase
- Sources that drive higher cart-to-purchase conversion