# 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](/checkout/analytics-events/).

## Getting the checkout API handle

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](/checkout/integrate/render-checkout-snippet/) 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:

```js
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

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.

```js
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:

```js
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.

## The event catalogue

### Checkout events

| Event | Fires when | Payload |
| --- | --- | --- |
| `load` | The checkout iframe has rendered | Customer type and the address fields known so far |
| `user_interacted` | The customer's first mouse, keyboard or express-button interaction; once per checkout load | `type` — `mousedown` or `keydown`, or `click` when the first touch is an express checkout button |
| `customer` | The checkout detects or changes customer type | `type` — `person` or `organization` |
| `change` | Billing details change — postal code, country, email | The changed fields. In AT and DE, narrowed to `country`, `postal_code` and `city` |
| `billing_address_change` | A valid billing address is detected | `postal_code`, `country` |
| `shipping_address_change` | A valid shipping address is detected | `postal_code`, `country` |
| `shipping_option_change` | The customer selects a shipping option | The full option — `price` and `tax_amount` in minor units, `tax_rate` a percentage |
| `shipping_address_update_error` | Updating shipping failed | Empty object |
| `order_total_change` | The order total changes | `order_total` in minor units |
| `checkbox_change` | A checkbox is ticked or unticked | `key`, `checked` |
| `can_not_complete_order` | The customer needs an alternative payment option, for example after a declined credit check | Empty object |
| `network_error` | The iframe detects a network problem | Empty object |
| `redirect_initiated` | The customer is about to be redirected to your confirmation page | `true` |
| `validation_callback` | The customer clicked **Pay order**, before the server request | Empty object, plus a callback |

### Payload shapes

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

```json
{
  "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.

```json
{
  "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%.

```json
{
  "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`:

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

## 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.

```js
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](/checkout/integrate/validation-callback/) on your server.

## Forwarding events to an analytics tool

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.

```js
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](/checkout/analytics-events/). Set `options.analytics_enabled`
to `true` when creating an order, or enable events through merchant configuration.
Follow the guide's [GA4 mapping](/checkout/analytics-events/#example-map-events-to-ga4) and choose
one source per measurement to avoid duplicates.

## Confirmation widget events

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

| Event | Fires when | Payload |
| --- | --- | --- |
| `load_confirmation` | The confirmation snippet has rendered | Empty object |

### Upsell events

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.

| Event | Fires when | Payload |
| --- | --- | --- |
| `upsell_initialized` | The upsell component first mounts, even if it renders nothing | Empty object |
| `upsell_carousel_loaded` | The carousel first renders with available products and an upsell deadline, even if that deadline has passed | `productCount` |
| `upsell_dialog_opened` | The customer opens a product dialog | `id`, `reference` (optional), `name`, `orderIndex` |
| `upsell_dialog_closed` | The customer manually closes a product dialog, including after completion | `id`, `reference` (optional), `name` |
| `upsell_quantity_changed` | The customer changes quantity with the dialog's stepper | `id`, `quantity` |
| `upsell_product_added` | The request to add the upsell product to the order succeeds | `id`, `reference` (optional), `name`, `quantity` |
| `upsell_add_failed` | The request to add the upsell product to the order fails | `id`, `reference` (optional), `name`, `quantity`, `variant_id` (optional), `selected_attributes` (optional), `errorCode` (optional) |
| `upsell_timer_expired` | The upsell deadline passes while the widget is open, even if the timer badge is hidden | Empty object |
| `upsell_not_available` | The mounted upsell component detects no items or no available items | `reason`, `productCount` (optional) |

### Delivery and interaction details

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.

### Upsell payload fields

| Field | Type | Meaning |
| --- | --- | --- |
| `id` | string | Upsell product id |
| `reference` | string | Product reference, included when non-empty |
| `name` | string | Product name |
| `quantity` | number | Selected quantity; for `upsell_product_added`, the quantity added by that request |
| `orderIndex` | number | Zero-based product position in the displayed carousel |
| `productCount` | number | Available product count for `upsell_carousel_loaded`; total provided product count for `upsell_not_available` when items exist |
| `variant_id` | string | Selected variant SKU, included on failure when the product has variants and a variant is selected |
| `selected_attributes` | object with string values | Selected attribute names and values, included under the same condition as `variant_id` |
| `errorCode` | string | Error code, included on failure when available |
| `reason` | string | One 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:

| Reason | Meaning | `productCount` |
| --- | --- | --- |
| `no_items` | No upsell items are present in the order data checked by the mounted component | Omitted |
| `out_of_stock` | Every provided item has stock quantity below 1 | Included |
| `purchase_limit_zero` | Every provided item has a purchase limit below 1, unless all items are out of stock | Included |
| `all_maxed_out` | No provided items are available for another reason: mixed stock/limit restrictions, cart quantity at the limit, or missing cart items data | Included |

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.

### Visibility and fallback handling

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.

### Subscribe to upsell events

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

```js
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);
    },
  });
});
```

## Related

- [Analytics events in the dataLayer](/checkout/analytics-events/): built-in funnel events
  and GA4 mapping for your tag manager.
- [Render and update](/checkout/integrate/render-checkout-snippet/) — embed the snippet and
  access the checkout API object.
- [Server-side callbacks](/checkout/callbacks/) — process order changes on your server.
- [Handle callbacks](/checkout/integrate/validation-callback/) — block a purchase from
  your server rather than the browser.
- [Troubleshooting Checkout](/checkout/troubleshooting/) — diagnose iframe failures.
