Tracking API Reference
The SDK provides two complementary APIs for tracking analytics events. Choose the simple API for quick implementations or the advanced API for full control.
API Overview
Section titled “API Overview”Best for: Quick implementations, minimal code
// Simple, clean method callsnext.trackAddToCart(packageId, quantity);next.trackViewItem(packageId);next.trackBeginCheckout();next.trackPurchase(orderData);Features:
- Handles async loading automatically
- Simple parameter signatures
- Works before SDK fully loads (queued)
- Ideal for most use cases
Best for: Advanced tracking, custom events, full control
// Direct access to analytics enginewindow.NextAnalytics.trackAddToCart(item, listId, listName);window.NextAnalytics.track({ event: 'custom', data: '...' });window.NextAnalytics.setDebugMode(true);Features:
- Full item data objects
- List attribution support
- Custom event tracking
- Debug and status methods
- Direct analytics engine access
E-commerce Events
Section titled “E-commerce Events”Add to Cart
Section titled “Add to Cart”Track when items are added to the cart.
// Track with package ID and quantitynext.trackAddToCart('123', 1);
// With quantitynext.trackAddToCart('456', 2);Parameters:
packageId(string|number) - Product/package identifierquantity(number, optional) - Quantity added (default: 1)
Auto-tracked when:
- Using
data-next-action="add-to-cart"attributes - Calling cart methods like
next.addToCart()
// With full item datawindow.NextAnalytics.trackAddToCart({ id: 'pkg-123', packageId: '123', title: 'Premium Package', price: 99.99, quantity: 1});
// With list attributionwindow.NextAnalytics.trackAddToCart({ id: 'pkg-123', packageId: '123', title: 'Premium Package', price: 99.99, quantity: 1}, 'summer-collection', 'Summer Sale 2025');Parameters:
item(object) - Full item dataid(string) - Unique item identifierpackageId(string|number) - Package IDtitle(string) - Product nameprice(number) - Unit pricequantity(number) - Quantity
listId(string, optional) - Product list ID for attributionlistName(string, optional) - Product list name for attribution
Remove from Cart
Section titled “Remove from Cart”Track when items are removed from the cart.
// Track removalnext.trackRemoveFromCart('123', 1);Parameters:
packageId(string|number) - Product identifierquantity(number, optional) - Quantity removed
// Using EcommerceEvents helperimport { EcommerceEvents } from '@/utils/analytics';import { dataLayer } from '@/utils/analytics';
const event = EcommerceEvents.createRemoveFromCartEvent(item);dataLayer.push(event);Auto-tracked when:
- Using cart removal methods
View Item
Section titled “View Item”Track product detail page views.
// Track product viewnext.trackViewItem('123');Parameters:
packageId(string|number) - Product identifier
Auto-tracked when:
- Page has exactly 1 product with
data-next-package-id - Selected items in
data-next-selection-mode="select"selectors - Selected items in
data-next-selection-mode="swap"selectors
// With full product datawindow.NextAnalytics.trackViewItem({ id: 'pkg-123', packageId: '123', title: 'Premium Package', price: 99.99});Parameters:
item(object) - Product dataid(string) - Unique identifierpackageId(string|number) - Package IDtitle(string) - Product nameprice(number) - Price
View Item List
Section titled “View Item List”Track product list/collection views.
// Track list viewnext.trackViewItemList( ['123', '456', '789'], 'summer-sale', 'Summer Sale Collection');Parameters:
packageIds(array) - Array of product IDslistId(string) - List identifierlistName(string) - List display name
Auto-tracked when:
- URL matches collection/category patterns
- Page type detected as product list
window.NextAnalytics.trackViewItemList(items, listId, listName);Parameters:
items(array) - Array of item objectslistId(string) - List identifierlistName(string) - List display name
Begin Checkout
Section titled “Begin Checkout”Track when checkout process starts.
// Track checkout startnext.trackBeginCheckout();No parameters required - automatically includes cart items
Auto-tracked when:
- Checkout page loads (in auto mode)
window.NextAnalytics.trackBeginCheckout();Automatically includes:
- All current cart items
- Cart total value
- Currency
- User properties
Purchase
Section titled “Purchase”Track completed orders.
// Minimal purchase trackingnext.trackPurchase({ id: 'ORDER_123', total: 159.99, currency: 'USD', tax: 9.99, shipping: 10.00});
// With itemsnext.trackPurchase({ id: 'ORDER_123', total: 159.99, currency: 'USD', items: [ { id: 'SKU-123', name: 'Product Name', price: 149.99, quantity: 1 } ]});Parameters:
orderData(object)id(string) - Required - Order IDtotal(number) - Required - Order totalcurrency(string) - Currency code (default: ‘USD’)tax(number, optional) - Tax amountshipping(number, optional) - Shipping costitems(array, optional) - Order line items
// Full order data from backendwindow.NextAnalytics.trackPurchase({ order: { ref_id: 'ORD-12345', number: '12345', total_incl_tax: '159.99', total_tax: '9.99', shipping_incl_tax: '10.00', currency: 'USD', user: { first_name: 'John', last_name: 'Doe' }, lines: [ { product_sku: 'SKU-123', product_title: 'Product Name', price_incl_tax: '149.99', quantity: 1 } ], billing_address: { first_name: 'John', last_name: 'Doe', city: 'San Francisco', state: 'CA', postcode: '94102', country: 'US' } }});Parameters:
orderData(object)order(object) - Complete order object from backend- Automatically transforms to GA4 format
- Includes user properties, items, transaction details
Auto-tracked: Yes (queued and fired on confirmation page)
Event Queue: Purchase events are queued to sessionStorage when order completes, then automatically fired on the confirmation page after redirect.
Manual tracking (optional):
You can manually trigger purchase events if needed (e.g., for testing or special integrations):
// Manually track with order data from sessionStorage['next-order']const orderData = JSON.parse(sessionStorage.getItem('next-order'))?.state?.order;if (orderData) { next.trackPurchase({ order: orderData });}
// Or provide custom order datanext.trackPurchase({ id: 'ORDER_123', total: 159.99, currency: 'USD'});User Events
Section titled “User Events”Sign Up
Section titled “Sign Up”Track user registration.
// Track registrationParameters:
email(string) - User email address
Automatically includes:
- User email
- Timestamp
- Session data
- Attribution
Track user login.
Custom Events
Section titled “Custom Events”Track custom business events.
// Only available via advanced APIwindow.NextAnalytics.track({ event: 'newsletter_subscribe', list_name: 'Weekly Newsletter', source: 'footer_form'});
// Video engagementwindow.NextAnalytics.track({ event: 'video_played', video_id: 'intro-demo', video_title: 'Product Introduction', duration: 120});
// Feature usagewindow.NextAnalytics.track({ event: 'feature_used', feature_name: 'product_comparison', items_compared: 3});Parameters:
eventData(object) - Custom event objectevent(string) - Required - Event name (use snake_case)- Any additional properties as needed
Custom events are sent to all enabled providers.
See Custom Events Guide for advanced patterns and EventBuilder usage.
Utility Methods
Section titled “Utility Methods”setDebugMode
Section titled “setDebugMode”Enable or disable debug logging.
// Enable debug modewindow.NextAnalytics.setDebugMode(true);
// Disablewindow.NextAnalytics.setDebugMode(false);Parameters:
enabled(boolean) - Enable/disable debug logs
Debug output includes:
- Event names and data
- Provider dispatch confirmations
- Validation warnings
- Error messages
getStatus
Section titled “getStatus”Get current analytics status and configuration.
const status = window.NextAnalytics.getStatus();console.log(status);Returns:
{ enabled: true, mode: 'auto', providers: ['GTM', 'Facebook', 'RudderStack', 'Custom'], eventsTracked: 15, debugMode: false, sessionId: 'sess_abc123', version: '0.2.0'}Method Reference Tables
Section titled “Method Reference Tables”Simple API (next.*)
Section titled “Simple API (next.*)”| Method | Parameters | Description | Auto-Tracked |
|---|---|---|---|
trackViewItem() | packageId | Product detail view | Yes* |
trackAddToCart() | packageId, quantity? | Add item to cart | Yes* |
trackRemoveFromCart() | packageId, quantity? | Remove from cart | Yes* |
trackViewItemList() | packageIds[], listId, listName | Product list view | Yes* |
trackBeginCheckout() | - | Checkout initiation | Yes* |
trackPurchase() | orderData | Order completion | Yes* |
trackSignUp() | User registration | No | |
trackLogin() | User login | No |
*Auto-tracked only in auto mode
Advanced API (window.NextAnalytics)
Section titled “Advanced API (window.NextAnalytics)”| Method | Parameters | Description |
|---|---|---|
trackAddToCart() | item, listId?, listName? | Add to cart with list attribution |
trackRemoveFromCart() | item | Remove from cart |
trackViewItem() | item | Product detail view |
trackViewItemList() | items[], listId, listName | Product list view |
trackBeginCheckout() | - | Checkout initiation |
trackPurchase() | orderData | Order completion |
trackSignUp() | User registration | |
trackLogin() | User login | |
track() | eventData | Custom event |
setDebugMode() | enabled | Enable/disable debug logs |
getStatus() | - | Get analytics status |
Usage Patterns
Section titled “Usage Patterns”Track on Page Load
Section titled “Track on Page Load”window.addEventListener('DOMContentLoaded', () => { // Product page if (productData) { next.trackViewItem(productData.id); }
// Order confirmation if (orderData) { next.trackPurchase(orderData); }});Track Before SDK Loads
Section titled “Track Before SDK Loads”Use the nextReady queue:
window.nextReady = window.nextReady || [];window.nextReady.push(function() { next.trackAddToCart('123', 1); next.trackBeginCheckout();});Track from Event Handlers
Section titled “Track from Event Handlers”// Button clickdocument.getElementById('subscribe-btn').addEventListener('click', () => { window.NextAnalytics.track({ event: 'newsletter_subscribe', source: 'hero_section' });});
// Form submissionform.addEventListener('submit', (e) => { window.NextAnalytics.track({ event: 'form_submitted', form_id: 'contact' });});Track with List Attribution
Section titled “Track with List Attribution”// Set list attribution when viewing a collectionwindow.NextAnalytics.trackViewItemList( items, 'summer-sale-2025', 'Summer Sale Collection');
// Attribution automatically included when user adds to cartnext.trackAddToCart('123', 1);// Event includes: item_list_id: 'summer-sale-2025', item_list_name: 'Summer Sale Collection'Error Handling
Section titled “Error Handling”The SDK handles analytics errors gracefully:
// Analytics errors never break your apptry { next.trackPurchase(orderData);} catch (error) { // Error automatically logged in debug mode // App continues functioning normally}Error behavior:
- Errors logged to console in debug mode
- Events still stored in NextDataLayer
- Failed provider doesn’t affect others
- SDK functionality unaffected
TypeScript Support
Section titled “TypeScript Support”Type definitions available for TypeScript projects:
// Import typesimport type { OrderData, ItemData } from 'next-campaign-cart';
// Typed parametersconst orderData: OrderData = { id: 'ORDER_123', total: 159.99, currency: 'USD'};
next.trackPurchase(orderData);Related Documentation
Section titled “Related Documentation”- Configuration & Modes - Configure tracking modes and providers
- Event Reference - Complete event schemas and examples
- Custom Events - Advanced tracking patterns with EventBuilder
- Debugging Guide - Troubleshooting and testing