> ## 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 is the only Commerce Engine integration and owns auth. `"provided"`: the parent application owns the Commerce Engine session. **Required whenever `@commercengine/storefront` is also installed.** |
| `accessToken` | `string` | — | Initial access token (JWT). Used with `authMode: "provided"`. |
| `refreshToken` | `string` | — | Initial refresh token. Used with `authMode: "provided"`. |

<Info>
  **Choosing the session owner**

  Use `authMode: "provided"` whenever the parent application imports `@commercengine/storefront` or makes direct session-bound Commerce Engine API calls. This applies even when the storefront has no custom login UI: the Storefront SDK still creates and refreshes the session used by cart, wishlist, account, and order operations.

  Use `managed` mode only when Hosted Checkout is the sole Commerce Engine integration—for example, a static or no-code site that does not use the Storefront SDK.
</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. |

### Callbacks

| Option | Type | Description |
| - | - | - |
| `onReady` | `(data) => void` | Checkout iframe initialized and ready. |
| `onOpen` | `() => void` | Overlay opened. |
| `onClose` | `() => void` | Overlay closed. |
| `onComplete` | `(order) => void` | Order completed successfully. |
| `onCartUpdate` | `(cart) => void` | Cart count, total, or currency changed. |
| `onAnalyticsEvent` | `(event: AnalyticsEvent) => void` | Canonical track or identify envelope emitted by Hosted Checkout. Forward it to your analytics destination. |
| `onTokensUpdated` | `({ accessToken, refreshToken, user }) => void` | Tokens changed after anonymous auth, login, logout, or refresh. |
| `onLogin` | `(data) => void` | Semantic login event. |
| `onLogout` | `(data) => void` | Semantic logout event. |
| `onSessionError` | `() => void` | Session became invalid and checkout cleared its tokens. |
| `onError` | `(error) => void` | Checkout configuration or runtime error. |

<Info>
  Hosted Checkout uses `@commercengine/analytics` internally to map canonical Commerce Engine cart, coupon, checkout-step, payment, identity, and order events. `onAnalyticsEvent` exposes the completed envelopes without prescribing a destination. See [Analytics](/docs/hosted-checkout/analytics) for Hosted Checkout, custom SDK checkout, and direct REST patterns.
</Info>

### 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. |
| `analytics:event` | `AnalyticsEvent` | Canonical Segment/RudderStack-compatible track or identify envelope. |
| `auth:tokens-updated` | `{ accessToken, refreshToken, user }` | 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);

// Forward canonical analytics events
checkout.on("analytics:event", (event) => {
  if (event.type === "track") {
    analytics.track(event.event, event.properties);
  }
});
```

Hosted Checkout uses `@commercengine/analytics` internally. The same vendor-neutral mapper package can also be used by custom checkout implementations built with the Storefront SDK or direct REST calls. See [Analytics](/docs/hosted-checkout/analytics).

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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.