NextCommerce

Source: next-commerce.ts:67

The programmatic SDK facade — the scriptable counterpart to the data-next-* attributes. A single instance is created during initialization and exposed as window.next, so most code obtains it directly rather than constructing one.

Use it to read cart/campaign state, drive the cart (NextCommerce.cart), subscribe to events, and fire analytics — all without touching the DOM layer.

This class is a thin orchestrator: the constructor and singleton accessor live here, and every other method delegates to a same-named function extracted verbatim into a sibling module grouped by @category (next-commerce.cart.ts, next-commerce.analytics.ts, …). Splitting this way keeps the class — and the published window.next member list — exactly where it was; only the implementation moved.

Example

CODE
const sdk = window.next; // created by the SDK on load

// React to cart changes
sdk.on('cart:updated', cart => render(cart.total));

// Drive the cart from code
await sdk.cart.addItem({ packageId: 2, quantity: 1, isUpsell: false });

// Read current state
const { total } = sdk.getCartTotals();

Constructors

new NextCommerce(): NextCommerce

Returns

NextCommerce


Accessors

get cart(): CartOperations

The programmatic cart API — the blessed way to drive the cart in code. Backed by the cart operations layer (@/state/cart/operations).

Methods

hasItemInCart(options: { packageId?: number }): boolean

Whether a package is currently in the cart.

Parameters

  • options ({ packageId?: number })

Properties

  • packageId (number, optional)

Returns

  • boolean

addItem( options: { packageId?: number; quantity?: number }, ): Promise<void>

Adds a package to the cart (quantity defaults to 1). No-op if packageId is omitted. For upsell adds use NextCommerce.cart.

Parameters

  • options ({ packageId?: number; quantity?: number })

Properties

  • packageId (number, optional)
  • quantity (number, optional)

Returns

  • Promise<void>

removeItem(options: { packageId?: number }): Promise<void>

Removes a package from the cart entirely. No-op if packageId is omitted.

Parameters

  • options ({ packageId?: number })

Properties

  • packageId (number, optional)

Returns

  • Promise<void>

updateQuantity( options: { packageId?: number; quantity: number }, ): Promise<void>

Sets the exact quantity for a package (a quantity of 0 removes it).

Parameters

  • options ({ packageId?: number; quantity: number })

Properties

  • packageId (number, optional)
  • quantity (number)

Returns

  • Promise<void>

clearCart(): Promise<void>

Empties the cart.

Returns

  • Promise<void>

swapCart( items: { packageId: number; quantity: number }[], ): Promise<void>

Replaces the entire cart contents with the given items in one atomic swap (used by bundle/package selectors). Existing items not listed are removed.

Parameters

  • items ({ packageId: number; quantity: number }[])

Returns

  • Promise<void>

getCartData(): CallbackData

A snapshot of the full cart for callbacks — enriched line items, totals, campaign data, and applied vouchers.

Returns

getCartTotals( ): { subtotal: Decimal; total: Decimal; hasDiscounts: boolean; totalDiscount: Decimal; totalDiscountPercentage: Decimal; shippingMethod: ShippingMethod | undefined }

The current cart totals (subtotal, total, discounts, shipping) as Decimals.

Properties

  • subtotal (Decimal)
  • total (Decimal)
  • hasDiscounts (boolean)
  • totalDiscount (Decimal)
  • totalDiscountPercentage (Decimal)
  • shippingMethod (ShippingMethod | undefined)

Returns

  • { subtotal: Decimal; total: Decimal; hasDiscounts: boolean; totalDiscount: Decimal; totalDiscountPercentage: Decimal; shippingMethod: ShippingMethod | undefined }

getCartCount(): number

Total number of units in the cart (sum of item quantities).

Returns

  • number

getCampaignData(): Campaign | null

The loaded campaign (packages, currency, shipping methods), or null if it hasn't loaded yet.

Returns

getPackage(id: number): any

Looks up a package by its ref_id in the loaded campaign.

Parameters

  • id (number)

Returns

  • any

getVariantsByProductId(productId: number): any

All variant packages for a product id (variant selection support).

Parameters

  • productId (number)

Returns

  • any

getAvailableVariantAttributes( productId: number, attributeCode: string, ): string[]

The distinct values available for one variant attribute (e.g. all sizes) of a product — used to build variant pickers.

Parameters

  • productId (number)
  • attributeCode (string)

Returns

  • string[]

getPackageByVariantSelection( productId: number, selectedAttributes: Record<string, string>, ): any

Resolves the concrete package for a product given a full set of selected variant attributes (e.g. { color: 'red', size: 'L' }).

Parameters

  • productId (number)
  • selectedAttributes (Record<string, string>)

Returns

  • any

createVariantKey(attributes: Record<string, string>): string

Builds a stable, order-independent key from a set of variant attributes (e.g. color:red|size:L) for use as a lookup/map key.

Parameters

  • attributes (Record<string, string>)

Returns

  • string

on< K extends keyof EventMap, >( event: K, handler: (data: EventMap[K]) => void, ): void

Subscribes to an SDK event. Names and payloads are typed via EventMap.

Type Parameters

  • K extends keyof EventMap

Parameters

  • event (K)
  • handler ((data: EventMap[K]) => void)

Returns

  • void

off<K extends keyof EventMap>(event: K, handler: Function): void

Unsubscribes a handler previously registered with NextCommerce.on.

Type Parameters

  • K extends keyof EventMap

Parameters

  • event (K)
  • handler (Function)

Returns

  • void

registerCallback( type: CallbackType, callback: (data: CallbackData) => void, ): void

Registers a callback for a lifecycle callback type (e.g. cart/order hooks). Prefer NextCommerce.on for event-style subscriptions.

Parameters

Returns

  • void

unregisterCallback(type: CallbackType, callback: Function): void

Removes a callback registered with NextCommerce.registerCallback.

Parameters

Returns

  • void

triggerCallback(type: CallbackType, data: CallbackData): void

Invokes all callbacks registered for a type (errors are caught and logged).

Parameters

Returns

  • void

trackViewItemList( packageIds: (string | number)[], _listId?: string, listName?: string, ): Promise<void>

Reports a list of packages as viewed — a product grid or recommendation rail. _listId is accepted and ignored; the list name is the third argument.

Parameters

  • packageIds ((string | number)[])
  • _listId (string, optional)
  • listName (string, optional)

Returns

  • Promise<void>

trackViewItem(packageId: string | number): Promise<void>

Reports one package as viewed. Warns and sends nothing when the package is not in the loaded campaign, so an early call is silently dropped.

Parameters

  • packageId (string | number)

Returns

  • Promise<void>

trackAddToCart( packageId: string | number, quantity?: number, ): Promise<void>

Reports an add-to-cart that happened outside the SDK's own cart calls. Pairing it with NextCommerce.addItem reports the add twice.

Parameters

  • packageId (string | number)
  • quantity (number, optional)

Returns

  • Promise<void>

trackRemoveFromCart( packageId: string | number, quantity?: number, ): Promise<void>

Reports a removal that happened outside the SDK's own cart calls. Pairing it with NextCommerce.removeItem reports the removal twice.

Parameters

  • packageId (string | number)
  • quantity (number, optional)

Returns

  • Promise<void>

trackBeginCheckout(): Promise<void>

Reports checkout starting, from the current cart. The built-in checkout form already fires this — call it only for a hand-built flow.

Returns

  • Promise<void>

trackPurchase(orderData: any): Promise<void>

Reports a completed order from an order payload. The receipt page already fires this; a second call doubles reported revenue.

Parameters

  • orderData (any)

Returns

  • Promise<void>

trackCustomEvent( eventName: string, data?: Record<string, any>, ): Promise<void>

Sends an event of the caller's own naming. Nothing validates the name or the payload, so a typo becomes a new event name.

Parameters

  • eventName (string)
  • data (Record<string, any>, optional)

Returns

  • Promise<void>

trackSignUp(email: string): Promise<void>

Reports a newsletter or account sign-up. The address goes into the event payload as customer_email in the clear — nothing hashes it — so it reaches every configured provider and the browser data layer as plain text.

Parameters

  • email (string)

Returns

  • Promise<void>

trackLogin(email: string): Promise<void>

Reports a returning visitor signing in. Carries the address in the clear, exactly as NextCommerce.trackSignUp does.

Parameters

  • email (string)

Returns

  • Promise<void>

setDebugMode(enabled: boolean): Promise<void>

Turns verbose analytics logging on or off at runtime. Unrelated to the debug overlay, which is ?debugger=true or window.nextConfig.debugger.

Parameters

  • enabled (boolean)

Returns

  • Promise<void>

invalidateAnalyticsContext(): Promise<void>

Discards the cached page context so the next event is built from the current route. Needed in a single-page app, where no page load resets it.

Returns

  • Promise<void>

addMetadata(key: string, value: any): void

Adds one key to the attribution metadata sent with the order, merging so the automatically collected fields survive.

Parameters

  • key (string)
  • value (any)

Returns

  • void

setMetadata(metadata: Record<string, any>): void

Adds several keys to the attribution metadata. Merges rather than replaces, despite the name — a true replace would wipe the automatic fields.

Parameters

  • metadata (Record<string, any>)

Returns

  • void

clearMetadata(): void

Drops caller-supplied metadata while preserving the automatic fields (landing_page, referrer, device, device_type, domain, timestamp).

Returns

  • void

getMetadata(): Record<string, any> | undefined

The attribution metadata as stored. undefined means the read failed; an empty bag is {}.

Returns

  • Record<string, any> | undefined

setAttribution(attribution: Record<string, any>): void

Overwrites the collected attribution — funnel, affiliate, utm_*. This decides who is credited for the sale, so it is a reporting change.

Parameters

  • attribution (Record<string, any>)

Returns

  • void

getAttribution(): Record<string, any> | undefined

Attribution in the shape sent to the order API, not the raw store — the right thing to log when an order is attributed wrongly.

Returns

  • Record<string, any> | undefined

debugAttribution(): void

Prints the whole attribution state to the console. Returns nothing; use NextCommerce.getAttribution when you need a value.

Returns

  • void

getShippingMethods(): ShippingMethodInfo[]

All shipping methods available in the loaded campaign.

Returns

  • ShippingMethodInfo[]

getSelectedShippingMethod(): SelectedShippingMethod | null

The currently selected shipping method, or null if none chosen yet.

Returns

  • SelectedShippingMethod | null

setShippingMethod(methodId: number): Promise<void>

Selects a shipping method by id and recalculates cart totals. Throws if the id isn't in the campaign's shipping methods.

Parameters

  • methodId (number)

Returns

  • Promise<void>

getVersion(): string

The resolved SDK version (runtime loader value if present, else build- time).

Returns

  • string

formatPrice(amount: number, currency?: string): string

Formats an amount using the campaign currency (or an override), e.g. $19.99.

Parameters

  • amount (number)
  • currency (string, optional)

Returns

  • string

validateCheckout(): { valid: boolean; errors: string[] }

Lightweight pre-checkout validation (currently: cart must not be empty).

Properties

  • valid (boolean)
  • errors (string[])

Returns

  • { valid: boolean; errors: string[] }

applyCoupon( code: string, ): Promise<{ success: boolean; message: string }>

Applies a coupon code and recalculates totals. Returns { success, message }success: false when the code is already applied or invalid.

Parameters

  • code (string)

Returns

  • Promise<{ success: boolean; message: string }>

removeCoupon(code: string): void

Removes a previously applied coupon and recalculates totals.

Parameters

  • code (string)

Returns

  • void

getCoupons(): string[]

The coupon codes currently applied to the cart.

Returns

  • string[]

exitIntent(options: ExitIntentOptions): Promise<void>

Arms the exit-intent popup, lazy-loading its enhancer on the first call. Rethrows when that import fails.

Parameters

  • options (ExitIntentOptions)

Returns

  • Promise<void>

disableExitIntent(): void

Stops the exit-intent popup from appearing again. No-op when NextCommerce.exitIntent was never called.

Returns

  • void

addUpsell(options: AddUpsellOptions): Promise<any>

Adds packages to the already-paid order, charging the saved payment method. Throws when there is no order in session, when the order cannot take upsells or is mid-processing, and when neither packageId nor items is given.

Parameters

  • options (AddUpsellOptions)

Returns

  • Promise<any>

canAddUpsells(): boolean

Whether the order in session can take a post-purchase upsell right now. Also false while one is processing, so it guards a double submit.

Returns

  • boolean

getCompletedUpsells(): string[]

Package ids already accepted on this order, as strings rather than numbers.

Returns

  • string[]

isUpsellAlreadyAdded(packageId: number): boolean

Whether a package was already accepted on this order — checks the completed list and the accepted entries of the upsell journey, so it survives a reload.

Parameters

  • packageId (number)

Returns

  • boolean

setParam(key: string, value: string): void

Sets one captured URL parameter for the rest of the session. Does not touch the address bar.

Parameters

  • key (string)
  • value (string)

Returns

  • void

setParams(params: Record<string, string>): void

Sets several captured URL parameters, replacing the keys named and leaving the rest alone.

Parameters

  • params (Record<string, string>)

Returns

  • void

getParam(key: string): string | null

Reads one captured URL parameter. null when it was never captured.

Parameters

  • key (string)

Returns

  • string | null

getAllParams(): Record<string, string>

Every URL parameter captured for this session.

Returns

  • Record<string, string>

hasParam(key: string): boolean

Whether a parameter was captured, including one present with an empty value.

Parameters

  • key (string)

Returns

  • boolean

clearParam(key: string): void

Forgets one captured URL parameter.

Parameters

  • key (string)

Returns

  • void

clearAllParams(): void

Forgets every captured URL parameter — utm_* values included, which attribution reads.

Returns

  • void

mergeParams(params: Record<string, string>): void

Adds parameters to the captured set without disturbing keys it does not name.

Parameters

  • params (Record<string, string>)

Returns

  • void

Static Methods

getInstance(): NextCommerce

Returns the shared SDK instance, creating it on first call.

Returns

  • NextCommerce — The singleton NextCommerce (the same object exposed as window.next).