# Storefront API

Browser JavaScript API for reading Kaching Subscriptions streaks from Shopify themes, cart drawers, and apps.

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

Kaching Subscriptions rewards subscribers with **streaks**: discounts and free gifts on later orders, shown as a ladder in the product-page widget. This page documents the **storefront API**, a browser-side JavaScript object at `window.KachingSubscriptions`. It lets themes, cart drawers, and third-party apps read the streak a subscription plan earns on any storefront page, either as raw data or as the ladder the widget draws.

> **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. For server-side access, use the [Kaching Subscriptions API](https://www.kachingappz.com/developers/subscriptions/shop-api/).

## Prerequisites

- A Shopify store with the [Kaching Subscriptions app](https://apps.shopify.com/kaching-subscriptions) installed
- The **Kaching Subscriptions** app embed turned on in the theme (**Online Store → Themes → Customize → App embeds**)
- A live streak for there to be anything to show. Without one, every method returns `null`.

## Accessing the API

The app embed's script attaches the API to the global `window` object on every storefront page, then dispatches a `kaching-subscriptions:ready` event on `document`:

```javascript
window.KachingSubscriptions;
```

The script loads deferred, so your code may run before or after it. Handle both cases:

```javascript
function onKachingSubscriptionsReady(callback) {
  if (window.KachingSubscriptions) {
    callback(window.KachingSubscriptions);
    return;
  }

  document.addEventListener(
    "kaching-subscriptions:ready",
    () => callback(window.KachingSubscriptions),
    { once: true },
  );
}

onKachingSubscriptionsReady(({ streaks }) => {
  // call streaks.get / streaks.getLadder here
});
```

> **Warning** `window.KachingSubscriptions` is not set when the app embed is turned off, when the page is opened with `?kaching-subs=off`, or when the store's Kaching Subscriptions plan is inactive. Always guard on it.

### TypeScript

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

```typescript
declare global {
  interface Window {
    KachingSubscriptions?: KachingSubscriptionsApi;
  }
}

interface KachingSubscriptionsApi {
  streaks: {
    get: (sellingPlanId: number | string | null | undefined) => Streak | null;
    getLadder: (
      sellingPlanId: number | string | null | undefined,
    ) => Promise<StreakLadder | null>;
  };
}

interface Streak {
  id: number;
  conditions: { type: "ALL" | "SELLING_PLAN_GROUP"; targetGid: string | null }[];
  steps: StreakStep[];
}

type StreakStep = { afterOrder: number } & (
  | ({ type: "DISCOUNT" } & StreakDiscount)
  | ({ type: "PRODUCT" } & StreakGifts)
  | ({ type: "DISCOUNT_AND_PRODUCT" } & StreakDiscount & StreakGifts)
);

interface StreakDiscount {
  discountType: "PERCENTAGE" | null;
  discountValue: number | null;
  recurringCycleLimit: number | null;
}

interface StreakGifts {
  products: { productId: string; variantId: string | null; quantity: number }[];
}

interface StreakLadder {
  streakId: number;
  sellingPlanId: number;
  catalog: "loaded" | "unavailable";
  steps: {
    afterOrder: number;
    caption: string;
    projectedDate: string | null;
    labels: string[];
    discount: {
      percentage: number;
      recurringCycleLimit: number | null;
      label: string;
    } | null;
    gifts: {
      productId: string;
      variantId: string | null;
      quantity: number;
      title: string | null;
      imageUrl: string | null;
      originalPrice: string | null;
    }[];
  }[];
}
```

`KachingSubscriptions` is typed as optional because it is only present after the app embed's script runs. Always narrow before calling.

## The selling plan id

Both methods take the id of a selling plan, exactly as Shopify's [Cart AJAX API](https://shopify.dev/docs/api/ajax/reference/cart#get-locale-cart-js) gives it for a cart line: `items[i].selling_plan_allocation.selling_plan.id`. A number or the same digits as a string both work.

A plan earns the streak that names its selling plan group, and otherwise the store's **Everyone** streak, if there is one. A one-time line (no selling plan, so `null` or `undefined`), a plan from another app, or an unknown id gives `null`.

## Methods

### streaks.get

Returns the raw streak the plan earns, or `null` when it earns none. Synchronous.

```javascript
const streak = window.KachingSubscriptions.streaks.get(sellingPlanId);
```

```typescript
get(sellingPlanId: number | string | null | undefined): Streak | null
```

**Example result:**

```javascript
{
  id: 12,
  conditions: [
    { type: "SELLING_PLAN_GROUP", targetGid: "gid://shopify/SellingPlanGroup/123" },
  ],
  steps: [
    {
      afterOrder: 2,
      type: "DISCOUNT",
      discountType: "PERCENTAGE",
      discountValue: 10,
      recurringCycleLimit: null,
    },
    {
      afterOrder: 4,
      type: "PRODUCT",
      products: [{ productId: "8812", variantId: null, quantity: 1 }],
    },
  ],
}
```

| Field | Type | Description |
| --- | --- | --- |
| `id` | number | The streak's id. |
| `conditions` | array | Who the streak is for: one `ALL` row (everyone), or one `SELLING_PLAN_GROUP` row per plan group with its Admin GID. |
| `steps[].afterOrder` | number | The order that earns the step. The order placed at checkout is order 1. |
| `steps[].type` | string | `DISCOUNT`, `PRODUCT` (free gifts), or `DISCOUNT_AND_PRODUCT`. |
| `steps[].discountValue` | number \| null | The percentage off, on steps with a discount. |
| `steps[].recurringCycleLimit` | number \| null | How many orders the discount lasts, starting with that one. `null` means every order from then on. |
| `steps[].products` | array | Free gifts, on steps with gifts. Ids only, no titles. `variantId: null` means the subscriber picks the variant after subscribing. |

> **Note** `get` returns a copy, so changing the object you get back has no effect on the widget.

---

### streaks.getLadder

Returns a promise of the ladder the product-page widget would draw for the plan, ready to render, or `null` when the plan earns no streak. The steps, captions and labels match the widget's ladder for that plan, in the storefront's language, with gift titles, images and prices loaded.

```javascript
const ladder = await window.KachingSubscriptions.streaks.getLadder(sellingPlanId);
```

```typescript
getLadder(sellingPlanId: number | string | null | undefined): Promise<StreakLadder | null>
```

**Example result**, for a monthly plan and a streak with 10% off every order from order 2 and a free gift on order 4:

```javascript
{
  streakId: 12,
  sellingPlanId: 690123456,
  catalog: "loaded",
  steps: [
    { afterOrder: 0, caption: "Today", projectedDate: "2026-11-19", labels: ["Join"], discount: null, gifts: [] },
    {
      afterOrder: 2,
      caption: "Dec 19",
      projectedDate: "2026-12-19",
      labels: ["10% off"],
      discount: { percentage: 10, recurringCycleLimit: null, label: "10% off" },
      gifts: [],
    },
    {
      // Between two steps: the lasting 10% from order 2 still pays here.
      afterOrder: 3,
      caption: "Jan 19",
      projectedDate: "2027-01-19",
      labels: ["10% off"],
      discount: { percentage: 10, recurringCycleLimit: null, label: "10% off" },
      gifts: [],
    },
    {
      afterOrder: 4,
      caption: "Feb 19",
      projectedDate: "2027-02-19",
      labels: ["10% off", "+ gift"],
      discount: { percentage: 10, recurringCycleLimit: null, label: "10% off" },
      gifts: [
        {
          productId: "8812",
          variantId: null,
          quantity: 1,
          title: "Sticker pack",
          imageUrl: "https://cdn.shopify.com/…",
          originalPrice: "$5.00",
        },
      ],
    },
  ],
}
```

| Field | Type | Description |
| --- | --- | --- |
| `streakId` | number | The streak's id, as in `get`. |
| `sellingPlanId` | number | The plan the ladder is for. |
| `catalog` | string | `"loaded"`, or `"unavailable"` when the gift products could not be loaded (see below). |
| `steps[].afterOrder` | number | The order that earns the step. `0` is the Join step: today's order. |
| `steps[].caption` | string | `"Today"`, a date (`"Dec 19"`), or an order number (`"Order 3"`), following the widget's **Step labels** setting. |
| `steps[].projectedDate` | string \| null | The calendar day (`yyyy-mm-dd`) the order is projected to, filled under either Step labels setting. `null` when the plan has no usable delivery interval. |
| `steps[].labels` | string\[\] | The lines the widget draws under the step, translated. |
| `steps[].discount` | object \| null | The discount on that order: `percentage`, `recurringCycleLimit` (`null` = every order from then on), and a translated `label`. |
| `steps[].gifts` | array | Free gifts on that order: ids, `quantity`, `title`, `imageUrl`, and `originalPrice` (price × quantity, in the store's money format; the lowest variant price when the variant is left open). |

How the ladder is worked out:

- **Dates** are projected as if the cart checks out today, from the plan's delivery interval.
- **Display settings** (Step labels, Join step) and **translations** come from the widget the plan belongs to. A widget that doesn't draw a ladder (the ladder turned off, or an older v1 widget) gets the defaults: dates, with the Join step.
- **A step between two rewards** appears when a lasting discount keeps paying on that order, as on the product page.
- **A lasting discount** (`recurringCycleLimit: null` on the last discount) continues past the last step. The widget pages through those later orders; `getLadder` returns the streak's own steps, ending at the last one.

> **Note** `getLadder` does not reject because gift products could not be loaded. It resolves with `catalog: "unavailable"`, and every gift keeps its ids and quantity with `title`, `imageUrl` and `originalPrice` set to `null`. A gift the storefront does not return (a draft or archived product) also has `null` text, while `catalog` is `"loaded"`.

**Loading.** The ladder is built by the Kaching Subscriptions widget script, which `getLadder` waits for the first time it runs. On a store whose pages don't already load that script, the first call loads it (about 59 KB gzipped). The gift products of every streak load in one request, the first time a ladder needs them, and are reused for the rest of the page. A load that fails stays failed until the next page load. If the widget script itself cannot load, `getLadder` resolves `null` after up to 10 seconds.

## Example: streak ladder in a cart drawer

Read the cart, then ask for each subscription line's ladder:

```javascript
onKachingSubscriptionsReady(async ({ streaks }) => {
  const cart = await (await fetch("/cart.js")).json();

  for (const item of cart.items) {
    const ladder = await streaks.getLadder(
      item.selling_plan_allocation?.selling_plan?.id,
    );
    if (!ladder) continue;

    const container = document.querySelector(
      `[data-cart-line-key="${item.key}"] .streak`,
    );
    if (!container) continue;

    // Text, not HTML: labels carry the merchant's translations.
    const list = document.createElement("ul");
    for (const step of ladder.steps) {
      const row = document.createElement("li");
      row.textContent = `${step.caption}: ${step.labels.join(" ")}`;
      list.append(row);
    }
    container.replaceChildren(list);
  }
});
```

Run it again whenever the drawer re-renders after a cart change. Repeat calls make no new request for gift products already loaded on the page.

**With Kaching Cart**, read the lines from the drawer's cached cart instead of fetching it. The items follow the same Shopify cart shape:

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

for (const item of cart?.items ?? []) {
  const ladder = await window.KachingSubscriptions?.streaks.getLadder(
    item.selling_plan_allocation?.selling_plan?.id,
  );
  // …render as above
}
```

See the [Storefront Drawer API](https://www.kachingappz.com/developers/cart/storefront-drawer-api/) for `getCartData`.

## Stability

Method names, the `kaching-subscriptions:ready` event name, and every field documented above are a public contract. Fields may be added, but none are renamed or removed.
