# Build a storefront on Asstio

**Base URL: `https://api.storefront.asstio.com`** · this document: `GET /docs/onboarding` · OpenAPI: `GET /openapi/v1.json` · browsable reference: `GET /docs`

This is the entry point for building a new webshop frontend on Asstio Storefront. It is written for an AI
agent with Asstio MCP tools: read this part top to bottom (it is the whole path from nothing to a running
catalogue), call the tools it names, and build the frontend. A human reading it directly gets the same story,
minus the ability to run step 1.

The guide is four documents, so an agent reads only what the task needs:

| Part | Read it | Address |
| --- | --- | --- |
| **This document**: what exists, Steps 0-3 (look at the catalogue, create the shop, talk to the API, stack), when it looks broken | first, all of it | `GET /docs/onboarding` |
| **Checkout** (Step 4, sections 4.1-4.8): configuration, the hosted payment flow, pitfalls, per-provider notes, testing, shipping | when you build the cart and checkout | `GET /docs/onboarding/checkout` |
| **Contract reference**: every response shape (listing, product and variants, search, filters, images, content and attributes, cart, product facts, GA4) | look things up as you build a page; do not read it end to end | `GET /docs/onboarding/reference` |
| **Product ranking**: popular, newest and recommended order, pinned and hidden products, how to set it up with MCP and what the frontend sees | when you want a deliberate listing order | `GET /docs/onboarding/ranking` |

Links between the parts are written as `/docs/onboarding/<part>#<section>`. Each document also answers at the same
address with `.md` appended.

Asstio Storefront is a shared, multi-tenant, headless B2C read API. A new shop is **configuration inside
Asstio**, not a new backend to operate: no infrastructure to provision, no database, no deploy on our side.
The frontend lives in its own repository, is deployed wherever the customer likes, and talks only to the
public API documented here.

Division of labour, so you know where to put things:

| Concern | Owner |
| --- | --- |
| Products, prices, stock, categories, customers, orders | Asstio (Purchase) |
| Search index, slugs, facets, listing/detail responses | Asstio Storefront (this API) |
| Pages, layout, design, routing, SEO markup, cart UI | Your frontend |

## What exists today, and what does not

**Today the API is a catalogue read surface with images, descriptions, attributes, brand, related products and
bundles (0.3), a cart, and a hosted checkout with order lookup (0.4). No editorial page content yet — that is the
CMS phase.** Verified against the code at `v0.13.0`, 2026-10-09 (the shipping rows at `v0.16.1`, 2026-10-11; the
wording on context headers, page bindings, offers and price pairs at the market-model release):

| Available | Endpoint |
| --- | --- |
| Site bootstrap (markets, locales, page bindings, offer policy, capabilities, URL patterns, config version, media URL templates) | `GET /v1/site` |
| Product search & listing with facets; spelling correction, query intents and rescues (see [Search](https://api.storefront.asstio.com/docs/onboarding/reference#search)) | `GET /v1/products` |
| Search measurement events (exposures, clicks, add-to-carts), with the shopper's consent | `POST /v1/events`, `trackSearchEvents()` in the SDK (see [Search events](https://api.storefront.asstio.com/docs/onboarding/reference#search-events-post-v1events)) |
| Product, variant and cart-line images as media descriptors (see [Images](https://api.storefront.asstio.com/docs/onboarding/reference#images)) | on every product, card, variant and cart response |
| Product detail (by slug, historical slug or id) | `GET /v1/products/{slugOrId}` |
| Product lookup by SKU (product's own or a variant's) | `GET /v1/products/by-sku/{sku}` |
| Variant paging with cascading availability | `GET /v1/products/{slugOrId}/variants` |
| Collection tree and one collection with its listing | `GET /v1/collections`, `GET /v1/collections/{slugOrId}` |
| Category tree as data (facet source, not pages) | `GET /v1/categories` |
| Sitemap rows and lastmod for revalidation, per page binding | `GET /v1/sitemap?binding=` (`?cursor=start` for a full crawl; the SDK's `sitemapEntries` walks it) |
| Cart: create, read, add/update/remove line, change market, country or locale | `POST/GET /v1/cart`, `POST /v1/cart/lines`, `PATCH/DELETE /v1/cart/lines/{id}`, `POST /v1/cart/context` |
| Discount codes on the cart, and links that carry a code (`?kod=`, `/kod/X`) | `POST /v1/cart/codes`, `DELETE /v1/cart/codes/{code}`; SDK `applyCode`, and `@asstio-dev/storefront/code-link` for links (see [Discount codes and code links](https://api.storefront.asstio.com/docs/onboarding/reference#discount-codes-and-code-links)) |
| Checkout: start or converge, status, complete (hosted provider widget) | `POST /v1/checkout`, `GET /v1/checkout/{attemptId}`, `POST /v1/checkout/{attemptId}/complete` (see [Step 4](https://api.storefront.asstio.com/docs/onboarding/checkout#step-4--checkout)) |
| Order lookup with the order's access token | `GET /v1/orders/{orderId}` with `X-Order-Token` |
| Shipping estimate for the cart: options, fees, free-shipping progress. The shipping *choice* is made inside the provider's widget | `GET /v1/cart/shipping-estimate`; the chosen shipping on the order is `OrderDto.shipping` (see [4.8 Shipping](https://api.storefront.asstio.com/docs/onboarding/checkout#48-shipping)) |
| Product content: description, attributes, brand, related products, bundles | on every product detail response (see [Content, attributes, related products and bundles](https://api.storefront.asstio.com/docs/onboarding/reference#content-attributes-related-products-and-bundles)) |
| Search-as-you-type and search within a facet panel | `GET /v1/search/suggest`, `GET /v1/products/facets/{key}` (see [Suggest and search-in-facet](https://api.storefront.asstio.com/docs/onboarding/reference#suggest-and-search-in-facet)) |
| Brand pages and responsible parties | `GET /v1/brands`, `/v1/brands/{slugOrId}`, sitemap `type=brand`; `brand` and `responsible` on products and variants |
| Product facts (brand, categories, short description, attributes) on cards, cart lines, checkout cart lines and order lines, plus GA4 ecommerce mapping | `productFacts()`, `toGa4Item()`, `toGa4Ecommerce()` in the SDK (see [Product facts and GA4](https://api.storefront.asstio.com/docs/onboarding/reference#product-facts-and-ga4)) |

**Not built yet — do not design around it, do not promise it to the user:**

- **No order confirmation e-mail from the storefront.** A shop can take a paid order end to end; the mail comes in a
  later release.
- **No shipping picker of your own.** Shipping is built (see [4.8 Shipping](https://api.storefront.asstio.com/docs/onboarding/checkout#48-shipping)), but the shopper chooses
  inside the provider's widget. Do not design a shipping step beside it, and do not design around split parcels,
  time slots or a returns link: those are not built.
- **No code price in listings or on the product page.** A code's effect shows in the cart only; never compute a
  code price in the frontend.
- **No video playback yet.** Video descriptors can appear in `images[]` (`kind: "video"`); render their poster
  frame like an image until the encoder's video pipeline ships.
- **No customer accounts, no wishlists, no reviews.**

Images **do** exist: every product, card, variant and cart line carries media descriptors, and `GET /v1/site`
carries the templates that turn them into URLs. See [Images](https://api.storefront.asstio.com/docs/onboarding/reference#images) below before you render a single `<img>`.

If the user needs the confirmation mail, or a shipping step that is not the provider's, now, say this plainly before
building anything.

---

## Step 0 — Look at the catalogue before you design anything

The most expensive mistake on this API is designing against an imagined catalogue. Five minutes of
looking first saves days. Do this **before** you draw a screen or ask the user a single question.

If the shop already exists in Asstio — the usual case when someone wants a frontend built — you can run
this now with any publishable key. For a genuinely new shop there is nothing to look at yet: do Step 1
first, then come back here before designing.

```bash
KEY=sfk_pub_…                       # an existing publishable key, or mint one (1.4) and publish (1.5)
API=https://api.storefront.asstio.com
H=(-H "X-Site-Key: $KEY" -H "X-Market: se")

curl -s "${H[@]}" "$API/v1/products?pageSize=5" | jq '{total, names: [.items[].name], facets: [.facets[].key]}'
curl -s "${H[@]}" "$API/v1/collections" | jq 'length'
```

Then read the answers honestly:

| What you see | What it means for your design |
| --- | --- |
| `total` far larger than the shop's real product count, and names that read like a variant matrix — every size, colour and pack spelled out in the product name | The tenant's variants are not linked to parent products, so every SKU lists as its own product. A product grid is unusable until that is fixed in Asstio. **Raise it before building the grid, not after.** |
| `variantCount` in the hundreds or thousands on a product | Normal wherever a product has several independent axes — size × colour × pack multiplies fast. `variants` will be `null`, so plan for the paged endpoint from the start rather than as a refactor. |
| `/v1/collections` returns `[]` | There is no navigation to build. Either collections get configured (1.3) or the nav needs a different source. |
| A facet the design assumes is absent from `facets[]` | It does not exist. Render facets from the response (see [Filters](https://api.storefront.asstio.com/docs/onboarding/reference#filters)); never hard-code the ones a mock-up drew. |
| Products missing entirely | Usually no price on that market — a product with no price is not sold there and never appears. Check `get_storefront_sync_status` for `NO_PRICE` warnings. |
| `offer.stock.status: "inStock"` on very few items | Stock-driven features (sale pages, "only N left") will look empty. Check before promising them. |
| `backorder` site with no `storefront:delivery_days` values | Every out-of-stock line shows the site's backorder range. |

Also check `get_storefront_sync_status(siteId)` and actually read its `warnings` — they name the
products the catalogue is silently dropping and why.

---

## Step 1 — Create the shop in Asstio (MCP tools)

Do this yourself with the Asstio MCP tools. Do not send the user into the Purchase UI to click.

**Look things up before you ask.** Most of what you need is discoverable, and every question you ask
the shop owner is a question they may not know the answer to. `list_instances` names the instances,
`get_company_profile` the business, `list_storefront_sites` whatever already exists — an existing site
often answers market, currency and price-list questions by example. Ask only what discovery cannot settle:

1. **Which Asstio ecom site** the shop sells for (`ecomSiteId`). Verify with `list_instances` /
   `set_default_instance` first that you are on the right Asstio instance — the storefront tools act on the
   default instance and take no instance argument.
2. **Market**: its countries, its locales, and **the real future domain** of the shop.
3. **Which Asstio price list** the market prices from (`defaultPriceListId`). The list fixes the currency and the price basis.

Then, in order:

### 1.1 `save_storefront_site`

```
save_storefront_site(
  code = "moory",          # names the search index: lowercase letters, digits, hyphens, max 40 chars
  name = "Moory",
  ecomSiteId = 3,
  devOrigins = ["http://localhost:3000"],
  assortmentJson = "{\"categoryRootIds\":[100],\"excludeInactive\":true}"   # optional
)
```

`code` is effectively permanent: changing it renames and rebuilds the search index. Pick it once.

`urlPatterns` is settable here too — `{ "product": "/p/{slug}", "collection": "/k/{path}" }` by default.
**Decide it before any collection exists.** Slugs are mint-once identity with history kept, so a pattern
change later leaves every cached listing URL, canonical and sitemap entry pointing at the old shape.

`devOrigins` matters more than it looks — see [CORS](#cors-which-origins-may-call-from-a-browser).

Returns the `siteId` every other tool needs.

### 1.2 Market, locales and URLs

Classify the price list first with `set_price_list_basis`: an unclassified list is a publish finding. Then, in this
order (each save returns the `expectedDraftUpdatedAt` the next one needs):

```
save_storefront_seller(siteId = 7, country = "SE", expectedDraftUpdatedAt = …)

save_storefront_locales(siteId = 7, localesJson = '[{ "tag": "sv", "catalogLocale": "sv" }]', expectedDraftUpdatedAt = …)

save_storefront_commerce_market(
  siteId = 7, code = "se", defaultPriceListId = 12,
  countries = ["SE"], defaultCountry = "SE",
  localeMode = "primaryOnly", allowedLocales = ["sv"], defaultLocaleByCountryJson = '{ "SE": "sv" }',
  expectedDraftUpdatedAt = …
)

save_storefront_url_strategy(siteId = 7, urlStrategyJson = '{
  "mode": "none", "origin": "https://www.moory.se", "basePath": "", "omitDefaultPrefix": true,
  "defaultBinding": { "market": "se", "country": "SE", "locale": "sv" }, "originOverrides": [], "xDefault": null
}', expectedDraftUpdatedAt = …)

save_storefront_offer_policy(siteId = 7, offerPolicyJson = '{
  "offers": "public", "displayBasis": { "public": "inc", "company": "ex" },
  "companyPayment": "psp", "companyStockQuantity": false
}', expectedDraftUpdatedAt = …)
```

- Use the market tool that takes `defaultPriceListId`, `countries` and the locale policy, as above; it replaces its legacy
  namesake when that is retired. A market tool that asks for `urlTemplate`, `language` and `currency` writes the legacy
  `markets` array, which the storefront no longer reads.
- A publish compiles these into the site's **page bindings**, one per allowed market, country and locale, with the id
  `{market}/{COUNTRY}/{locale}` (`se/SE/sv`). The API builds every `url` and `alternates` entry in its responses from
  the binding, and the binding origins are what CORS allows. Use the real production domain, even before it resolves.
- **A market can hold several countries.** It has one default price list and so one currency. Tax follows the
  destination country: the seller country is domestic, and every other destination needs its rates
  (`save_storefront_tax_rates`). A country's shipping and checkout come from profiles (`save_storefront_shipping_profile`,
  `save_storefront_checkout_profile`), inherited from the site default (`save_storefront_default_profiles`).
- `offers: "verifiedCompany"` closes prices, stock and buying to signed-in, verified companies. The catalog stays public
  and shows `offerStatus: "loginRequired"`.
- Exactly one binding is the default (`defaultBinding`): it answers a request that names no market on a site with several.
- Brand pages need a brand pattern (`urlPatterns.brand`, e.g. `/varumarken/{slug}`) and a brand filter (facet source
  `{ "kind": "brand" }`).

### 1.3 Facets and collections (optional)

Skip this unless the user already knows their filter set. With no configuration at all the shop gets
**zero-config facets**: every active category root becomes a facet (a hierarchy when the tree is deep enough),
plus the built-in `price` range and `in-stock` toggle. That is a working filter sidebar on day one.

When the user does know what they want:

- `save_storefront_facet_config(siteId, key, definitionJson)` — one facet per call. `price` and `in-stock` are
  reserved keys.
- `save_storefront_collection(siteId, slugsJson, namesJson, filterJson, …)` — a collection is a listing page
  defined by a filter, with its own slug per language and its own place in the shop's tree. Use
  `{"all": []}` to match everything.

Categories are a **facet source**, never pages. List pages are collections.

### 1.4 `create_storefront_api_key`

```
create_storefront_api_key(siteId = 7, kind = "publishable", label = "Next.js frontend")
```

The raw key is returned **once and stored nowhere**. Hand it to the user immediately and tell them where to
put it (`.env.local`, then the host's secret store) — you cannot retrieve it again.

| kind | Prefix | Use it for |
| --- | --- | --- |
| `publishable` | `sfk_pub_…` | Everything a browser does. Safe in a client bundle. |
| `preview` | `sfk_prv_…` | Reads the **unpublished draft** config and preview index. Editorial preview only. |
| `secret` | `sfk_sec_…` | Server-to-server only, higher rate limit. Sent from a browser it is rejected with `SECRET_KEY_FROM_BROWSER` and gets no CORS headers. |

A Next.js app rendering on the server can use either: `secret` for server components/route handlers,
`publishable` for anything that reaches the client. When in doubt, `publishable`.

### 1.5 `publish_storefront_config` — the step that is forgotten

```
publish_storefront_config(siteId = 7, note = "initial setup")
```

**Nothing above is live until this runs.** Every save lands in the draft. A freshly minted key answers
`401 SITE_KEY_INVALID` until the config that contains it has been published — this is the single most common
"the key doesn't work" cause. Check `get_storefront_draft_diff(siteId)` first if you want to see what goes out.

The shop picks up the new version within about a minute.

### 1.6 Verify

- `get_storefront_sync_status(siteId)` — the latest indexing run: mode, outcome (`ok | gated | failed |
  cancelled`), document count, errors, warnings. The first full index of a new shop takes a while; until it
  finishes, listings are empty or `503 INDEX_UNAVAILABLE`.
- `curl -s https://api.storefront.asstio.com/v1/site -H "X-Site-Key: sfk_pub_…"` — should return the site,
  its markets, locales and `bindings`, a `configVersion` and a `media` block (`baseUrl` + four URL `templates`).
- `trigger_storefront_reindex(siteId)` exists but is normally unnecessary: indexing follows the catalogue by
  itself. Use it only when the index and the catalogue have demonstrably drifted.
- `build_storefront_preview(siteId)` builds a preview index from the draft for a `preview` key, leaving the
  live shop untouched.

### 1.7 Shopping feed (Google Merchant Center)

A merchant can send the catalogue to Google Merchant Center. The shop owner enables the Google feed per market in Asstio
(Webbutik › Kanaler) and copies the feed URL from there. The URL is a secret: share it only with the merchant's own Merchant Center.

In Merchant Center the merchant:

1. creates a **file data source** with the feed URL from Kanaler;
2. sets the **feed label** to the market code upper-cased (for example `SE`) and the **content language** to the market language (for example `sv`).

What to know:

- There is **no service account step**. Google diagnostics are deferred to a later phase, so diagnostics stay in the merchant's own Merchant Center.
- **Shipping.** If all of a market's shipping options are address-dependent (the shopper chooses a pickup point) or in-store, the feed sends no
  `g:shipping`, and the merchant must set shipping in Merchant Center.
- Backorder and short-stock items are sent as `out_of_stock`.
- Bundles are left out.
- A Google product category can be set as a category entity property whose type is named in `content.category.googleCategoryTypeId`.
- `product_type` carries the category path without the root level. `g:shipping` lists only options the shopper pays for and that are not
  pickup; collection points (ombud, paketbox) are set at account level in Merchant Center.

### 1.8 Price comparison feed (PriceRunner)

The shop owner enables the `pricerunner` feed per market in Asstio (Webbutik › Kanaler) and maps variant axes (`color`, `size`,
`material`, `pattern`) in the feed config. The file is XML (`<Products>`, one `<Product>` per variant).

1. Copy the feed URL from Kanaler. It is a secret: send it only to PriceRunner's retailer contact.
2. PriceRunner fetches the file itself; there is no account step on our side. Check the feed health on Kanaler after the first fetch.

What to know:

- **MPN is not sent.** Asstio has no MPN field; nothing is invented.
- **Pickup fees go per item.** `ShippingCost` is the lowest fee among the shopper's delivery options, including pickup points.
- Items without a SKU or with a duplicate SKU are left out; duplicate names, missing lead time, brand, category or description, and
  images below 700 px are warnings.

### 1.9 Price comparison feed (Prisjakt)

The shop owner enables the `prisjakt` feed per market in Asstio (Webbutik › Kanaler). The file is Prisjakt XML (RSS 2.0, one item per variant).

1. Copy the feed URL from Kanaler. It is a secret: paste it only in Prisjakt's Business Center (Data management › Add feed › Product feed › Prisjakt XML).
2. Prisjakt fetches the file itself. Check the feed health on Kanaler and the Business Center feed status after the first fetch.

What to know:

- **Shipping is per item**, with carrier and delivery type, including pickup options. Without a written entry, Prisjakt falls back to the shipping services set in Business Center.
- **Stock:** a variant with `Short` availability is shown as out of stock.

### 1.10 ChatGPT Ads feed (OpenAI)

The shop owner adds an `openai` feed in Asstio (Webbutik › Produktflöden): seller name, whether products may show in ChatGPT ads,
returns, the axis map and optional gender / age-group mappings. The file is OpenAI's product file schema as CSV (one row per variant).

1. Copy the feed URL. It is a secret: in OpenAI Ads Manager add a product feed with **Hosted URL** and paste it there, nowhere else.
2. OpenAI fetches the file itself. Check the feed health in Asstio and the Upload History in Ads Manager after the first upload.

What to know:

- **Stopping ads:** pausing the campaign in Ads Manager is the only immediate stop. Turning ads off on the feed reaches OpenAI only
  after the change is published, a new file is promoted and OpenAI fetches it; OpenAI keeps an item up to 2 weeks after its last refresh.
- **Required:** a product without a description or brand is left out (no generated text). A variant without distinguishing options
  in a family is sent ungrouped.
- **Stock:** `Short` availability is sent as `out_of_stock`.

---

## Step 2 — Talk to the API

### Headers

| Header | Required | Meaning |
| --- | --- | --- |
| `X-Site-Key` | yes | Which shop, and with which visibility. Missing → `401 SITE_KEY_MISSING`; unknown or revoked → `401 SITE_KEY_INVALID`. |
| `X-Market` | no | Market code, e.g. `se`. Omitted → the site's only market, else the default binding's market, else `400 MARKET_REQUIRED`. Unknown or inactive → `400 MARKET_NOT_FOUND`. |
| `X-Country` | no | ISO country, e.g. `DE`. Omitted → the market's only country; on a market with several, a catalogue read uses its default country, and cart creation and checkout answer `400 COUNTRY_REQUIRED`. Not in the market → `400 COUNTRY_NOT_ALLOWED`. |
| `X-Locale` | no | Locale tag as the site spells it, e.g. `sv`. Omitted → the country's default locale. Not allowed there → `400 LOCALE_NOT_ALLOWED`. |
| `X-Shopper-Session` | no | A signed-in shopper's session, server-to-server with the server key only. The request then resolves with that shopper's prices and offer. A bad session is `401 SESSION_INVALID` on every route, never a silent anonymous answer. |
| `Accept-Language` | no | Selects nothing. Only `GET /v1/site` reads it, to fill `suggestedLocale` for a locale picker. |

**Take `X-Market`, `X-Country` and `X-Locale` from the page's binding** (`GET /v1/site` → `bindings[]`), not from the
browser. A response states what it was built for in `context` (`market`, `country`, `locale`, `currency`,
`customerKind`) on the site, listing, product and cart answers. A price that cannot be resolved yet is an answer, not a
fallback: `503 PRICE_CONTEXT_NOT_READY` (with `Retry-After`) or `503 PRICE_CONTEXT_UNAVAILABLE`, on any catalogue read.

**The tenant and the commerce context are never in an API path.** Every shop calls the same paths; the key decides
which catalogue answers. Responses carry `X-Config-Version` (which published config produced the answer) and an
`ETag`.

### Minimal call, no SDK

```ts
const BASE = "https://api.storefront.asstio.com";

async function storefront<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    ...init,
    headers: {
      "X-Site-Key": process.env.STOREFRONT_SITE_KEY!,
      "X-Market": "se",
      "X-Country": "SE",
      "X-Locale": "sv",
      ...init.headers,
    },
  });
  if (!res.ok) {
    const problem = await res.json();       // application/problem+json
    throw new Error(`${problem.code}: ${problem.detail ?? res.status}`);
  }
  return res.json() as Promise<T>;
}

const listing = await storefront("/v1/products?q=parfym&page=1&pageSize=24&sort=price_asc&filter[brand]=dior,chanel");
```

### The typed SDK

`@asstio-dev/storefront` is a generated TypeScript client for this API: the same headers, typed paths,
typed responses and typed error codes. Prefer it over hand-rolled `fetch` in a TypeScript project.

```bash
npm install @asstio-dev/storefront
```

```ts
import { createStorefrontClient, filterQuery, encodeFilterValues, decodeFilterValues } from "@asstio-dev/storefront";

const storefront = createStorefrontClient({
  baseUrl: "https://api.storefront.asstio.com",
  siteKey: process.env.STOREFRONT_SITE_KEY!,   // publishable in the browser, secret only on a server
  market: "se",
  country: "SE",
  locale: "sv",
});

const { data, error } = await storefront.GET("/v1/products", {
  params: { query: { q: "parfym", page: 1, pageSize: 24, sort: "price_asc",
                     filter: filterQuery({ brand: ["dior", "chanel"], price: "100-500" }) } },
});

if (error) throw new Error(`${error.code}: ${error.detail ?? ""}`);   // error.code is typed
```

The client sets `X-Site-Key` and the context you give it (`X-Market`, `X-Country`, `X-Locale`), so you never pass them by
hand. The context is fixed when the client is built: leave out what the API may resolve, or pass a page binding instead of the three
values (`binding`, one of `bindings[]` from `GET /v1/site`), and make one client per context.
`filterQuery()` encodes multi-select values (see [Filters](https://api.storefront.asstio.com/docs/onboarding/reference#filters)) and drops `undefined` ones; `filter` goes on
the wire as `filter[brand]=dior,chanel`. The package also exports the media URL helpers (`pictureSources`, `mediaUrl`,
`srcSet`, `posterUrl`, `fileUrl`, `videoSources`) — see [Images](https://api.storefront.asstio.com/docs/onboarding/reference#images) — and the `MediaDescriptor` /
`MediaConfig` types.

In another language, or without the package: the OpenAPI document is the contract and the SDK is generated
from exactly that snapshot, so generate your own types from it.

```bash
npx openapi-typescript https://api.storefront.asstio.com/openapi/v1.json -o src/storefront-schema.d.ts
```

### CORS: which origins may call from a browser

The API allows exactly two sets of origins, both derived from the shop's own published configuration:

1. the origin of every page binding of an active market, and
2. everything listed in the site's `devOrigins`.

So `http://localhost:3000` **must be in `devOrigins`** (via `save_storefront_site`, then published) or local
browser development fails at the preflight. Server-side rendering is unaffected — CORS is a browser rule.

**`save_storefront_site` replaces every field of the site, and its read does not return them all.** On a site that
already exists, a save from you would blank the site's assortment and URL patterns (and any `devOrigins` you leave
out). Ask the operator to make the change, or pass every field explicitly from the live version. On a new site there
is nothing to lose.

### Rate limits

600 requests/minute per publishable or preview key, 6000 for a secret key, 60 per IP for calls carrying no
valid key. Over the limit is `429 RATE_LIMITED` with `Retry-After` and `retryAfterSeconds` in the body. Limits
are per key, so a server-rendered site behind one key shares one budget — cache.

### Caching

Successful reads carry `ETag`, `Cache-Control: public, max-age=60, stale-while-revalidate=300` and
`Vary: X-Site-Key, X-Market, X-Country, X-Locale` (`GET /v1/site` adds `Accept-Language`). Send the ETag back as
`If-None-Match` for a `304`. Draft (preview-key) responses and every answer to a request with a session are
`private, no-store`; errors are `no-store` and never carry an ETag.

Do not put a shared CDN cache in front of catalogue responses in v1 — the answer depends on all four headers,
and a cache that mis-keys them serves one shop's page to another.

---

## Step 3 — Recommended stack

**Start from [`asstio-shop-starter`](https://github.com/hcbs/asstio-shop-starter)** (public; no GitHub account
needed: `git clone https://github.com/hcbs/asstio-shop-starter.git`). It is a working reference storefront on
this API — four screens, no design, no shop-specific logic. Copy it and build on top, or read it to see what the
API expects of a frontend. It already implements the three things most often got wrong: facets rendered from the response
with no facet key in the code, errors branched on `code`, and historical slugs turned into `301`s. It also shows the current
practice: `@asstio-dev/storefront` from npm (its README names the version it is built against), `/v2` listings whose cards
carry their own variants, prices through `priceDisplay`, heads and `sitemap.xml` from the SDK's SEO helpers, and every point of
[A fast and reliable server-rendered frontend](#a-fast-and-reliable-server-rendered-frontend) below.

**Next.js (App Router) + TypeScript, Server Components for listing and detail pages.** Not a requirement — the
API is plain HTTP and stack-agnostic — but it is what the Asstio ecosystem is built and tested against:

- A public shop needs server rendering for SEO; listing and detail responses are exactly the SSR payload.
- The site key stays on the server when you render there.
- The generated client is TypeScript, and the OpenAPI document types any TS codebase today.
- `/v1/sitemap` is built for `sitemap.xml` and for selective revalidation (ISR/`revalidateTag`): `?since=` lists
  what changed for revalidation, and cursor mode (`?cursor=start`, then each `nextCursor` until `null`) walks the
  whole catalog for a full crawl, with no 10 000-row ceiling.

Suggested shape:

| Route | Call |
| --- | --- |
| `/` | `GET /v1/collections` for navigation, `GET /v2/products?sort=newest&include=variants` |
| `/[collection-path]` | `GET /v2/collections/{slug}` — collection, breadcrumb, listing, hreflang in one call |
| `/search` | `GET /v2/products?q=…` — same `ListingV2Response` shape, so one component renders both |
| `/p/[slug]` | `GET /v1/products/{slug}`, then `/variants` when `variants` is `null` |
| `/sitemap.xml` | The SDK's `sitemapEntries` + `toNextSitemap` (cursor walk of `GET /v1/sitemap` for `type=product`, `collection` and `brand`; BCP 47 hreflang) |

Build URLs from the API's own `url` and `alternates` fields (they come from the page bindings), and make your
route pattern match the shop's `urlPatterns` and the binding's `prefix` from `GET /v1/site`.

`alternates` is a list of `{ bindingId, market, country, locale, hreflang, url }`, indexable bindings only. Take the
tag from `hreflang`, never from a market code (`hreflang="se"` is Northern Sami, not Swedish). A secondary binding
(`indexable: false`) is `noindex,follow` and has no alternates. Use the SDK: `productHead`/`collectionHead`/`brandHead`
for page heads, `sitemapEntries` with the page's `binding` for `sitemap.xml`.

### A fast and reliable server-rendered frontend

These are lessons from shops already running on this API. Each one cost a live shop API calls, bytes or failed requests
before it was fixed. Budget: aim for one API call per page view on a warm cache, never one per product shown.

- **Turn off Node's address-family race (Node 20+).** Call `net.setDefaultAutoSelectFamily(false)` once at server start,
  for example in Next's `instrumentation.ts` `register()` on the `nodejs` runtime. The API host has an IPv4 and an IPv6
  address. Node gives the IPv4 attempt 250 ms on a JS timer. When a server render blocks the event loop past that,
  Node drops the IPv4 connect even if it already succeeded. IPv6 then fails in a container without IPv6 egress (Scaleway
  serverless has none), and `fetch` throws `TypeError: fetch failed` with cause `AggregateError` and code `ETIMEDOUT`. The
  request never leaves your server, so the API never logs it. One shop saw about 30 a day, more at every API deploy.
  The SDK does not do this for you: it is a process-wide setting, and a library must not change it.
- **Keep data reads out of the root `not-found.tsx`.** Next renders the root not-found boundary into every page's RSC
  payload, not only on a 404. A product list or any other read there runs, and is sent, on every page. One shop
  carried a 404 "popular products" list on every page: about 25 KB per page and one extra read. Render the 404's extras only
  where the 404 is actually shown (a dedicated route for unmatched URLs, or client-side after mount).
- **A list of products carries what its cards need.** Read listings with `GET /v2/products` (or `/v2/collections/{slug}`)
  and `include=variants` (plus `categories` when the card needs them). Each card then has its own variants, offers,
  options and swatch attributes. Never read `GET /v1/products/{slug}` per card to find a cheapest size or the shades. A
  list of 24 cards with per-card reads is 25 calls. Only a card whose `variantCount` is larger than its `variants` list
  (more than 12 variants) needs its product read.
- **Facet value lists: read the v2 facet, page it, and hold it.** For a brand A–Z page, or to map a label to its filter
  key, use `GET /v2/products/facets/{key}?pageSize=300` and page with `page`/`total`. Hold the result in server memory for
  minutes; it changes only on a catalogue update. Do not sweep the v1 facet letter by letter or search it per page view.
- **"More from this series/category" on a product page.** A product's `categories` carry id, name and path but not the
  facet's filter key. Map the category's name to the key through the held facet list (above). The facet's `count` also
  tells you when the category holds only this product, so you can skip the listing read. Then do one listing read with
  `include=variants`.
- **Start independent reads together.** The product, the site and the side lists of a product page do not depend on each
  other. `Promise.all` them instead of awaiting one after the other. Each serial await adds a full API round trip
  to the page.
- **Cache answers yourself, for at most 60 seconds.** Next's Data Cache (`fetch` with `next: { revalidate }`) can serve an
  expired entry of any age to the first reader after expiry, so a page could show a price after its sale ended. Read with
  `cache: "no-store"` behind your own memo that keeps an answer until `min(fetchedAt + 60 s, X-Price-Valid-Until)` and never
  keeps a `private` or `no-store` one (the SDK README, "Revalidation"; `lib/api-memo.ts` in the starter is one).
- **Measure, then change.** Count the outgoing calls per page (Node's `diagnostics_channel` `undici:request:create` gives one
  event per real network call; a Data Cache hit makes none). Compare the rendered HTML before and after any change meant
  to be invisible.

---

## When it looks broken

Most "the API is broken" moments are one of these.

| Symptom | Cause | What to do |
| --- | --- | --- |
| A brand-new key answers `401 SITE_KEY_INVALID` | The config carrying it was never published | `publish_storefront_config(siteId)`, then allow about a minute for the registry to pick it up. A key is inert until then. |
| Everything 401s for a minute after publishing | Registry cache | Retry. It resolves itself. |
| Your server logs `fetch failed` with `AggregateError`, code `ETIMEDOUT`, often several within a second, and the API's logs show nothing at that time | Node's address-family race dropped the IPv4 connect while a render blocked the event loop; IPv6 has no route from the container | `net.setDefaultAutoSelectFamily(false)` at server start ([Step 3](#a-fast-and-reliable-server-rendered-frontend)). |
| `503 INDEX_UNAVAILABLE` / `SITE_REGISTRY_WARMING` | Index rebuilding, or first build unfinished | Retry, and render a "rebuilding" state rather than an error page. Both are expected during an index swap. |
| `503 PRICE_CONTEXT_NOT_READY` after a publish | The new context is built with the next catalogue generation | Retry per `Retry-After`. Persistent → the operator checks `get_storefront_sync_status`. |
| Every price is `null` and `offerStatus` is `loginRequired` | The site sells to verified companies; the request has no such session | Expected. Show the sign-in prompt, and send prices only through a shopper client on the server. |
| `get_storefront_sync_status` shows `documentCount: 0` | On a **delta** run this means *nothing changed*, not *the index is empty* | Read `mode` before reading `documentCount`. Only a `full` run's count is the index size. |
| `outcome: gated` | A safety gate refused to swap the alias — usually the document count dropped far enough to look like data loss | **It does not retry.** A gated run needs a human: confirm the drop is real (a genuine catalogue shrink after a data fix), then re-run. The new indices are kept unaliased for inspection. |
| `outcome: failed` | A real error; `warnings` carries it | Retried automatically with backoff. |
| The listing is full of SKU-level rows | Tenant variants are not linked to parents | An Asstio-side data fix, not a frontend one. See [Step 0](#step-0--look-at-the-catalogue-before-you-design-anything). |
| A product 404s that you can see in Asstio | No price on the requested market, or it is a variant of another product | Variants are not addressable on their own — only their parent is. |
| A filter you sent did nothing | Unknown facets are a `warning`, not an error | Read `warnings[]` on the 200 and show it. The page never blanks for a bad filter. |
| `POST /v1/checkout` answers `503 CHECKOUT_UNAVAILABLE` after a publish | The API or the worker has not picked up the option or the account yet, or the account is disabled | Wait 90 s; then [Checkout 4.3](https://api.storefront.asstio.com/docs/onboarding/checkout#43-readiness-you-can-observe). Persistent → the operator (account enabled? worker order token?). |
| `400 ORIGIN_NOT_ALLOWED` on a preview host | The host is not in the published `devOrigins` | The operator adds it ([Checkout 4.2 step 4](https://api.storefront.asstio.com/docs/onboarding/checkout#42-configure-in-order)), then publish. |
| The shopper paid, but no order appears in Purchase, and `list_storefront_order_exports` has no row for it | No intake config: Purchase refuses before storing a row; the storefront keeps the export `pending` (`INTAKE_NOT_CONFIGURED`) and retries hourly | `save_storefront_intake_config` ([Checkout 4.2 step 3](https://api.storefront.asstio.com/docs/onboarding/checkout#42-configure-in-order)); the waiting export goes through at its next retry. `get_storefront_order_flow` shows it under `orders.export.pending`. |
| The widget stays greyed out after a cart change | A widget action hung (Checkout part, 4.5) | Bound the callbacks; recover by full navigation. |
| The checkout page or the waiting page spins for good | A rejected Server Action call raced against a deadline (Checkout part, 4.5) | Turn the rejection into a problem before the race. |
| After paying, the header shows an empty cart and the order page cannot be reached again | A cart reader dropped the cookie on a `410` (Checkout part, 4.4 item 7) | Ask `POST /v1/checkout` before dropping it. |

---

## Where to go deeper

- **The full design and decision log:** `docs/superpowers/specs/2026-09-10-storefront-design.md` in the
  `asstio-storefront` repository — why things are the way they are, including everything not built yet.
- **The contract itself:** `GET /openapi/v1.json`, browsable at `GET /docs`.
- **Asstio's own data API** (orders, customers, stock, and everything Purchase owns): `PUBLIC_API.md` in
  `asstio-order-backend`.

Ask the Asstio team before designing around anything this document lists as not built.
