# Render and update

Embed the Kustom Checkout html_snippet, mount it in a single-page app and keep the cart in sync with suspend, update and resume.

> Live page: renders the `html_snippet` from the last created order.

Use the `html_snippet` and `order_id` from [Create an order](/checkout/integrate/create-order/).
Keep the same order while the customer checks out, updating it with
`POST /checkout/v3/orders/{order_id}`.

## Where the checkout lives on the page

The iframe handles address, shipping and payment. Keep the surrounding page focused on
completing the purchase. Use this layout unless your own testing supports another:

| Region | What goes there |
| --- | --- |
| Header | Logo, a security badge, a help link. No navigation, no promotions |
| Above the iframe | The cart, editable in place: quantity, remove, discount code and the running total |
| The iframe | Address, shipping, payment, **Pay order** |
| Below the iframe | Returns policy and a support contact. Nothing that leaves the page |

- **Use a dedicated route**, such as `/checkout`, reached from the cart page. Embedding the
  iframe on the cart page creates orders before customers choose to check out.
- **Keep the cart editable above the iframe.** Update quantities and discounts in place using
  the sequence below.
- **Use one column, full width on a phone.** Let the iframe set its height. Avoid drawers,
  modals and tabs, which constrain scrolling under a mobile keyboard.
- **Keep one buy button**, inside the iframe. Leave newsletters, upsell carousels and other
  calls to action off the checkout page.
- **Render immediately.** Don't lazy-load the snippet or wait for a consent banner to close.

Show the order total outside the iframe as well, and update both together:
[`order_total_change`](/checkout/client-side-events/) is what tells your panel the total moved
after a shipping choice inside the iframe.

## Put it on the page

The snippet is a `<div>` plus a `<script>` that loads the checkout iframe. Keep the script tags
exactly as received. The container you inject into is yours, and its id is your choice.

**Server-side** — render it straight into your template:

```html
<div id="checkout">{{ kustom_order.html_snippet }}</div>
```

**Client-side** — `innerHTML` doesn't execute scripts, so recreate them. Preserve their
attributes, including `src`, `async` and `nonce`, so the bootstrap script can run.

```js title="render-checkout.js" wrap
// Scripts inserted via innerHTML never execute, so re-create each one.
function renderCheckout(container, htmlSnippet) {
  container.innerHTML = htmlSnippet;
  container.querySelectorAll('script').forEach((inert) => {
    const script = document.createElement('script');
    for (const a of inert.attributes) script.setAttribute(a.name, a.value);
    script.textContent = inert.textContent;
    inert.replaceWith(script);
  });
}
```

Render the snippet on the page whose URL you gave as `merchant_urls.checkout`. See *When it
breaks* below for what happens if it runs more than once.

## Mount it in a single-page app

In a React, Vue or Svelte route:

- **Mount once per page view.** Development modes can run effects twice, including React
  StrictMode and fast refresh. Guard the mount and clear the container on unmount. See
  [When it breaks](#when-it-breaks).
- **Key the mount on the order, not on the cart.** A cart update changes the order behind the
  iframe, and the iframe re-reads it on `resume()`. Remounting on every cart change flashes the
  checkout and loses whatever the customer had typed.
- **Fetch the snippet on mount, every time.** Never keep it in application state across
  navigation: the stored copy may belong to an order that has since completed or expired. A
  query-string change on the same route — the notice a rejected validation sends the customer
  back with — isn't a remount.

```jsx title="KustomCheckout.jsx" wrap
import { useEffect, useRef } from 'react';
import { renderCheckout } from './render-checkout';

export function KustomCheckout({ orderId, htmlSnippet }) {
  const container = useRef(null);
  const mountedFor = useRef(null); // which order is on screen right now

  useEffect(() => {
    const el = container.current;
    if (!el || mountedFor.current === orderId) return; // StrictMode runs this twice
    mountedFor.current = orderId;
    renderCheckout(el, htmlSnippet);
    return () => {
      el.innerHTML = '';
      mountedFor.current = null;
    };
  }, [orderId, htmlSnippet]); // not the cart: cart changes go through suspend and resume

  return <div ref={container} style={{ minWidth: 320 }} />;
}
```

The accessor the snippet installs — and with it `suspend`, `resume` and every event — exists only
once the snippet's script has run. Resolve it before calling anything on it:

```js title="checkout-api.js" wrap
export function checkoutApi() {
  return new Promise((resolve) => {
    const tick = () =>
      window._klarnaCheckout ? window._klarnaCheckout(resolve) : setTimeout(tick, 50);
    tick();
  });
}
```

`v-html` and `{@html}` insert scripts without running them, so Vue and Svelte call
`renderCheckout` from the mounted hook rather than binding the snippet into the template. The
mount-once guard and the cleanup apply unchanged.

On mount, request the order from your server, as the quickstart's `index.html` does. Your
server decides whether to create or reuse an order.

## Who owns the cart

Your system owns the cart. Keep one Kustom order per cart for payment.

- **The order belongs to the cart, not to the session.** Store the `order_id` on the cart
  record. A customer with two tabs open, or one who logs in halfway through, still has one cart
  and therefore one order.
- **Create it when the checkout route opens**, not when something is added to the cart. Most
  carts never reach the checkout.
- **Mark the order with the cart's version.** Every cart mutation increments a counter of yours.
  Send it in `merchant_data` (`"cart:crt_8a1f:v17"`) on every create and update. The
  [validation callback](/checkout/integrate/validation-callback/#answer-the-validation-callback)
  carries it back in the order it posts you, so you can compare it with the cart and catch an
  update that never landed.

When the checkout route loads, the cart is in one of four states:

| The cart holds | Do |
| --- | --- |
| No order | Create one. Store its `order_id`, `status` and `started_at` on the cart |
| An order, `checkout_incomplete`, touched within 48 hours | `GET` it. If its `merchant_data` version is behind the cart, `POST` the difference. Render the snippet it returns |
| An order that has expired | `GET` returns an empty `404`. Create a new one and replace the `order_id` on the cart |
| An order that is `checkout_complete` | The customer already paid. Send them to the confirmation route for that order and start a fresh cart. Never render the checkout snippet for a completed order |

Serialize order creation per cart on your server. If a route mounts twice and makes two
requests, the second request must reuse the first order to prevent duplicate payments.

## When the cart changes

When the customer changes a quantity or applies a coupon:

1. The customer changes something.
2. `suspend()` the checkout, so it stops rendering a state that's about to be stale.
3. `POST` the change to `/checkout/v3/orders/{order_id}`.
4. `resume()`, which re-reads the order and redraws the totals.

Always suspend before updating to prevent customer interactions from overlapping the update.

```js title="update.js" wrap
async function updateOrder(orderId, changes) {
  window._klarnaCheckout((api) => api.suspend());
  try {
    await fetch(`/checkout/${orderId}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(changes),
    });
  } finally {
    // Always. resume() is what re-reads the order and redraws the totals.
    window._klarnaCheckout((api) => api.resume());
  }
}
```

`/checkout/${orderId}` is your server route. It forwards the request to
`/checkout/v3/orders/{order_id}` with Basic auth credentials, which must stay server-side.

`resume()` belongs in a `finally` because it has to run even when the `POST` fails — an iframe
left suspended stays frozen. Skip it and a ten-second auto-resume fires on its own. Pass
`api.suspend({ autoResume: { enabled: false } })` when an update legitimately takes longer than
that.

The call itself is a plain `POST` of the fields you're changing — fields you leave out keep
their current values. A cart update might change a quantity, add or remove a line, or swap the
shipping option a customer picked.

**Sending `order_lines` replaces every line on the order.** Include all lines and recalculate
`order_amount` and `order_tax_amount`; Kustom rejects mismatched totals. Omitted lines are
removed.

Send only the fields you're changing. Resending the original order can overwrite newer
address or `options` values. Update the existing order for cart changes.

This request changes the first line's quantity and includes all lines and both totals:

> Live page: a request runner, which sends this call and shows the response inline. Programmatic equivalent: `POST https://api.playground.kustom.co/checkout/v3/orders/{order_id}`, authenticated with HTTP Basic using your API username and API password.

```json
{
  "order_lines": [
    {
      "type": "physical",
      "reference": "tshirt-001",
      "name": "Cotton T-Shirt",
      "quantity": 3,
      "quantity_unit": "pcs",
      "unit_price": 25000,
      "tax_rate": 2500,
      "total_amount": 75000,
      "total_discount_amount": 0,
      "total_tax_amount": 15000
    },
    {
      "type": "physical",
      "reference": "chinos-001",
      "name": "Slim Fit Chinos",
      "quantity": 1,
      "quantity_unit": "pcs",
      "unit_price": 70000,
      "tax_rate": 2500,
      "total_amount": 70000,
      "total_discount_amount": 0,
      "total_tax_amount": 14000
    },
    {
      "type": "discount",
      "reference": "discount-10pct",
      "name": "10% off",
      "quantity": 1,
      "quantity_unit": "pcs",
      "unit_price": -14500,
      "tax_rate": 2500,
      "total_amount": -14500,
      "total_discount_amount": 0,
      "total_tax_amount": -2900
    }
  ],
  "order_amount": 130500,
  "order_tax_amount": 26100
}
```

After the customer enters the checkout:

| Constraint | What it means for your code |
| --- | --- |
| Updates are rejected once the order's status is no longer `checkout_incomplete` | A completed order can't be patched back open. This one does tell you: `403` with `error_code: READ_ONLY_ORDER`. Treat it as the signal to send the tab to your confirmation route. An expired order is gone instead, and answers an empty `404`. [Order lifecycle](/basics/order-lifecycle/) covers every status an order moves through |
| `billing_address` and `shipping_address` updates are ignored once the customer has entered their own | Sending an address you collected on your own guest-checkout form does nothing after that point — don't rely on it to change what the customer already typed |

An ignored address update still returns `200`. Read the order afterward to check its address.

### One change at a time

For concurrent updates, the last request to reach Kustom wins, even if it contains older data:

- **Serialize per cart on your server.** One lock, or one queue, around the whole update
  including the call to Kustom.
- **Version every mutation.** The browser sends the cart version it last saw. A stale version
  gets a `409` from your server. The client reloads the cart and reapplies the customer's change.
- **Debounce, but never drop the last change.** A trailing debounce of a few hundred
  milliseconds on the stepper is fine. The final state is always sent.
- **Resume only after the update completed, and on failure too.** Resuming early makes the iframe
  re-read the old order, so the two totals disagree until the next event. Not resuming leaves a
  frozen checkout, which the `finally` above prevents.

If the update is rejected because the order is no longer `checkout_incomplete`, the customer
completed the purchase in another tab. Send this tab to the confirmation route rather than
showing an error.

## Keep your own cart panel in sync

Use events from the snippet's accessor to update totals and item counts outside the iframe
without polling. [Checkout JavaScript events](/checkout/client-side-events/) lists event names,
payloads and listener registration.

## When it breaks

| Rule | Why |
| --- | --- |
| One snippet per page | A second injection leaves two iframes and leaked listeners. Re-initializing needs a page load, not a second call to your render function |
| Never inside an iframe of your own | Kustom's iframe expects to talk directly to the top frame it's embedded in, not through another one of yours |
| Don't style the container or anything inside it | Put width rules on a wrapper, allow at least 320px and let the height change freely. A global `iframe { … !important }` rule, or a `transform` on `body`, breaks the checkout's fullscreen states |
| Don't cache `html_snippet` across sessions | It's tied to the order it came from, not to the customer or the page |
| Allow `*.kustom.co` in `frame-src` and `script-src` | Without it the browser silently drops the iframe rather than erroring |
| If you send a `Cross-Origin-Opener-Policy` header, make it `same-origin-allow-popups` | Plain `same-origin` makes popup payment methods open twice |

## Prove it

Select **Add one more of line 1** above. It suspends the checkout, updates the order and
resumes it. Check that the total changes without a page reload. You can also run the `POST`
example and inspect the returned `order_amount` and updated line.

Next: [Handle callbacks](/checkout/integrate/validation-callback/).

## Related

- [Create an order](/checkout/integrate/create-order/) — where the `html_snippet` and the
  `order_id` come from
- [Checkout JavaScript events](/checkout/client-side-events/) — every event the iframe emits,
  and its payload
- [Order lifecycle](/basics/order-lifecycle/) — every status an order moves through, including
  `checkout_incomplete`
- [Handle callbacks](/checkout/integrate/validation-callback/) — a last look at the
  order before the purchase completes
- [Supported browsers](/checkout/supported-browsers/) — the browser versions the checkout runs in
- [Confirm the order](/checkout/integrate/confirmation-and-push/) — what happens after the
  customer pays
