> ## Documentation Index
> Fetch the complete documentation index at: https://www.commercengine.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuration

> Full reference for all Hosted Checkout configuration options, events, and methods.

## Init options

These options are passed to `initCheckout()` (framework SDKs) or `Commercengine.init()` / `new Checkout()` (vanilla JS).

### Credentials

| Option        | Type                        | Default        | Description                                                                                                                                                                       |
| ------------- | --------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `storeId`     | `string`                    | —              | Your Commerce Engine Store ID. Required unless `url` is provided.                                                                                                                 |
| `apiKey`      | `string`                    | —              | Your Commerce Engine API Key. Required unless `url` is provided (or already embedded in `url`).                                                                                   |
| `environment` | `"production" \| "staging"` | `"production"` | Determines which subdomain pattern is used: `https://{storeId}.checkout.commercengine.com` or `https://{storeId}.staging.checkout.commercengine.com`.                             |
| `url`         | `string`                    | —              | Override checkout host resolution (local dev, preview builds, custom domains). If host is `localhost` and `storeId` is passed, SDK rewrites to a store-scoped host automatically. |

### Appearance

| Option              | Type                            | Default    | Description                                                                                      |
| ------------------- | ------------------------------- | ---------- | ------------------------------------------------------------------------------------------------ |
| `theme`             | `"light" \| "dark" \| "system"` | `"system"` | Per-session theme override for checkout UI. Primary visual config is managed in Checkout Studio. |
| `appearance.zIndex` | `number`                        | `99999`    | z-index for the checkout overlay container.                                                      |

### Authentication

| Option         | Type                      | Default     | Description                                                                                                                                                                       |
| -------------- | ------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `authMode`     | `"managed" \| "provided"` | `"managed"` | `"managed"`: checkout handles its own auth. `"provided"`: your app manages tokens and syncs them to checkout (recommended when your storefront already uses Storefront SDK auth). |
| `accessToken`  | `string`                  | —           | Initial access token (JWT). Used with `authMode: "provided"`.                                                                                                                     |
| `refreshToken` | `string`                  | —           | Initial refresh token. Used with `authMode: "provided"`.                                                                                                                          |

<Info>
  **When to use `authMode: "provided"`**

  Use this when your app already has its own login system and you want checkout to share the same session. Pass tokens at init and call `updateTokens()` when they change.
</Info>

### Quick Buy

| Option               | Type                                 | Default               | Description                                                                                                      |
| -------------------- | ------------------------------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `quickBuy`           | `object`                             | —                     | Open checkout directly for a specific product.                                                                   |
| `quickBuy.productId` | `string`                             | —                     | Product ID. Required when using `quickBuy`.                                                                      |
| `quickBuy.variantId` | `string \| null`                     | —                     | Variant ID, or `null` for products without variants. Required when using `quickBuy`.                             |
| `quickBuy.quantity`  | `number`                             | `1`                   | Quantity to add.                                                                                                 |
| `sessionMode`        | `"continue-existing" \| "force-new"` | `"continue-existing"` | Whether to continue the user's existing cart or start fresh.                                                     |
| `autoDetectQuickBuy` | `boolean`                            | `false`               | Automatically detect quick buy params from the parent URL. The SDK will clean up the URL params after detection. |

### Managed in Checkout Studio

The following settings are configured remotely in **Checkout Studio** (Config API) and injected into checkout on each page load:

* Feature flags (`loyalty`, `coupons`, `collectInStore`, `freeShippingProgress`, `productRecommendations`)
* Login configuration (enabled methods, account switch behavior)
* Drawer direction (mobile/desktop)
* Payment provider selection
* Brand appearance tokens (colors, typography, shape system, sizing)

These are intentionally not part of the SDK init options.

## Configuration precedence (source of truth)

| Setting                                                                        | Primary source                                         | Runtime override                                | Notes                                                  |
| ------------------------------------------------------------------------------ | ------------------------------------------------------ | ----------------------------------------------- | ------------------------------------------------------ |
| Features, login methods, drawer direction, payment provider, appearance tokens | Checkout Studio                                        | None via SDK init options                       | Saved config is fetched and applied by Hosted Checkout |
| Theme mode                                                                     | Checkout Studio default (`ui.theme`)                   | `theme` in SDK init                             | SDK `theme` is a per-session override                  |
| Auth tokens                                                                    | Parent app / checkout auth flow                        | `accessToken`, `refreshToken`, `updateTokens()` | Depends on `authMode`                                  |
| Quick buy behavior                                                             | SDK init options / parent URL (if auto-detect enabled) | `quickBuy`, `sessionMode`, `autoDetectQuickBuy` | Request-scoped behavior                                |
| Checkout host resolution                                                       | `storeId` + `environment`                              | `url`                                           | `url` fully overrides host resolution                  |

***

## Methods

These methods are available on the checkout instance (vanilla JS) or returned by the framework hook/composable.

| Method                                       | Description                                                                                                                        |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `openCart()`                                 | Open the cart drawer.                                                                                                              |
| `openCheckout()`                             | Open the checkout directly, skipping the cart drawer.                                                                              |
| `close()`                                    | Close the checkout overlay.                                                                                                        |
| `addToCart(productId, variantId, quantity?)` | Add an item. `variantId` can be `null`. `quantity` defaults to `1`.                                                                |
| `updateTokens(accessToken, refreshToken?)`   | Sync auth tokens from your app into checkout.                                                                                      |
| `getCart()`                                  | Returns `{ count, total, currency }`. Vanilla JS only.                                                                             |
| `getTokens()`                                | Returns latest `{ accessToken, refreshToken }` received via `auth:tokens-updated`, or `null` if not received yet. Vanilla JS only. |
| `destroy()`                                  | Remove the iframe and clean up all listeners. Vanilla JS only.                                                                     |

## Runtime properties (vanilla JS)

| Property | Type      | Description                                                                   |
| -------- | --------- | ----------------------------------------------------------------------------- |
| `ready`  | `boolean` | `true` when iframe initialization has completed (or surfaced an error state). |
| `open`   | `boolean` | `true` when the checkout overlay is visible.                                  |

***

## Events

When using the vanilla JS SDK (`@commercengine/js`), you can listen to events with `checkout.on(event, handler)`:

| Event                 | Payload                         | Description                                              |
| --------------------- | ------------------------------- | -------------------------------------------------------- |
| `ready`               | —                               | Iframe loaded and ready.                                 |
| `open`                | —                               | Overlay became visible.                                  |
| `close`               | —                               | Overlay was closed.                                      |
| `complete`            | `{ id, orderNumber }`           | Order placed.                                            |
| `cart:updated`        | `{ count, total, currency }`    | Cart changed.                                            |
| `auth:tokens-updated` | `{ accessToken, refreshToken }` | Tokens changed (anonymous auth, login, logout, refresh). |
| `auth:login`          | `{ user, loginMethod }`         | User logged in (semantic event).                         |
| `auth:logout`         | `{ user }`                      | User logged out (semantic event).                        |
| `auth:session-error`  | —                               | Session invalid, tokens cleared.                         |
| `error`               | `{ message }`                   | Error occurred.                                          |

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
checkout.on("complete", (order) => {
  console.log("Order:", order.orderNumber);
});

// Listen once
checkout.once("ready", () => {
  console.log("Checkout loaded");
});

// Remove listener
const handler = (cart) => console.log(cart.count);
checkout.on("cart:updated", handler);
checkout.off("cart:updated", handler);
```

### Recommended token sync pattern (Storefront SDK + Hosted Checkout)

If your storefront already uses `@commercengine/storefront`, run Hosted Checkout in `provided` mode and wire token sync both ways:

```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { createStorefront, BrowserTokenStorage } from "@commercengine/storefront";
import { initCheckout, getCheckout } from "@commercengine/checkout";

const storefront = createStorefront({
  storeId: "store_xxx",
  apiKey: "ak_xxx",
  session: {
    tokenStorage: new BrowserTokenStorage("ce_"),
  },
  onTokensUpdated: (accessToken, refreshToken) => {
    // SDK -> checkout
    getCheckout().updateTokens(accessToken, refreshToken);
  },
});

const sdk = storefront.session();
await sdk.ensureAccessToken();

const accessToken = await sdk.getAccessToken();
const refreshToken = await sdk.session.peekRefreshToken();

initCheckout({
  storeId: "store_xxx",
  apiKey: "ak_xxx",
  authMode: "provided",
  accessToken: accessToken ?? undefined,
  refreshToken: refreshToken ?? undefined,
  onTokensUpdated: ({ accessToken, refreshToken }) => {
    // checkout -> SDK
    sdk.setTokens(accessToken, refreshToken);
  },
});
```

***

## Environment URLs

| Environment  | Checkout App URL Pattern                               |
| ------------ | ------------------------------------------------------ |
| `production` | `https://{storeId}.checkout.commercengine.com`         |
| `staging`    | `https://{storeId}.staging.checkout.commercengine.com` |

The SDK is hosted at `https://cdn.commercengine.com/v1.js` (single deployment). The `environment` option selects the hostname pattern, and `storeId` is encoded in the subdomain.
