Skip to content

Checkout JavaScript events

Listen for Kustom Checkout and confirmation widget JavaScript events, including upsell payloads, and suspend the iframe during order updates.

Use Checkout JavaScript events to update your page or record analytics when the customer changes an address, shipping option or checkbox, or interacts with post-purchase upsell in the confirmation widget. Use suspend and resume to pause the iframe while updating an order. These events support presentation; use the Checkout API as the source of truth for order processing.

For checkout funnel events pushed to your page’s dataLayer, see Analytics events in the dataLayer.

After the iframe renders, the script in html_snippet installs a global accessor. Pass it a function to receive the checkout API object. Render and update documents that accessor and its current name. Every example below assumes you already hold the resulting api object.

Register listeners with api.on(), passing an object whose keys are event names:

api.on({
load: function (data) {
// data is the payload documented below
},
order_total_change: function (data) {
updateMerchantPanelTotal(data.order_total);
},
});

Suspending and resuming around an order update

Section titled “Suspending and resuming around an order update”

When your page changes the cart, call suspend to lock the iframe, then update the order through the Checkout API. Call resume to unlock the iframe and refresh it from the updated order.

api.suspend();
// POST the update to the order location URI, then:
api.resume();

The iframe resumes automatically after 10 seconds. If your update can take longer, disable automatic resume and call resume on every code path:

api.suspend({ autoResume: { enabled: false } });

Between suspend and resume, update the order with a POST to the order location URI you already hold. Don’t create a new order for a cart change: the iframe still uses the original order id.

EventFires whenPayload
loadThe checkout iframe has renderedCustomer type and the address fields known so far
user_interactedThe customer’s first mouse, keyboard or express-button interaction; once per checkout loadtype — mousedown or keydown, or click when the first touch is an express checkout button
customerThe checkout detects or changes customer typetype — person or organization
changeBilling details change — postal code, country, emailThe changed fields. In AT and DE, narrowed to country, postal_code and city
billing_address_changeA valid billing address is detectedpostal_code, country
shipping_address_changeA valid shipping address is detectedpostal_code, country
shipping_option_changeThe customer selects a shipping optionThe full option — price and tax_amount in minor units, tax_rate a percentage
shipping_address_update_errorUpdating shipping failedEmpty object
order_total_changeThe order total changesorder_total in minor units
checkbox_changeA checkbox is ticked or untickedkey, checked
can_not_complete_orderThe customer needs an alternative payment option, for example after a declined credit checkEmpty object
network_errorThe iframe detects a network problemEmpty object
redirect_initiatedThe customer is about to be redirected to your confirmation pagetrue
validation_callbackThe customer clicked Pay order, before the server requestEmpty object, plus a callback

Use load to initialize your panel with the checkout’s known data. shipping_address.country is an alpha-3 code.

{
"customer": { "type": "person" },
"shipping_address": { "country": "swe", "postal_code": "16972" }
}

change carries whichever billing fields the customer has supplied. Values may be prefilled or obfuscated, and the object is often partial.

{
"email": "shopper@example.com",
"postal_code": "12345",
"country": "deu"
}

shipping_option_change carries the whole option. price and tax_amount are in minor units; tax_rate is a percentage with two implicit decimals, so 2500 is 25%.

{
"id": "express",
"name": "Express delivery",
"description": "Delivered the next working day",
"promo": "Free over 500 SEK",
"price": 9900,
"tax_amount": 1980,
"tax_rate": 2500
}

checkbox_change identifies the checkbox by the id you gave it in options.additional_checkboxes. The older single-checkbox option has no id of its own, so it reports the fixed key additional_checkbox_from_merchant:

{
"key": "additional_checkbox_from_merchant",
"checked": true
}

Running client-side validation before the purchase

Section titled “Running client-side validation before the purchase”

validation_callback fires when the customer clicks Pay order, before Kustom makes any server request. It’s the only event with a second argument, and you have 10 seconds to call that callback with a should_proceed value.

Client-side validation fails open. If the handler doesn’t answer within 10 seconds, Kustom proceeds with the purchase. This includes handlers that throw or wait on a slow service. Keep the handler fast and synchronous where possible.

api.on({
validation_callback: function (data, callback) {
callback({
should_proceed: false,
message: 'Sorry, we cannot ship to that address.',
});
},
});

data is always an empty object. Enable the event by setting options.require_client_validation to true when you create the order.

Browser validation can be bypassed. Enforce stock, prices and delivery restrictions in the order validation callback on your server.

Client-side events can drive shipping lookups and cart updates. For analytics, select fields explicitly instead of forwarding the payload. This example assumes gtag is configured and your consent controls are applied.

const forward = (eventName, parameters = {}) =>
gtag('event', `checkout_${eventName}`, parameters);
api.on({
load: () => forward('load'),
user_interacted: (data) => {
const type = data?.type;
const parameters = ['mousedown', 'keydown', 'click'].includes(type)
? { interaction_type: type }
: {};
forward('user_interacted', parameters);
},
billing_address_change: () => forward('billing_address_change'),
shipping_address_change: () => forward('shipping_address_change'),
redirect_initiated: () => forward('redirect_initiated'),
});

The example sends event names and recognized interaction types, not customer or address data. These are custom GA4 events. redirect_initiated does not confirm a purchase. Some events also fire with prefilled data; define when each should count toward your measurement.

For checkout funnel reporting through GTM, use dataLayer analytics events. Set options.analytics_enabled to true when creating an order, or enable events through merchant configuration. Follow the guide’s GA4 mapping and choose one source per measurement to avoid duplicates.

Register these listeners on the confirmation page using the same api.on() interface.

EventFires whenPayload
load_confirmationThe confirmation snippet has renderedEmpty object

The following events are emitted by the hosted confirmation widget when it runs post-purchase upsell. This includes the hosted confirmation widget used with embedded Checkout, not just hosted Checkout. The legacy confirmation page doesn’t emit these upsell events. Availability depends on the confirmation widget version and upsell configuration used by your integration; confirm support for the widget version deployed for your merchant before relying on them.

EventFires whenPayload
upsell_initializedThe upsell component first mounts, even if it renders nothingEmpty object
upsell_carousel_loadedThe carousel first renders with available products and an upsell deadline, even if that deadline has passedproductCount
upsell_dialog_openedThe customer opens a product dialogid, reference (optional), name, orderIndex
upsell_dialog_closedThe customer manually closes a product dialog, including after completionid, reference (optional), name
upsell_quantity_changedThe customer changes quantity with the dialog’s stepperid, quantity
upsell_product_addedThe request to add the upsell product to the order succeedsid, reference (optional), name, quantity
upsell_add_failedThe request to add the upsell product to the order failsid, reference (optional), name, quantity, variant_id (optional), selected_attributes (optional), errorCode (optional)
upsell_timer_expiredThe upsell deadline passes while the widget is open, even if the timer badge is hiddenEmpty object
upsell_not_availableThe mounted upsell component detects no items or no available itemsreason, productCount (optional)

Register listeners as early as possible after obtaining the API handle. Events emitted before a listener is registered are buffered, but repeated events with the same name can collapse to the latest payload. Don’t treat late registration as a complete interaction history.

The product dialog runs in a separate fullscreen frame. upsell_quantity_changed and upsell_add_failed originate there; the other upsell events originate in the main confirmation frame. Don’t rely on strict ordering between events from different frames. Payloads are JSON objects, and optional fields are omitted when they don’t apply, rather than sent as null.

upsell_initialized and upsell_carousel_loaded fire at most once per confirmation widget session, including if the upsell component remounts. Reloading the widget starts a new session. Initialization alone doesn’t mean any products were shown.

Changing variants resets quantity to 1 without emitting upsell_quantity_changed. Read the quantity from upsell_product_added or upsell_add_failed for the attempted add, not from the last quantity-change event.

upsell_dialog_closed fires for manual closes, including the close action after success or failure. Outside clicks and Escape can also close the dialog at viewport widths of 768 px or more, but not on narrower viewports. Outside clicks and Escape are ignored while an add request is in flight or its success/error result is showing.

upsell_timer_expired fires even when display_options.timer_disabled hides the timer badge. It doesn’t fire merely because the widget loads after the upsell deadline has already passed.

FieldTypeMeaning
idstringUpsell product id
referencestringProduct reference, included when non-empty
namestringProduct name
quantitynumberSelected quantity; for upsell_product_added, the quantity added by that request
orderIndexnumberZero-based product position in the displayed carousel
productCountnumberAvailable product count for upsell_carousel_loaded; total provided product count for upsell_not_available when items exist
variant_idstringSelected variant SKU, included on failure when the product has variants and a variant is selected
selected_attributesobject with string valuesSelected attribute names and values, included under the same condition as variant_id
errorCodestringError code, included on failure when available
reasonstringOne of the unavailability reasons below

upsell_product_added reports a successful add request, rather than a button click. Its payload contains id, name, quantity and, when non-empty, reference. It doesn’t include variant fields, prices or currency. Use the order API when you need the updated order details.

On failure, errorCode is included when available. Recognized codes include upsell_failed, upsell_item_not_found, upsell_not_allowed and add_failed. Other backend codes are passed through unchanged, so handle unknown values as well.

The reason values for upsell_not_available are checked in this order; the first match wins:

ReasonMeaningproductCount
no_itemsNo upsell items are present in the order data checked by the mounted componentOmitted
out_of_stockEvery provided item has stock quantity below 1Included
purchase_limit_zeroEvery provided item has a purchase limit below 1, unless all items are out of stockIncluded
all_maxed_outNo provided items are available for another reason: mixed stock/limit restrictions, cart quantity at the limit, or missing cart items dataIncluded

The upsell component only mounts when upsell items are supplied. An order with no recommendations therefore isn’t guaranteed to emit upsell_not_available with no_items. The event can fire again when the order data changes, for example after a successful add uses up the last allowed quantity. all_maxed_out doesn’t necessarily mean a customer has reached a limit: missing cart.items also makes products unavailable.

Don’t rely only on upsell_not_available to decide whether to show fallback content:

  • Without upsell items in the initial order configuration, the component doesn’t mount and no upsell events fire. no_items can occur when a mounted component’s fetched order data has no items, including when items disappear after mounting.
  • With available products but no last_upsell_time, the component emits upsell_initialized but renders nothing and emits neither upsell_carousel_loaded nor upsell_not_available.
  • If the widget loads after the deadline, it can emit upsell_initialized and upsell_carousel_loaded, but every card is disabled. No upsell_timer_expired event is emitted for that already-expired deadline.

Treat upsell_carousel_loaded as a rendering signal, not proof that the customer can buy. Neither that event alone nor the absence of upsell_timer_expired establishes purchasability. Use order data and its deadline when deciding availability, and use a bounded timeout for fallback presentation if no rendering signal arrives. Keep the order API as the source of truth for purchases.

After the confirmation snippet’s script has installed the accessor, register your handlers:

window._klarnaCheckout(function (api) {
api.on({
upsell_product_added: function (data) {
console.log('Upsell product added:', data.id, data.quantity);
// Refresh your order summary from your server.
},
upsell_add_failed: function (data) {
console.log('Upsell add failed:', data.id, data.errorCode);
},
upsell_not_available: function (data) {
console.log('Upsell unavailable:', data.reason);
},
});
});

This page is also available as Markdown — append .md to its URL — and is indexed in llms.txt.