# Storefront drawer API

Browser JavaScript API for interacting with the Kaching Cart drawer from Shopify themes, page builders, and apps.

https://www.kachingappz.com/developers/cart/storefront-drawer-api/ · Updated 2026-11-23

Kaching Cart is a Shopify app that adds a fully-featured cart drawer to a merchant's storefront. This page documents the **storefront drawer API** — a browser-side JavaScript object attached to `window.kachingCartApi` that lets themes, page builders, and third-party apps drive the drawer: open and close it, read cart state, refresh data, and override the default checkout button behavior.

> **Note** This is a client-side API that only exists in the customer's browser on the storefront. It is not an HTTP/server API — there is no base URL, no authentication, and no way to call it from a backend.

## Prerequisites

- A Shopify store with the [Kaching Cart app](https://apps.shopify.com/kaching-cart) installed and enabled on the storefront
- The cart extension loaded on the page — `window.kachingCartApi` is only available after Kaching Cart has booted

## Accessing the API

Once the cart extension boots, the API is attached to the global `window` object:

```javascript
window.kachingCartApi
```

In non-preview environments, opening the browser DevTools console will show a collapsed log group — `🛍️ Kaching Cart API Documentation` — listing every available method along with its arguments and whether it returns a Promise. This is generated from the same source as this page and is the canonical reference at runtime.

> **Note** The API is not available immediately on page load — it's attached when the cart extension finishes initializing. If you need to call it from code that may run earlier (for example a `DOMContentLoaded` handler), guard with `if (window.kachingCartApi)` or poll until it appears.

### TypeScript

If you're working in TypeScript, declare the global so the compiler knows about it:

```typescript
declare global {
  interface Window {
    kachingCartApi?: KachingCartApi;
  }
}

interface KachingCartApi {
  openCart: (options?: { refetchCart?: boolean }) => void;
  closeCart: () => void;
  refreshCart: () => Promise<void>;
  getCartData: () => CartData | undefined;
  updateTieredPromotionsBar: () => Promise<void>;
  getCheckoutButtonClickHandler: () =>
    | ((event: MouseEvent) => boolean | Promise<boolean>)
    | null;
  setCheckoutButtonClickHandler: (
    newHandler: (event: MouseEvent) => boolean | Promise<boolean>,
  ) => void;
}
```

`kachingCartApi` is typed as optional because it's only present after the extension boots — always narrow before calling.

## Methods

### openCart

Opens the cart drawer.

```javascript
window.kachingCartApi.openCart();
```

```typescript
openCart(options?: { refetchCart?: boolean }): void
```

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `refetchCart` | boolean | `false` | When `true`, the drawer refetches cart data as it opens. Use this after adding/updating items outside the drawer. |

**Example — open after adding an item via the Shopify AJAX API:**

```javascript
await fetch("/cart/add.js", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ id: variantId, quantity: 1 }),
});

window.kachingCartApi?.openCart({ refetchCart: true });
```

---

### closeCart

Closes the cart drawer.

```javascript
window.kachingCartApi.closeCart();
```

```typescript
closeCart(): void
```

---

### refreshCart

Refetches the cart data from Shopify and updates the drawer. Use after a mutation that happened outside Kaching Cart's own controls — for example, an Add-to-Cart elsewhere on the page, or a third-party app that mutated the cart.

```javascript
await window.kachingCartApi.refreshCart();
```

```typescript
refreshCart(): Promise<void>
```

The returned Promise resolves once the refetch completes. If you need the drawer to reopen with the fresh data, prefer [\`openCart({ refetchCart: true })\`](https://www.kachingappz.com/developers/cart/storefront-drawer-api/#opencart) — it combines both operations.

---

### getCartData

Returns the currently cached cart data synchronously. The shape follows Shopify's [Cart AJAX API](https://shopify.dev/docs/api/ajax/reference/cart#get-locale-cart-js) response, with a few Kaching-specific extensions.

```javascript
const cart = window.kachingCartApi.getCartData();

if (cart) {
  console.log(`Cart has ${cart.item_count} items, total ${cart.total_price}`);
}
```

```typescript
getCartData(): CartData | undefined
```

Returns `undefined` if the cart hasn't been fetched yet. Commonly used fields:

| Field | Type | Description |
| --- | --- | --- |
| `token` | string | Shopify cart token. |
| `item_count` | number | Total quantity across all line items. |
| `total_price` | number | Cart total in the store's currency subunits (e.g. cents). |
| `total_discount` | number | Total discount applied to the cart, in subunits. |
| `items_subtotal_price` | number | Subtotal before discounts, in subunits. |
| `currency` | string | ISO currency code, e.g. `"USD"`. |
| `items` | array | Line items in the cart. |
| `attributes` | object | Cart-level custom attributes. |
| `note` | string | Cart note. |
| `checkoutUrl` | string? | Resolved checkout URL when available. |

> **Note** This method reads from the in-memory cache — it does not make a network request. To force a fresh read, call [\`refreshCart\`](https://www.kachingappz.com/developers/cart/storefront-drawer-api/#refreshcart) first.

---

### updateTieredPromotionsBar

Recomputes the tiered promotions bar and applies any free gifts, automatic discounts, or upgrades that have become eligible. Useful when you're about to redirect a customer to checkout after adding an item programmatically and want their cart-level promotions reflected before they leave the storefront.

```javascript
await window.kachingCartApi.updateTieredPromotionsBar();
```

```typescript
updateTieredPromotionsBar(): Promise<void>
```

If the tiered promotions bar is not active on the store, this is a no-op. Otherwise it fetches the latest cart state with promo operations resolved, then resumes normal cart interception.

**Example — add an item then go straight to checkout with promos applied:**

```javascript
await fetch("/cart/add.js", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ id: variantId, quantity: 1 }),
});

await window.kachingCartApi?.updateTieredPromotionsBar();
window.location.href = "/checkout";
```

---

### getCheckoutButtonClickHandler

Returns the currently registered custom checkout button handler, or `null` if none has been set.

```javascript
const handler = window.kachingCartApi.getCheckoutButtonClickHandler();
```

```typescript
getCheckoutButtonClickHandler():
  | ((event: MouseEvent) => boolean | Promise<boolean>)
  | null
```

Use this if you want to compose with an existing handler — read it, wrap it, and pass the wrapped version back via [\`setCheckoutButtonClickHandler\`](https://www.kachingappz.com/developers/cart/storefront-drawer-api/#setcheckoutbuttonclickhandler).

---

### setCheckoutButtonClickHandler

Overrides the default checkout button click handler with a function of your own. The handler runs when the customer clicks the checkout button inside the cart drawer.

```javascript
window.kachingCartApi.setCheckoutButtonClickHandler((event) => {
  // run custom logic — analytics, validation, custom redirect, etc.
  return true; // allow the default redirect to proceed
});
```

```typescript
setCheckoutButtonClickHandler(
  newHandler: (event: MouseEvent) => boolean | Promise<boolean>,
): void
```

**Return value semantics:**

| Returned value | Behavior |
| --- | --- |
| `true` | Continue with the default checkout redirect. |
| `false` | Cancel the default redirect. |
| `Promise<boolean>` | Awaited — same semantics as the resolved value. |
| Anything else | Treated as "continue" — only `false` cancels. |

> **Warning** Only `false` cancels the redirect. Returning `undefined` (e.g. forgetting a `return` statement) allows the default behavior to continue, which can mask bugs in your handler logic. Be explicit.

**Example — redirect to a custom checkout page:**

```javascript
window.kachingCartApi.setCheckoutButtonClickHandler((event) => {
  event.preventDefault();
  window.location.href = "/pages/my-custom-checkout";
  return false; // cancel the default redirect
});
```

**Example — run async validation before allowing checkout:**

```javascript
window.kachingCartApi.setCheckoutButtonClickHandler(async (event) => {
  const ok = await validateCartWithMyBackend();

  if (!ok) {
    alert("Please resolve the issues in your cart before checking out.");
    return false;
  }

  return true;
});
```

**Example — compose with an existing handler:**

```javascript
const previous = window.kachingCartApi.getCheckoutButtonClickHandler();

window.kachingCartApi.setCheckoutButtonClickHandler(async (event) => {
  trackCheckoutClick();

  if (previous) {
    return await previous(event);
  }

  return true;
});
```
