Skip to content

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.

Best for: Quick implementations, minimal code

// Simple, clean method calls
next.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

Track when items are added to the cart.

// Track with package ID and quantity
next.trackAddToCart('123', 1);
// With quantity
next.trackAddToCart('456', 2);

Parameters:

  • packageId (string|number) - Product/package identifier
  • quantity (number, optional) - Quantity added (default: 1)

Auto-tracked when:

  • Using data-next-action="add-to-cart" attributes
  • Calling cart methods like next.addToCart()

Track when items are removed from the cart.

// Track removal
next.trackRemoveFromCart('123', 1);

Parameters:

  • packageId (string|number) - Product identifier
  • quantity (number, optional) - Quantity removed

Track product detail page views.

// Track product view
next.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

Track product list/collection views.

// Track list view
next.trackViewItemList(
['123', '456', '789'],
'summer-sale',
'Summer Sale Collection'
);

Parameters:

  • packageIds (array) - Array of product IDs
  • listId (string) - List identifier
  • listName (string) - List display name

Auto-tracked when:

  • URL matches collection/category patterns
  • Page type detected as product list

Track when checkout process starts.

// Track checkout start
next.trackBeginCheckout();

No parameters required - automatically includes cart items

Auto-tracked when:

  • Checkout page loads (in auto mode)

Track completed orders.

// Minimal purchase tracking
next.trackPurchase({
id: 'ORDER_123',
total: 159.99,
currency: 'USD',
tax: 9.99,
shipping: 10.00
});
// With items
next.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 ID
    • total (number) - Required - Order total
    • currency (string) - Currency code (default: ‘USD’)
    • tax (number, optional) - Tax amount
    • shipping (number, optional) - Shipping cost
    • items (array, optional) - Order line items

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 data
next.trackPurchase({
id: 'ORDER_123',
total: 159.99,
currency: 'USD'
});

Track user registration.

// Track registration
next.trackSignUp('[email protected]');

Parameters:

  • email (string) - User email address

Track user login.

// Track login
next.trackLogin('[email protected]');

Parameters:

  • email (string) - User email address

Track custom business events.

// Only available via advanced API
window.NextAnalytics.track({
event: 'newsletter_subscribe',
list_name: 'Weekly Newsletter',
source: 'footer_form'
});
// Video engagement
window.NextAnalytics.track({
event: 'video_played',
video_id: 'intro-demo',
video_title: 'Product Introduction',
duration: 120
});
// Feature usage
window.NextAnalytics.track({
event: 'feature_used',
feature_name: 'product_comparison',
items_compared: 3
});

Parameters:

  • eventData (object) - Custom event object
    • event (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.


Enable or disable debug logging.

// Enable debug mode
window.NextAnalytics.setDebugMode(true);
// Disable
window.NextAnalytics.setDebugMode(false);

Parameters:

  • enabled (boolean) - Enable/disable debug logs

Debug output includes:

  • Event names and data
  • Provider dispatch confirmations
  • Validation warnings
  • Error messages

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'
}

MethodParametersDescriptionAuto-Tracked
trackViewItem()packageIdProduct detail viewYes*
trackAddToCart()packageId, quantity?Add item to cartYes*
trackRemoveFromCart()packageId, quantity?Remove from cartYes*
trackViewItemList()packageIds[], listId, listNameProduct list viewYes*
trackBeginCheckout()-Checkout initiationYes*
trackPurchase()orderDataOrder completionYes*
trackSignUp()emailUser registrationNo
trackLogin()emailUser loginNo

*Auto-tracked only in auto mode

MethodParametersDescription
trackAddToCart()item, listId?, listName?Add to cart with list attribution
trackRemoveFromCart()itemRemove from cart
trackViewItem()itemProduct detail view
trackViewItemList()items[], listId, listNameProduct list view
trackBeginCheckout()-Checkout initiation
trackPurchase()orderDataOrder completion
trackSignUp()emailUser registration
trackLogin()emailUser login
track()eventDataCustom event
setDebugMode()enabledEnable/disable debug logs
getStatus()-Get analytics status

window.addEventListener('DOMContentLoaded', () => {
// Product page
if (productData) {
next.trackViewItem(productData.id);
}
// Order confirmation
if (orderData) {
next.trackPurchase(orderData);
}
});

Use the nextReady queue:

window.nextReady = window.nextReady || [];
window.nextReady.push(function() {
next.trackAddToCart('123', 1);
next.trackBeginCheckout();
});
// Button click
document.getElementById('subscribe-btn').addEventListener('click', () => {
window.NextAnalytics.track({
event: 'newsletter_subscribe',
source: 'hero_section'
});
});
// Form submission
form.addEventListener('submit', (e) => {
window.NextAnalytics.track({
event: 'form_submitted',
form_id: 'contact'
});
});
// Set list attribution when viewing a collection
window.NextAnalytics.trackViewItemList(
items,
'summer-sale-2025',
'Summer Sale Collection'
);
// Attribution automatically included when user adds to cart
next.trackAddToCart('123', 1);
// Event includes: item_list_id: 'summer-sale-2025', item_list_name: 'Summer Sale Collection'

The SDK handles analytics errors gracefully:

// Analytics errors never break your app
try {
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

Type definitions available for TypeScript projects:

// Import types
import type { OrderData, ItemData } from 'next-campaign-cart';
// Typed parameters
const orderData: OrderData = {
id: 'ORDER_123',
total: 159.99,
currency: 'USD'
};
next.trackPurchase(orderData);