JavaScript API Methods
The Next Commerce JS SDK exposes methods through the window.next object after initialization.
Getting Started
Section titled “Getting Started”Initialization Detection
Section titled “Initialization Detection”// Check if SDK is readyif (window.next) { // SDK is ready, use it directly next.addItem({ packageId: 123 });} else { // Queue for later execution window.nextReady = window.nextReady || []; window.nextReady.push(function() { next.addItem({ packageId: 123 }); });}
// Or listen for initialization eventdocument.addEventListener('next:initialized', function(event) { console.log('SDK initialized at', new Date(event.detail.timestamp)); next.addItem({ packageId: 123 });});Cart Methods
Section titled “Cart Methods”addItem
Section titled “addItem”Adds an item to the cart. Requires an options object, not a direct package ID.
// ✅ CORRECT - Pass an object with packageId propertyawait next.addItem({ packageId: 123, quantity: 2});
// ✅ CORRECT - Quantity is optional (defaults to 1)await next.addItem({ packageId: 123 });
// ❌ WRONG - Don't pass packageId directly// next.addItem(123); // This won't work!Parameters:
options(object): Required options objectoptions.packageId(number): Package ID to addoptions.quantity(number, optional): Quantity to add (default: 1)
Returns: Promise<void>
removeItem
Section titled “removeItem”Removes an item from the cart. Requires an options object.
// ✅ CORRECTawait next.removeItem({ packageId: 123 });
// ❌ WRONG// next.removeItem(123); // This won't work!Parameters:
options(object): Required options objectoptions.packageId(number): Package ID to remove
Returns: Promise<void>
updateQuantity
Section titled “updateQuantity”Updates the quantity of an item in the cart. Requires an options object.
// ✅ CORRECTawait next.updateQuantity({ packageId: 123, quantity: 5});
// ❌ WRONG// next.updateQuantity(123, 5); // This won't work!Parameters:
options(object): Required options objectoptions.packageId(number): Package ID to updateoptions.quantity(number): New quantity
Returns: Promise<void>
clearCart
Section titled “clearCart”Removes all items from the cart.
await next.clearCart();Returns: Promise<void>
hasItemInCart
Section titled “hasItemInCart”Checks if an item is in the cart. Requires an options object.
// ✅ CORRECTconst hasItem = next.hasItemInCart({ packageId: 123 });console.log('Item in cart:', hasItem); // true or false
// ❌ WRONG// next.hasItemInCart(123); // This won't work!Parameters:
options(object): Required options objectoptions.packageId(number): Package ID to check
Returns: boolean
getCartData
Section titled “getCartData”Returns comprehensive cart data including enriched items, totals, campaign data, and applied coupons.
const cartData = next.getCartData();console.log(cartData);// {// cartLines: [...],// cartTotals: { subtotal: {...}, total: {...}, ... },// campaignData: {...},// appliedCoupons: [...]// }Returns:
{ cartLines: EnrichedCartLine[]; cartTotals: CartTotals; campaignData: Campaign | null; appliedCoupons: AppliedCoupon[];}getCartTotals
Section titled “getCartTotals”Returns cart totals and pricing information.
const totals = next.getCartTotals();console.log('Total:', totals.total.formatted); // "$99.99"console.log('Subtotal:', totals.subtotal.formatted); // "$89.99"console.log('Shipping:', totals.shipping.formatted); // "$10.00"Returns: CartTotals object with subtotal, shipping, tax, discounts, and total
getCartCount
Section titled “getCartCount”Returns the total number of items in the cart.
const count = next.getCartCount();console.log('Items in cart:', count); // 3Returns: number
Campaign & Package Methods
Section titled “Campaign & Package Methods”getCampaignData
Section titled “getCampaignData”Returns the loaded campaign data.
const campaign = next.getCampaignData();if (campaign) { console.log('Campaign:', campaign.name); console.log('Currency:', campaign.currency); console.log('Packages:', campaign.packages);}Returns: Campaign | null
getPackage
Section titled “getPackage”Gets detailed information about a specific package.
const package = next.getPackage(123);if (package) { console.log('Package name:', package.display_name); console.log('Price:', next.formatPrice(package.price));}Parameters:
id(number): Package ID
Returns: Package | null
Profile Methods
Section titled “Profile Methods”Profile methods enable dynamic package ID mapping for different pricing tiers, promotions, and customer segments.
setProfile
Section titled “setProfile”Applies a pricing profile to swap package IDs.
// Basic usageawait next.setProfile('black_friday');
// With optionsawait next.setProfile('vip', { clearCart: true, preserveQuantities: false});revertProfile
Section titled “revertProfile”Reverts to original packages.
await next.revertProfile();getActiveProfile
Section titled “getActiveProfile”Gets the currently active profile ID.
const profile = next.getActiveProfile();console.log(profile); // "black_friday" or nullgetMappedPackageId
Section titled “getMappedPackageId”Gets the mapped package ID for the active profile.
const mappedId = next.getMappedPackageId(1);console.log(mappedId); // 101 (if profile maps 1 -> 101)listProfiles
Section titled “listProfiles”Lists all configured profiles.
const profiles = next.listProfiles();console.log(profiles); // ["regular", "black_friday", "vip"]Coupon Methods
Section titled “Coupon Methods”applyCoupon
Section titled “applyCoupon”Applies a coupon code to the cart.
const result = await next.applyCoupon('SAVE20');if (result.success) { console.log('Coupon applied:', result.message); console.log('Discount amount:', result.data.amount);} else { console.error('Coupon error:', result.message);}Parameters:
code(string): Coupon code to apply
Returns:
Promise<{ success: boolean; message: string; data?: { amount: number; formatted: string; }}>removeCoupon
Section titled “removeCoupon”Removes a coupon from the cart.
next.removeCoupon('SAVE20');Parameters:
code(string): Coupon code to remove
Returns: void
getCoupons
Section titled “getCoupons”Returns all applied coupons.
const coupons = next.getCoupons();coupons.forEach(coupon => { console.log(`${coupon.code}: ${coupon.amount.formatted} off`);});Returns: AppliedCoupon[]
validateCoupon
Section titled “validateCoupon”Validates a coupon without applying it.
const validation = next.validateCoupon('TESTCODE');if (validation.valid) { console.log('Coupon is valid');} else { console.log('Invalid:', validation.message);}Parameters:
code(string): Coupon code to validate
Returns:
{ valid: boolean; message?: string;}Tracking & Analytics Methods
Section titled “Tracking & Analytics Methods”trackViewItemList
Section titled “trackViewItemList”Tracks when users view a list of products.
// Basic trackingawait next.trackViewItemList(['1', '2', '3']);
// With list contextawait next.trackViewItemList( ['1', '2', '3'], 'homepage', 'Featured Products');Parameters:
packageIds(Array<string|number>): Array of package IDslistId(string, optional): Unique list identifierlistName(string, optional): Human-readable list name
Returns: Promise<void>
trackViewItem
Section titled “trackViewItem”Tracks when a single item is viewed.
await next.trackViewItem('1');Parameters:
packageId(string|number): Package ID viewed
Returns: Promise<void>
trackAddToCart
Section titled “trackAddToCart”Tracks when an item is added to cart.
await next.trackAddToCart('1', 2);Parameters:
packageId(string|number): Package ID addedquantity(number, optional): Quantity added (default: 1)
Returns: Promise<void>
trackRemoveFromCart
Section titled “trackRemoveFromCart”Tracks when an item is removed from cart.
await next.trackRemoveFromCart('1', 1);Parameters:
packageId(string|number): Package ID removedquantity(number, optional): Quantity removed (default: 1)
Returns: Promise<void>
trackBeginCheckout
Section titled “trackBeginCheckout”Tracks when checkout process begins.
await next.trackBeginCheckout();Returns: Promise<void>
trackPurchase
Section titled “trackPurchase”Tracks completed purchases.
// Track with order dataawait next.trackPurchase(orderData);Parameters:
orderData(any): Order data object
Returns: Promise<void>
trackCustomEvent
Section titled “trackCustomEvent”Tracks custom events with optional data.
// Simple custom eventawait next.trackCustomEvent('video_played');
// Custom event with dataawait next.trackCustomEvent('user_engagement', { section: 'hero', action: 'video_play', duration: 30});Parameters:
eventName(string): Custom event namedata(Record<string, any>, optional): Additional event data
Returns: Promise<void>
Shipping Methods
Section titled “Shipping Methods”getShippingMethods
Section titled “getShippingMethods”Returns all available shipping methods from the campaign.
const methods = next.getShippingMethods();console.log(methods);// [// {ref_id: 1, code: "standard", price: "0.00"},// {ref_id: 2, code: "express", price: "12.99"}// ]Returns: Array<{ref_id: number; code: string; price: string}>
getSelectedShippingMethod
Section titled “getSelectedShippingMethod”Returns the currently selected shipping method.
const selected = next.getSelectedShippingMethod();if (selected) { console.log('Shipping:', selected.name, selected.price);}Returns: {id: number; name: string; price: number; code: string} | null
setShippingMethod
Section titled “setShippingMethod”Sets the shipping method by ID.
// Set standard shipping (ID 1)await next.setShippingMethod(1);
// Set express shipping (ID 2)await next.setShippingMethod(2);Parameters:
methodId(number): The ref_id of the shipping method from campaign data
Returns: Promise<void>
Throws: Error if shipping method ID is not found in campaign data
Upsell Methods
Section titled “Upsell Methods”addUpsell
Section titled “addUpsell”Adds upsell items to a completed order. Only available after order completion.
// Add single upsellconst result = await next.addUpsell({ packageId: 123, quantity: 1});
// Add multiple upsells at onceconst result = await next.addUpsell({ items: [ { packageId: 123, quantity: 1 }, { packageId: 456, quantity: 2 } ]});
console.log('Upsells added:', result.addedLines);console.log('Total upsell value:', result.totalValue);Parameters:
options.packageId(number, optional): Single package ID to addoptions.quantity(number, optional): Quantity for single item (default: 1)options.items(Array, optional): Multiple items to additems[].packageId(number): Package IDitems[].quantity(number, optional): Quantity (default: 1)
Returns:
Promise<{ order: Order; addedLines: OrderLine[]; totalValue: number;}>Throws: Error if no order exists or order doesn’t support upsells
canAddUpsells
Section titled “canAddUpsells”Checks if upsells can be added to the current order.
if (next.canAddUpsells()) { console.log('Order supports upsells');}Returns: boolean
Behavioral Methods
Section titled “Behavioral Methods”Starts FOMO (Fear of Missing Out) popup notifications showing recent purchases.
// Start with default configurationawait next.fomo();
// Start with custom configurationawait next.fomo({ items: [ { text: "Premium Package", image: "/images/product1.jpg" }, { text: "Starter Bundle", image: "/images/product2.jpg" } ], customers: { US: ["John", "Sarah", "Mike", "Emma"], GB: ["James", "Sophie", "Oliver", "Lily"] }, maxMobileShows: 2, displayDuration: 5000, delayBetween: 12000, initialDelay: 3000});Parameters:
config(object, optional):items(Array): Custom product items to showcustomers(object): Customer names by country codemaxMobileShows(number): Max popups on mobile (default: 2)displayDuration(number): How long to show each popup in ms (default: 5000)delayBetween(number): Delay between popups in ms (default: 12000)initialDelay(number): Initial delay before first popup in ms (default: 3000)
Returns: Promise<void>
stopFomo
Section titled “stopFomo”Stops FOMO popup notifications.
next.stopFomo();Returns: void
exitIntent
Section titled “exitIntent”Shows exit intent popup when user tries to leave the page.
await next.exitIntent({ image: 'https://example.com/special-offer.jpg', action: async () => { // Apply discount when popup is clicked await next.applyCoupon('EXIT20'); // Close the popup }});Parameters:
options.image(string): URL of the image to displayoptions.action(function, optional): Function to call when popup is clicked
Returns: Promise<void>
disableExitIntent
Section titled “disableExitIntent”Disables the exit intent popup.
next.disableExitIntent();Returns: void
Event Methods
Section titled “Event Methods”Subscribe to internal SDK events.
// Listen for cart updatesnext.on('cart:updated', (cartState) => { console.log('Cart updated:', cartState.items.length, 'items');});
// Listen for item additionsnext.on('cart:item-added', (data) => { console.log('Item added:', data.packageId);});Parameters:
event(string): Event name from EventMaphandler(function): Event handler function
Returns: void
Unsubscribe from internal SDK events.
const handler = (data) => console.log(data);next.on('cart:updated', handler);// Later...next.off('cart:updated', handler);Parameters:
event(string): Event namehandler(function): Handler function to remove
Returns: void
Available Events
Section titled “Available Events”// Cart eventsnext.on('cart:updated', (cartState) => { /* ... */ });next.on('cart:item-added', (data) => { /* ... */ });next.on('cart:item-removed', (data) => { /* ... */ });next.on('cart:quantity-changed', (data) => { /* ... */ });
// Campaign eventsnext.on('campaign:loaded', (campaign) => { /* ... */ });
// Checkout eventsnext.on('checkout:started', (data) => { /* ... */ });next.on('checkout:form-initialized', () => { /* ... */ });
// Order eventsnext.on('order:completed', (order) => { /* ... */ });
// Payment eventsnext.on('payment:tokenized', (data) => { /* ... */ });next.on('payment:error', (error) => { /* ... */ });
// Coupon eventsnext.on('coupon:applied', (coupon) => { /* ... */ });next.on('coupon:removed', (code) => { /* ... */ });
// Upsell eventsnext.on('upsell:added', (data) => { /* ... */ });next.on('upsell:skipped', (data) => { /* ... */ });next.on('upsell:viewed', (data) => { /* ... */ });next.on('upsell:accepted', (data) => { /* ... */ });
// Other eventsnext.on('error:occurred', (error) => { /* ... */ });next.on('config:updated', (config) => { /* ... */ });next.on('fomo:shown', (data) => { /* ... */ });next.on('route:changed', (route) => { /* ... */ });Utility Methods
Section titled “Utility Methods”formatPrice
Section titled “formatPrice”Formats a price value according to campaign currency.
const formatted = next.formatPrice(19.99); // "$19.99"const euros = next.formatPrice(19.99, 'EUR'); // "€19.99"Parameters:
amount(number): Price amount to formatcurrency(string, optional): Currency code (uses campaign currency if not provided)
Returns: string
validateCheckout
Section titled “validateCheckout”Validates if the cart is ready for checkout.
const validation = next.validateCheckout();if (!validation.valid) { console.error('Cannot checkout:', validation.errors);}Returns:
{ valid: boolean; errors?: string[];}registerCallback
Section titled “registerCallback”Register a callback for specific SDK operations (legacy compatibility).
next.registerCallback('itemAdded', (data) => { console.log('Item added:', data); // data includes: cartLines, cartTotals, campaignData, appliedCoupons});Parameters:
type(CallbackType): Type of callback. Available types:'beforeRender'- Before cart UI renders'afterRender'- After cart UI renders'beforeCheckout'- Before checkout starts'afterCheckout'- After checkout completes'beforeRedirect'- Before order redirect'itemAdded'- After item added to cart'itemRemoved'- After item removed from cart'cartCleared'- After cart cleared
callback(function): Callback function that receivesCallbackData
Returns: void
Debug API
Section titled “Debug API”The debug API provides powerful utilities for development and troubleshooting. Available only when debug mode is enabled with ?debugger=true.
Accessing Debug Mode
Section titled “Accessing Debug Mode”// Check if debug mode is availableif (window.nextDebug) { console.log('Debug mode available');}Store Access
Section titled “Store Access”Direct access to all internal stores:
// Cart storeconst cartState = nextDebug.stores.cart.getState();console.log('Cart items:', cartState.items);
// Campaign storeconst campaignState = nextDebug.stores.campaign.getState();console.log('Campaign data:', campaignState.data);
// Config storeconst configState = nextDebug.stores.config.getState();console.log('API key:', configState.apiKey);
// Checkout storeconst checkoutState = nextDebug.stores.checkout.getState();
// Order storeconst orderState = nextDebug.stores.order.getState();
// Attribution storeconst attributionState = nextDebug.stores.attribution.getState();Cart Debug Methods
Section titled “Cart Debug Methods”// Quick cart operationsnextDebug.addToCart(123); // Add single itemnextDebug.addToCart(123, 3); // Add with quantitynextDebug.removeFromCart(123); // Remove itemnextDebug.updateQuantity(123, 5); // Update quantity
// Add test items (packages 2, 7, 9)nextDebug.addTestItems();Error Handling
Section titled “Error Handling”Standard Error Handling
Section titled “Standard Error Handling”try { await next.addItem({ packageId: 123, quantity: 2 }); console.log('Item added successfully');} catch (error) { console.error('Failed to add item:', error.message);}Async Method Handling
Section titled “Async Method Handling”// Most cart/coupon methods are asyncconst result = await next.applyCoupon('INVALID_CODE');if (!result.success) { console.error('Coupon error:', result.message); // Show user-friendly message}Event Error Handling
Section titled “Event Error Handling”next.on('error:occurred', (error) => { console.error('SDK error:', error); // Handle errors gracefully});Best Practices
Section titled “Best Practices”- Always wait for SDK initialization before calling methods
- Use async/await for cleaner code with promises
- Handle errors appropriately - check success flags and catch exceptions
- Subscribe to events for reactive UI updates
- Use debug mode during development for troubleshooting
- Batch operations when possible for better performance
- Validate inputs before calling methods
- Clean up event listeners when no longer needed
Common Patterns
Section titled “Common Patterns”E-commerce Flow
Section titled “E-commerce Flow”window.nextReady.push(async function() { // 1. Track product list view await next.trackViewItemList(['1', '2', '3'], 'category', 'Best Sellers');
// 2. Add item to cart await next.addItem({ packageId: 1, quantity: 2 });
// 3. Apply coupon const couponResult = await next.applyCoupon('SAVE20'); if (couponResult.success) { console.log('Discount applied'); }
// 4. Track checkout start await next.trackBeginCheckout();});Reactive Cart Updates
Section titled “Reactive Cart Updates”// Update UI when cart changesnext.on('cart:updated', (cartState) => { document.querySelector('.cart-count').textContent = next.getCartCount(); document.querySelector('.cart-total').textContent = cartState.totals.total.formatted;});
// React to specific actionsnext.on('cart:item-added', (data) => { showNotification(`${data.packageName} added to cart`);});Related Documentation
Section titled “Related Documentation”- Events - Event system reference
- Callbacks - Legacy callback patterns
- Cart Methods - Detailed cart operations
- Analytics - Tracking and analytics