npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@asstio-dev/storefront

v0.61.0

Published

Typed client for the Asstio Storefront API (generated from OpenAPI).

Readme

@asstio-dev/storefront

Typed client for the Asstio Storefront API. The types are generated from the OpenAPI document committed at tests/Storefront.Api.Tests/Snapshots/openapi-v1.json, which is the contract: it only changes in a deliberate commit, so a change here always shows up in a diff.

npm install @asstio-dev/storefront

Setting a shop up in the first place — the Asstio-side MCP calls, the API key kinds, CORS, the filter and price model — starts at docs/PUBLIC_STOREFRONT_ONBOARDING.md (with the checkout and contract-reference parts beside it), served publicly at https://api.storefront.asstio.com/docs/onboarding. This file is only about using the package.

import { createStorefrontClient, filterQuery, requireBinding } from "@asstio-dev/storefront";

// Your key: process.env.STOREFRONT_SITE_KEY on a server, import.meta.env.VITE_… in a bundler.
declare const STOREFRONT_SITE_KEY: string;

const storefront = createStorefrontClient({
  baseUrl: "https://api.storefront.asstio.com",
  siteKey: STOREFRONT_SITE_KEY, // publishable in the browser, secret only on the 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", size: undefined }),
    },
  },
});

if (error) throw new Error(`${error.code}: ${error.detail ?? ""}`);
console.log(data.total, data.items, data.warnings);

A client's context is fixed when it is built, so a site with several contexts has one client per context. Leave out what the API may resolve (see Headers), or pass a page binding from GET /v1/site instead of the three values:

const { data: siteInfo } = await storefront.GET("/v1/site", {});
const germanInSwedish = createStorefrontClient({
  baseUrl: "https://api.storefront.asstio.com",
  siteKey: STOREFRONT_SITE_KEY,
  binding: requireBinding(siteInfo!, "eur/DE/sv"),   // sends X-Market: eur, X-Country: DE, X-Locale: sv
});
// A product with many variants comes back with variants: null and a variantCount; page them:
const { data: page } = await storefront.GET("/v1/products/{slugOrId}/variants", {
  params: { path: { slugOrId: "manadslins" }, query: { filter: { power: "-1.00" } } },
});
// page.options[].values[].available drives cascading dropdowns: a value reached through the cascade is
// available, but honour the flag for hand-built URLs or restored state, which can select an unavailable one.

Every example in this file is compiled as part of npm run check — the source of them is examples/readme.ts, which also covers product lookup, ETag revalidation, crawling, and image formats.

Images

Products, cards, variants and cart lines carry media descriptors, never URLs. Combine a descriptor with the media block of /v1/site to build src, srcset and <picture> sources. The helpers only ever produce a URL the CDN actually serves: a width and a format the descriptor announces, and the descriptor's own recipe.

import { pictureSources, fileUrl } from "@asstio-dev/storefront";

const { data: site } = await storefront.GET("/v1/site");
const { data: product } = await storefront.GET("/v1/products/{slugOrId}", { params: { path: { slugOrId: "acuvue-oasys" } } });

if (site && product?.image) {
  const { sources, img } = pictureSources(site.media, product.image, "(min-width: 900px) 33vw, 100vw");
  // <picture>{sources.map(s => <source {...s} />)}<img {...img} alt={product.image.alt["sv"] ?? product.name} /></picture>
}
for (const file of product?.files ?? []) console.log(file.filename, fileUrl(site!.media, file));
// A variant with hasOwnImages: false inherits: variant.hasOwnImages ? variant.images : product.images

videoSources returns [] for anything that is not a video, while mediaUrl/pictureSources/fileUrl/posterUrl throw MediaUrlError when the descriptor cannot produce that URL — branch on kind before calling.

Image formats

A site's formats (site.media.formats: card, gallery, thumb, cart, swatch, default, plus custom keys) say how an image is framed: aspect, fit (contain · cover · natural), padding and a background per bg class. They are published with the site, so the look changes without a frontend deploy. formatImage turns a descriptor and a format key into everything a <picture> needs:

import { formatImage } from "@asstio-dev/storefront";

const f = formatImage(site.media, product.image, "card", [
  { media: "(min-width: 1080px)", size: "25vw" },   // your slot's width per breakpoint
  { size: "100vw" },                                // the last one without a media condition
]);
// React:
// <div className={styles.cardImage}>                                  ← your slot: your class, may be a flex/grid item
//   <div style={f.box}>                                               ← the aspect frame, the slot's only child
//     <canvas ref={blurhashCanvas} style={f.placeholder} />           ← optional placeholder, same rectangle as the image
//     <picture>
//       {f.sources.map((s) => <source key={s.type} {...s} />)}
//       <img {...f.fallback} style={f.img} alt={alt} loading="lazy" />
//     </picture>
//   </div>
// </div>

Plain HTML (templating):

const f = formatImage(site.media, product.image, "card", [
  { media: "(min-width: 1080px)", size: "25vw" },
  { media: "(min-width: 640px)", size: "50vw" },
  { size: "100vw" },
]);
// alt is merchant text, not SDK output: escape it for the attribute.
const escapeAttr = (s: string) => s.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
const alt = escapeAttr(product.image.alt["sv"] ?? product.name);
// Your slot owns the width; box is its only child in every fit:
const picture =
  `<picture>${f.sources.map((s) => `<source type="${s.type}" srcset="${s.srcSet}" sizes="${s.sizes}">`).join("")}` +
  `<img src="${f.fallback.src}" srcset="${f.fallback.srcSet}" sizes="${f.fallback.sizes}" width="${f.fallback.width}" height="${f.fallback.height}" alt="${alt}" loading="lazy" style="${styleToCss(f.img)}"></picture>`;
const placeholder = `<canvas width="32" height="32" style="${styleToCss(f.placeholder)}"></canvas>`;
const html = `<div class="card-image"><div style="${styleToCss(f.box)}">${placeholder}${picture}</div></div>`;
  • Element contract. Your slot element owns the width (grid, flex, className); it may be stretched. Put the box inside it as its only child and give the box no padding, border or height of its own — its inline styles pin its geometry, so a stretched slot never distorts the format's aspect.
  • One rectangle. img and placeholder are the same absolutely positioned rectangle with object-fit: fill, computed from the descriptor: a blurhash canvas of any decode size is stretched to exactly where the image will paint. The box's backgroundColor shows around a contain image and through transparent AVIF/WebP.
  • Natural has a box too, at the image's own aspect and without a colour; img and placeholder fill it. So the layout is reserved before load in every fit, and the placeholder sits under the image the same way.
  • sizes is your slots scaled by the image's drawn fraction with calc(); srcset keeps the real widths, so the browser downloads a sharp enough rendition for a cover crop and not a wasted one for a padded packshot.
  • formats: null (a site without formats) or an unknown key falls back to default, then to natural; your own CSS keeps working. focal (set per placement in Asstio) positions a cover crop; showWhole renders a cover format as contain for that image. formatImage throws MediaUrlError for video descriptors, file descriptors, a descriptor without w/h, a descriptor without renditions, or an empty slots array.
  • Plain HTML: see the templating example above, or the compiled function productCard in examples/readme.ts. styleToCss(f.box) gives the style attribute value for any element. Escape anything that is not SDK output (alt, product names) before it goes into markup; the React example needs no escaping because React escapes attribute values.

Product content

description is already sanitized on the server: render description.html as-is — do not sanitize, escape or re-parse it — and use description.text wherever you need plain text (a meta description, a snippet, an aria-label). shortDescription is plain text. brand is the product's brand (the main product's); every variant in variants[] and on /variants carries its own brand and responsible — render the selected variant's. brand.facet links a filtered listing (filter[facet.key]=facet.valueKey) when the shop has a brand filter. brand.url is the brand page on this market and is null whenever that page would not exist here (brand pages off, or nothing of the brand sold on this market) — then render the label (and brand.logo) without a link; never build a brand URL yourself.

attributes[] arrives ordered and labelled for display. Branch on type (text | html | number | bool | list): a list fills values, everything else fills value, and html fills html too — sanitized exactly like description.html.

if (product.description) render(product.description.html); // as-is: sanitized server-side
for (const a of product.attributes) {
  if (a.type === "html") render(a.html!);          // sanitized like description.html
  else if (a.values) render(a.values.join(", "));  // type: "list"
  else render(a.value!);                           // text | number | bool
}

A variant has its own attributes[] of the same shape, holding only what that variant has of its own (a shade, a strength): it inherits nothing, is always an array and is [] on a single product. Read the selected variant's list first and the product's after it. The merchant maps these in Asstio, so branch on type and, if you want a special widget, on a key you have seen in a response. facetKey and valueKeys are always null on a variant, and a value is free text the platform does not validate:

const own = variant.attributes ?? [];                       // [] when the variant has none
const isSwatch = (a: (typeof own)[number]) =>
  a.key === "storefront-color" && /^#[0-9a-f]{6}(,#[0-9a-f]{6})*$/i.test(a.value ?? "");
for (const a of own) {
  if (isSwatch(a)) renderSwatch(a.value!.split(","));       // several colours are comma-separated
  else renderRow(a.label, a.value ?? a.values?.join(", ")); // anything else, a free-text colour included
}

facetKey and valueKeys turn an attribute's values into filter links — filter[facetKey]=valueKeys[i], aligned index-for-index with values (or carrying the single value's key). valueKeys is absent entirely when any one value has no key of its own: a list is either fully linkable or not linkable at all.

related[] holds groups of cards already resolved for this market, and bundle.components[] the cards a bundle is made of; both leave out anything that no longer exists or is not sold here.

Brands and responsible parties

responsible is { manufacturer, importer, euResponsiblePerson }, each a party or null. Show the selected variant's on the product page (EU GPSR manufacturer and responsible-person contact data). null means nothing applies for this SKU: do not fall back to the product's or the brand's. phone is only present when the shop publishes it.

Brand pages: GET /v1/brands lists the brands with a page on this market (paged, by name); GET /v1/brands/{slugOrId} returns the brand's name, description (sanitized like product descriptions), logo, website, its default parties and facet — render the listing with GET /v1/products?filter[<facet.key>]=<facet.valueKey>. A redirectTo means 301 to that slug. GET /v1/sitemap?type=brand lists them for sitemap.xml.

const { data: brand } = await storefront.GET("/v1/brands/{slugOrId}", { params: { path: { slugOrId: "hugo-boss" } } });
if (brand?.redirectTo) redirect(301, `/varumarken/${brand.redirectTo}`);
const { data: listing } = await storefront.GET("/v1/products", {
  params: { query: { filter: filterQuery({ [brand!.facet!.key]: [brand!.facet!.valueKey] }) } },
});

Prices and buying

Every card, product and variant carries an offer. Render it with three helpers instead of reading its fields:

import { displayPrice, isBuyable, type OfferDto } from "@asstio-dev/storefront";

export function buyBox(offer: OfferDto) {
  // The offer's displayBasis side of its pair: ex for a dealer, inc for a consumer. Null means "show no price", never 0.
  const price = displayPrice(offer);        // { amount: "100.00", basis: "ex", currency: "SEK" }
  return {
    label: price ? `${price.amount} ${price.currency} ${price.basis === "ex" ? "excl. VAT" : "incl. VAT"}` : null,
    canBuy: isBuyable(offer),
  };
}
  • displayPrice is null when offerStatus is not available (render loginRequired as "Sign in for prices"), and when the pair lacks the side to show. It never falls back to the other side or computes an amount. isPriceVisible(offer) is whether it has an amount.
  • isBuyable is offerStatus and purchaseStatus both available. purchaseStatus already folds in permission, freshness, sellability and a complete price, so a partial price can be visible and still not buyable. Never decide it from stock: the API sends no public stock quantity, and zero stock is buyable on a backorder site.

Sales, the 30-day price and the RRP

While a sale applies, an offer carries regular, sale ({ price, validFrom, validTo, label, extendedFrom }), reference (the lowest price of the 30 days before the reduction) and, when the shop may say so, a claim ({ labelKey, percent, amountOff, since, endsAt, claimEndsAt }). Render every price through priceDisplay, on the request, with the request's time, instead of reading these fields:

import { priceDisplay } from "@asstio-dev/storefront";

const d = priceDisplay(variant.offer, { now: new Date(), locale: "sv" });
// endsAt is exclusive: show the date of its last second in the site's time zone.
const lastDay = (endsAt: string) =>
  new Date(Date.parse(endsAt) - 1000).toLocaleDateString("sv-SE", { timeZone: "Europe/Stockholm" });
<span data-price-part={d.parts.price}>{d.price?.amount}</span>
{d.struck && <span>{d.struck.label} <s data-price-part={d.parts.struck} title={d.struck.longLabel}>{d.struck.amount}</s></span>}
{d.badge && <span data-price-part={d.parts.badge}>{d.badge}</span>}   {/* "−20 %", a no-break space before % */}
{d.rrp && <span data-price-part={d.parts.rrp}>Rek. pris {d.rrp.amount}</span>}
{d.endsAt && <time data-price-part={d.parts["ends-at"]} dateTime={d.endsAt}>t.o.m. {lastDay(d.endsAt)}</time>}
  • A page may be served from a cache past a sale's end. priceDisplay drops a sale whose validTo ≤ now (it shows regular) and the offer's claim with it, and drops a claim whose endsAt or claimEndsAt ≤ now. An open-ended sale (validTo null) is never dropped by now, and endsAt is then null: show no end.
  • endsAt is the exclusive end (the first second the sale no longer applies). Show the date of endsAt − 1 s in the site's time zone (lastDay above), as productJsonLd does for priceValidUntil; a sale ending at midnight ends "t.o.m." the day before.
  • Only struck is struck: the claim's reference, with the claim's label (priorLowest: "Tidigare lägsta pris", long form "Lägsta pris de senaste 30 dagarna före prissänkningen"; English for other locales; override with texts). Never strike regular, compareAt or unitPriceBeforePromotions. A reference without a claim shows nothing.
  • The RRP (compareAt) is never shown while a sale applies, with or without a claim. With no sale and no claim it shows as before. It is never struck.
  • Two places can disagree: a listing card whose price segment has two sale owners carries sale: null, so its RRP can show on the card while the variant page shows a sale and hides it. That is expected; the card has no sale to show.
  • The optional members (reference, claim, sale.label, sale.extendedFrom) may be absent from a response: read them as x ?? null, as priceDisplay does.

Lines. linePriceDisplay(line, { now, currency }) does the same for a cart, checkout or order line's unit price: a line's claim strikes its reference whether or not the product is on sale (a code that beats the sale still shows a true percent). Cart lines are live (a claim past its end drops); checkout and order lines carry the order's evidence and are never dropped by now. currency (the checkout's or order's) is required for checkout and order lines, whose unit price is an inc string; without it the line shows no price. An item promotion effect in cart.promotions (stage: "item") is data: never render it as a discount row, and never show subtotalBeforePromotions while one is present; the struck price comes only from a line's claim. A code line with no claim shows the code's reduction as a discount row, as before.

Revalidation. A cached page that shows prices must not outlive the next price change. nextRevalidateSeconds(site, now) is the seconds until site.nextPriceBoundary, at most 60 and at least 1. It is not a value for Next's export const revalidate or fetch(…, { next: { revalidate } }): the Data Cache can serve an expired entry of any age (C10). Use it for a cache you control, such as the memo below:

const { data: site } = await storefront.GET("/v1/site", {});
const seconds = nextRevalidateSeconds(site!, new Date());   // the lifetime of your own memo entry

Catalog answers of a site with an item promotion carry X-Price-Valid-Until. A frontend never shows a catalog answer more than 60 s after it fetched it, nor past that header. Next's Data Cache (fetch with revalidate) can serve an entry of any age to the first reader after expiry, so read catalog endpoints with cache: "no-store" behind your own memo with the lifetime min(fetchedAt + 60 s, X-Price-Valid-Until), and never store a response whose Cache-Control holds private or no-store.

JSON-LD. Pass now to productJsonLd: each offer's price is then the price charged at now, and a live sale with an end adds priceValidUntil (the date of its last second in timeZone, default Europe/Stockholm).

Code reasons. codeReasonText(code.reason, locale) gives a default text for a code that does not apply, e.g. superseded → "Ett bättre erbjudande gäller redan".

Variant names

variant.name (on VariantDto, cart lines' variant and checkout/order lines' variant) is the variant's own name from Asstio, for example "Boss Bottled Eau de Parfum 50 ml". It is null for a variant without a name, until the site's index has been rebuilt on the release that added it, on a cart line whose catalogue facts could not be read, and on frozen checkout lines and order lines (only an open checkout's lines resolved live carry it). Fall back like this:

  • product page and cart: variant.name ?? product.name, plus variant.selectedOptions;
  • checkout and order lines: line.variant.name ?? line.name, plus line.options (the line's product block has no name).

Variant links

A link to one variant is the product URL plus ?variant={variantId} (the id from variants[].id); variant.url is that link ready-made, null when the variant has no price on the market. Read the parameter on the server, pass it to the API, and render by selectedVariantStatus:

const raw = (await headers()).get("x-search") ?? "";           // the raw search string, e.g. set by middleware
const param = readVariantParam(raw);                   // absent | id | invalid
const { data: product } = await storefront.GET("/v1/products/{slugOrId}", {
  params: { path: { slugOrId: slug }, query: { variant: variantQueryForApi(param) } },
});
if (product?.redirectTo) permanentRedirect(redirectTarget(product.url!, raw));   // 308; keeps ?variant= and UTM as received
// product.selectedVariantStatus: null (absent: your default), "matched" (preselect product.selectedVariant),
// "notSoldHere" (show it as unavailable here, preselect nothing), "unknown" (note that it is gone, preselect nothing).
if (!product) notFound();
const ld = productJsonLd(product, { site, binding: "se/SE/sv" });

Pass the raw search string to readVariantParam and redirectTarget when you can (for example from a middleware header): a Next.js searchParams record is accepted too, but it loses the interleaving of different keys. Canonical stays the product url. Never a 404 while the product resolves. If you have variant ids but no v.url (for example a cart line), variantUrl(product.url, product.id, variantId) builds the same link; the parameter name is exported as VARIANT_PARAM. The full contract is in the onboarding guide, "Variant links".

SEO

Pure helpers that compute schema.org JSON-LD and <head> data from the DTOs. They render nothing: your frontend writes the markup. No backend call, no DOM, no dependency.

Product JSON-LD. productJsonLd returns a Product (one variant) or a ProductGroup with one Product and Offer per variant sold in the page's context. Each variant's link is v.url from the API (see Variant links above), so no variantUrl hook is needed; pass one only to override it. Google needs a distinct URL per variant, and opening that URL must preselect the variant on your page. productJsonLd reads product.selectedVariant itself. variesBy maps your option names to size, color, material or pattern; unmapped options still name the variants. A product with more than 100 variants arrives with variants: null: pass the first /variants page as variants, or the product gets no offer (valid schema.org, but not eligible for product rich results).

const ld = productJsonLd(product, {
  site, binding: "se/SE/sv",   // the site.bindings id the page was requested on
  variesBy: { Storlek: "size", Färg: "color" },
});
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdScript(ld) }} />

In a plain template: <script type="application/ld+json">${jsonLdScript(ld)}</script>. jsonLdScript escapes <, >, &, U+2028 and U+2029, so merchant text cannot end the script element; never use plain JSON.stringify there.

Breadcrumbs. On a collection page, r.breadcrumb holds the ancestors only. Add the collection itself as current:

const crumbs = breadcrumbJsonLd(r.breadcrumb, { home: { name: "Hem", url: "https://moory.se/" }, current: r.collection });
// null below two items (Google's minimum): render nothing then.

Head. productHead, collectionHead (takes your own description; the API has none for collections) and brandHead return a framework-neutral SeoHead: title, description (cut at 160 characters on a word boundary), canonical (the page's own URL on its binding, base path and prefix included), robots: "noindex,follow" on a secondary (non-indexable) binding, hreflang alternates (the API's alternates: the indexable bindings where the page exists publicly, x-default from the site's default binding; override with xDefault: "<binding id>" or false; none on a secondary binding), and Open Graph / Twitter meta. binding is the site.bindings id the page was requested on (its X-Market, X-Country and X-Locale). titleTemplate: "%s | Moory" applies to <title> only, never to the social titles. In Next.js:

export async function generateMetadata(): Promise<Metadata> {
  return toNextMetadata(productHead(product, { site, binding: "se/SE/sv", titleTemplate: "%s | Moory" }));
}

Titles come out as { absolute } on purpose, so a layout's title.template does not apply a second time.

Sitemap. sitemapEntries reads every sitemap URL of one binding: GET /v1/site, then for each type (product, collection, brand; default all three) a cursor walk of GET /v1/sitemap?binding= from cursor=start along nextCursor, with no 10 000-row ceiling. since (optional) limits it to entries changed at or after a timestamp. A secondary (non-indexable) binding has an empty sitemap. toNextSitemap turns the result into Next.js's app/sitemap.ts shape:

import type { MetadataRoute } from "next";

export const dynamic = "force-dynamic";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const binding = process.env.STOREFRONT_BINDING!;          // a site.bindings id, e.g. "se/SE/sv": one sitemap per binding
  const api = createStorefrontClient({ baseUrl: API_URL, siteKey: SITE_KEY });
  const result = await sitemapEntries(api, { binding });
  if (!result.complete) console.warn("Sitemap: incomplete walk");
  return toNextSitemap(result);
}
  • binding is required and must be one of site.bindings; an unknown one throws SeoError before any page is read.
  • hreflang tags are the bindings' compiled tags (sv-SE, en-DE for en-GB shipped to Germany; never the market code se), each entry lists itself when its binding is indexable, and x-default appears only when the site's default binding has the page. Two bindings with the same tag and different URLs drop that entry's alternates; the URL stays listed.
  • lastModified is left out when the API reports the Unix epoch (collections carry no timestamp of their own).
  • A walk restarts once, whole: on 409 CURSOR_EXPIRED (a publish retired the generation, or a cursor is over an hour old), and when its responses name more than one X-Config-Version (a publish between two types). The new walk's entries replace the old ones. If a publish removed the binding, the restart throws SeoError.
  • complete: true: every type's walk finished on its own catalog generation, and the config version did not change between types. It does not promise one generation for the whole result: the API names no generation in a response, so a rebuild at the same config version between two types is not detected. That is acceptable for a sitemap, because two generations at one config version carry the same URL model and the next render reads the newer one.
  • complete: false: a transport failure, a 5xx, INDEX_UNAVAILABLE or SITE_REGISTRY_WARMING stopped the walk, or the restart could not meet that promise either. entries is what the last walk read, so a restart that stopped early can hold less than the first walk did. Only a first walk that finished replaces such a restart, which gives every entry when a config version change was the only trouble. Any other problem throws, a 400 such as INVALID_CURSOR included. A preview key can meet that one when its draft is created or published mid-walk: run the walk again.
  • An API older than cursor paging throws "the Storefront API does not support sitemap cursors; deploy the API first" rather than ending the walk after one page.
  • A walk is an eventually consistent crawl, not a snapshot: a product added mid-walk may wait for the next render.

Errors. SeoError means a caller or configuration error: redirectTo is set (answer 301 instead), an unknown binding, a bad variesBy value, a variant URL (v.url or the optional variantUrl hook) that is missing, not an absolute http(s) URL or repeated for two variants, or two bindings with the same hreflang and different URLs. Catch it at your SEO boundary and fix the site's bindings. Holes in the data never throw: a missing image, description or price only leaves that part out.

hreflang sets are only as reciprocal as the API's alternates; the SDK renders what the API gives.

Search events

trackSearchEvents(client, events, { consent }) posts search exposures, product clicks and add-to-carts to POST /v1/events, for measuring search quality. It sends nothing unless consent === true: the storefront stores no PII and cannot verify consent, so the frontend decides (coordinator.effective().measurement, see "Favorites and consent"). sessionId is deprecated: the API still accepts it and discards it, and the SDK issues none.

const exposure = { type: "search_exposure", occurredAt: new Date().toISOString(), resultId: listing.search!.resultId, query, page: 1, productIds };
await trackSearchEvents(client, [exposure], { consent: shopperAcceptedMeasurement });
await trackSearchEvents(client, [{ type: "product_click", occurredAt: new Date().toISOString(), exposureId: exposure.eventId, productId, position: 3 }], { consent });
  • An event without eventId gets a UUID written into the object. Retry the same objects after an uncertain answer (a timeout, a dropped connection) and the ids are reused, so the server counts the repeats as duplicates. A second click from the same exposure is a new event: build a new object.
  • occurredAt is UTC ISO-8601 (new Date().toISOString()), within 7 days back and 5 minutes ahead.
  • At most 50 events per call (a larger batch throws RangeError), 64 KB per body. The answer lists rejected events with their index and member; the others are kept. Any non-2xx answer throws: a malformed envelope (a 400 problem) and a bare 5xx alike, so a failed send is never mistaken for "no consent" (null).
  • Exposures come only from the client; a catalog GET is never one.

Product facts and GA4

Cards and cart lines carry the product facts the product page has: brand, categories, shortDescription and attributes (minus type: "html" attributes, which stay on the product page). A card has them flat; a cart line under line.product, with the line's own brand on line.variant.brand. An order line has the same product/variant shape without shortDescription (productFacts(orderLine).shortDescription is null): its facts are the ones the charged checkout snapshot captured, never re-resolved — url, facet and attribute facetKey/valueKeys are null there, the blocks are empty on orders placed before they existed, and null on fee, shipping and adjustment lines. A checkout cart line (checkout.cart.lines[]) has the order-line shape too, but is resolved live while the attempt is open, like a cart line, with url, facet and attribute keys filled in. In every other status, and for a line the catalogue can no longer describe, it carries the snapshot's frozen facts (links null). What it shows may therefore differ from what the order later freezes. productFacts() reads them from any source:

const facts = productFacts(line);           // card, product, { product, variant }, cart line, checkout cart line or product order line
render(facts.brand?.label);                 // the item's brand: the variant's own, never a fallback to the family's
render(facts.productBrand?.label);          // the family brand
render(facts.primaryCategory?.pathNames.join(" > ")); // the one category to use for analytics, breadcrumbs and feeds

brand is the selected or purchased variant's brand, and null can mean the variant deliberately has none — do not fall back to productBrand. categories carry no primary meaning: categories[0] may be a gender, a brand or a product-type node. primaryCategory is the one to use: the storefront picks it under the site's product-taxonomy root, one of categories, and it is null when the site has no root, the product has no category under it, or the line was frozen before it existed. Identify a root by pathIds[0], never by its translated name. pathIds and primaryCategory need API v0.24.0 or later; on order lines and checkout lines frozen from a snapshot taken before v0.24.0, pathIds is [] and primaryCategory is null.

toGa4Item() and toGa4Ecommerce() map the same sources to GA4 ecommerce data; toGa4Ecommerce(checkout.cart) is the begin_checkout payload. They are pure: they send nothing and know nothing about consent or a data layer.

| Source | item_id | item_brand | price | quantity | item_variant | |---|---|---|---|---|---| | card (impression) | the family sku | brand.label | from-price | 1 | — | | { product, variant } | the variant sku | the variant's brand | the variant's price | 1 | selected options | | cart line | the line sku | the variant's brand | the line's unit price | the line's | selected options | | checkout cart line | the line sku | the variant's brand | the unit price | the line's | options | | order line (product) | the line sku | the variant's brand | the unit price | the line's | options |

  • A card is a family impression; later events carry the purchased sku. Pass itemId to report at family level.
  • Cards, variants and cart lines read the API's price pair: ex by default, inc with tax: "include", never computed and in the currency's own precision (three decimals in KWD, none in JPY). A partial price without that side throws AnalyticsError. Checkout and order lines have no pair yet: they net unitPriceInc at vatRate and round to two decimals.
  • price and value are net of VAT by default, as GA4 defines them: 2 × 125.00 at 25 % gives price: 100, value: 200. value is the sum of the items' prices, so it need not match accounting to the öre (3 × 9.99 at 25 % gives price: 7.99, value: 23.97). Pass tax: "include" to report gross on purpose.
  • For add_to_cart and remove_from_cart, pass quantity: the positive number of units added or removed, never the line's new total.
  • item_category…item_category5 come from primaryCategory's pathNames (the full path, root included). When primaryCategory is null the item has no category fields: null can mean "this product has no category under the taxonomy root", and a fallback would put a brand or series root into GA4. Since v0.24.0 this is the default; before it was the longest path, which pickCategory: longestCategory still gives. A pickCategory gets the categories and the line's facts, (categories, facts) => CategoryRefDto | undefined; returning undefined means no category fields.
  • Identify a root by id (pathIds[0]), never by its translated name.
  • No discount: compareAt is a recommended price, not a discount applied.
  • A source without a price throws AnalyticsError, as does a non-product order line; never price: 0.
  • For an order, transaction_id is order.id (stable from completion; orderNumber is null until export), tax the recorded VAT and shipping the shipping lines' net.
// The primary category is the default; this drops a top-level taxonomy root from the emitted path.
const belowRoot = (_: readonly CategoryRefDto[], f: ProductFacts) =>
  f.primaryCategory ? { ...f.primaryCategory, pathNames: f.primaryCategory.pathNames.slice(1) } : undefined;
gtag("event", "view_item_list", { items: listing.items.map((card, index) => toGa4Item(card, { index, pickCategory: belowRoot })) });
gtag("event", "add_to_cart", { currency: cart.currency, items: [toGa4Item(line, { quantity: added })] });
gtag("event", "purchase", toGa4Ecommerce(order, { pickCategory: belowRoot }));

slice(1) is right only when the site's taxonomy root is a top-level category.

Search-as-you-type and search-in-facet

/v1/search/suggest answers three short lists for what the shopper has typed so far: up to 5 product cards (matched on the product name), 5 categories (each with the path to show above it) and 10 values from the facets whose panel is searchable. q is required and 1–100 characters — blank, missing or longer is a 400 (INVALID_QUERY), not a truncation the way a listing's q is.

/v1/products/facets/{key} is the search box inside one facet panel: the facet's values with the counts they have in the same filter[…] context the listing is showing, so a count is what selecting that value would leave. Send the panel's own filters with it, and omit q for the values as they are.

const { data: suggestions } = await storefront.GET("/v1/search/suggest", { params: { query: { q: typed } } });
const { data: brands } = await storefront.GET("/v1/products/facets/{key}", {
  params: { path: { key: "varumarke" }, query: { q: typed, filter: filterQuery({ kon: ["dam"] }) } },
});

The endpoint reads the facet's 1000 most common values and matches q against those — label contains, case-insensitively, or key prefix — returning at most 50. A facet with more distinct values than that is searched over its top 1000; no regular expression ever reaches the search index. key has to be a list or swatch facet: an unknown key is FACET_NOT_FOUND (404), and a range or toggle facet is FACET_NOT_SEARCHABLE (400).

Checkout

Two small modules, because the suspend → update → resume rule spans two runtimes. The server helpers need the client and the cart token (an httpOnly cookie, so they run in Server Actions and route handlers); mountCheckout needs neither key nor fetch — it mounts the provider's widget and drives it from the answers your server hands it.

import { awaitCompletion, completeCheckout, getCheckoutStatus, getOrder, mountCheckout, startCheckout, syncCheckout } from "@asstio-dev/storefront";

Server. startCheckout(client, cartToken, { option?, returnOrigin? }) creates the cart's checkout attempt or converges on the live one; call it from a Server Action or route handler on the shopper's navigation to the checkout page, never during a Server Component's render (a re-render would create a provider order per mutation). syncCheckout is the same POST /v1/checkout, retrying CHECKOUT_IN_PROGRESS per Retry-After twice by default — call it after every cart mutation on the checkout page, through the browser handle's update; there, and for the handle's sync, pass { retries: 0 } so each call is one POST and the handle's own burst does the retrying. getCheckoutStatus(client, attemptId, cartToken) is the non-mutating GET /v1/checkout/{attemptId} behind the handle's status callback. completeCheckout(client, attemptId, cartToken?) is the confirmation page's call; with the cart token the answer carries order.accessToken, on every call, so a lost first answer or a reload still ends with the token. awaitCompletion(() => completeCheckout(…)) polls with backoff until the order exists. getOrder(client, orderId, token) sends the token as X-Order-Token — a header, never a query string; send Referrer-Policy: no-referrer on the order page and keep its URL out of your logs.

// A Server Action or route handler, on the shopper's navigation to the checkout page.
const result = await startCheckout(storefront, cartToken, { returnOrigin: "https://shop.example" });
if (!result.ok) return { problem: result.problem, retryAfter: result.retryAfter };
return { checkout: result.data };   // "open" with a widget, or "completed"/"pending" with an order

// The Server Action behind mountCheckout's `sync`, and the POST inside every cart update: one HTTP POST per call.
export async function syncForBrowser() {
  return syncCheckout(storefront, cartToken, undefined, { retries: 0 });
}

// The confirmation page: complete with the cart token, keep the order's access token, then poll for the number.
const first = await completeCheckout(storefront, attemptId, cartToken);
const done = await awaitCompletion(() => completeCheckout(storefront, attemptId, cartToken));

// The order page: the token is a header.
const order = await getOrder(storefront, orderId, token);   // 404 ORDER_NOT_FOUND for an unknown id and a wrong token alike

Browser. mountCheckout(container, checkout, { sync, status, onProblem, onOrder }) takes the open answer your page was rendered with and returns a handle { attemptId, suspended, suspend, resume, remount, destroy, sync(update) }. The container is a client component keyed by attemptId. handle.sync(update) is the whole rule: it suspends the widget, runs your update once (mutate the cart, POST /checkout, return its answer), then dispatches status first, identity on open: completed/pending → onOrder(order, attemptId) (you navigate); locked → stays suspended and retries sync() per Retry-After within the API's budget (30 s, ten calls — a 429 counts the same; a Retry-After past the 30 s is not waited out), then polls status(attemptId); processing → polls status(); declined/expired → one sync(); open → resumes when the answer's attemptId is the mounted one, else remounts from the answer's widget (changed only says this call created a new attempt — never resume on it). A status() answer is never dispatched as payable: its open leads to one non-mutating sync(). An update that throws leaves the widget suspended. The widget is suspended the moment handle.sync is called, and stays suspended while another update is queued behind it; a newly queued update ends the running sync's waits (a retry or a status poll), so it runs at once. CHECKOUT_IN_PROGRESS is retried like locked, within the same burst. If the provider's script loads late, the handle keeps trying to bind its decline signal every half second for as long as the widget is mounted. A 503 CHECKOUT_UNAVAILABLE or CHECKOUT_PROVIDER_UNAVAILABLE is retried per its Retry-After by non-mutating syncs within the same budget, then reported; any other 503 (SITE_KEYS_SYNCING, SITE_REGISTRY_WARMING) and every other non-2xx of the SDK's own calls reaches onProblem(problem, { status }) at once, status being the HTTP status — a 409 CHECKOUT_CART_CHANGED carries the corrected cart in problem.cart: show it and its warnings, then handle.sync(() => POST /checkout). handle.sync never rejects. onProblem also receives the SDK's own codes: SDK_SYNC_FAILED or SDK_STATUS_FAILED when one of its calls throws (a network failure), SDK_UPDATE_FAILED when your update throws, and SDK_DISPATCH_FAILED for any other throw while dispatching (an onOrder that throws, an unknown widget controller) — each with { status: 0 } and the widget left suspended; SDK_CHECKOUT_CLOSED when the one sync() after a declined/expired answers closed again, and SDK_UNKNOWN_STATUS for an answer status the SDK does not know (both { status: 200 }); and SDK_EMPTY_ANSWER, which the server helpers return when an answer carried no body (with that answer's HTTP status). The SDK also syncs by itself: once on the provider's payment-declined signal where its JavaScript offers one, when the page becomes visible again while suspended, and three minutes before expiry, timed from the DTO's expiresInSeconds (server-relative, so a browser clock ahead of the server's still lands inside the server's five-minute window). An autonomous sync is skipped while another sync is running or queued.

// A client component, keyed by attemptId so a re-render never resets it.
const handle = mountCheckout(container, checkout, {
  sync: callSync,       // a Server Action calling syncForBrowser()
  status: callStatus,   // a Server Action calling getCheckoutStatus(storefront, attemptId, cartToken)
  onProblem: (problem) => { /* problem.cart when code === "CHECKOUT_CART_CHANGED"; otherwise the message for problem.code */ },
  onOrder: (order, attemptId) => { location.assign(`/kassa/tack?attempt=${attemptId}&order=${order.id}`); },
});
// Every cart mutation on the page goes through the handle: suspend → your update once → status first, identity on open.
await handle.sync(() => callAddLine(sku));   // callAddLine mutates the cart, then syncs, and returns that answer

After completion. Every cart endpoint answers 410 CART_EXPIRED for the converted cart, while the cart token is still what re-delivers the order's access token — so a 410 from a cart mutation on the checkout or confirmation path does not end the cart cookie: call GET /v1/checkout/{attemptId} (or POST /checkout, which answers the converted cart's completed attempt) with the same token, navigate to the confirmation from its order, and clear the cookie only once the confirmation page holds the access token.

Copy and CSP. The pending state ("awaiting payment approval") is your copy. Each provider's widget needs its domains in your CSP: Qliro One *.qliro.com (pago.qit.nu in the sandbox), Kustom *.kustom.co (verified, see below), Walley *.walleypay.com, plus their frame-src/script-src/connect-src — the provider's integration guide lists the exact hosts.

Problem codes you will meet here: CART_EMPTY, CHECKOUT_CART_CHANGED (with cart), CHECKOUT_PREVIEW_KEY, CONTEXT_MISMATCH (409: the request's market or country is not the cart's, the cart is under cart; send the cart's, or move it with POST /v1/cart/context, then sync), OPTION_NOT_AVAILABLE, ORIGIN_NOT_ALLOWED, CHECKOUT_UNAVAILABLE (503, with Retry-After when it is worth retrying) and CHECKOUT_PROVIDER_UNAVAILABLE (503, Retry-After), CHECKOUT_IN_PROGRESS (409, Retry-After), CHECKOUT_PROVIDER_REJECTED (502), CHECKOUT_NOT_FOUND, ORDER_NOT_FOUND, SITE_KEYS_SYNCING (503 for a secret key on a freshly created site, Retry-After).

Qliro (qliro-q1)

  • The widget is Qliro's HTML snippet; mountCheckout re-creates its scripts so they run.
  • After every cart change, handle.sync(update) locks the widget (q1.lock()), and resumes it through q1.onOrderUpdated, which makes the iframe re-read the order. The widget unlocks only when Qliro's order shows the confirmed total, or echoes the confirmed cart version (MerchantUpdateVersion, which the backend sends on a market with shipping, where Qliro's total includes the fee). If it does neither within 10 seconds, or the change came before Qliro's script had loaded, the widget is re-rendered from the confirmed checkout instead; it is never unlocked before Qliro shows the confirmed total or version.
  • When our validation declines a purchase (the cart moved on, the attempt expired, a line is out of stock), Qliro shows its out-of-stock message and fires q1.onPaymentDeclined; the SDK then syncs by itself and remounts or resumes.
  • q1 callbacks replace per event. The SDK owns onOrderUpdated and onPaymentDeclined, and with onShipping also onShippingMethodChanged and onShippingPriceChanged: a listener of your own on these silently stops the SDK's.

Kustom (klarna-kco)

  • The widget is Kustom's HTML snippet (Kustom Checkout v3); mountCheckout re-creates its scripts so they run.

  • After every cart change, handle.sync(update) suspends the checkout with suspend({ autoResume: { enabled: false } }), so Kustom never reopens payment by itself during a slow sync or while the SDK retries a locked answer. It resumes only on the confirmed open answer for the same attempt; Kustom re-reads its order on resume(). A change made before the snippet's script has defined window._klarnaCheckout is handed over as soon as it has.

  • When our validation declines a purchase, Kustom sends the whole page to your checkout page with declined=validation added to its query (the server answers Kustom with a 303 to the attempt's checkout page). That page is a fresh load: show a short message for declined=validation, sync the real cart, and handle completed/pending before mounting a widget, as on any page load. There is no onDeclined for Kustom.

  • can_not_complete_order (no offered payment method can complete the order) reaches onProblem with the code SDK_PROVIDER_CANNOT_COMPLETE; the copy is yours.

  • The re-entry refresh (a stored snippet older than ten minutes is re-fetched) and the acknowledgement to Kustom are the server's; the page does nothing for them.

  • The checkout page needs a checkoutPath and a termsPath in the market's checkout block (Purchase refuses a Kustom option without them).

  • Never bind can_not_complete_order yourself through window._klarnaCheckout(api => api.on(...)). Kustom's api.on replaces the listener per event instead of adding one, so yours and the SDK's would replace each other. Use onProblem. Listeners for other events are not affected. With onShipping set (see "Live shipping view" below) the SDK also owns shipping_option_change, shipping_address_change and order_total_change (one separate api.on); use onShipping for those.

  • CSP hosts (K-C10, docs/ops/kustom-playground-checks.md, 2026-10-09: a card with 3-D Secure and the default method, no blocked request). The checkout page itself loads only Kustom's script host. Everything else (kco.assets.kustomcdn.co, Klarna, Stripe, hCaptcha, Google Pay, Amazon Pay) loads inside Kustom's iframe under Kustom's own policy. Allow:

    • script-src 'unsafe-inline' https://*.kustom.co;
    • frame-src https://*.kustom.co;
    • connect-src https://*.kustom.co.

    https://*.kustom.co covers the playground (js.playground.kustom.co) and production (js.kustom.co).

Shipping

The shopper chooses delivery inside the provider's widget (Kustom's shipping assistant, Qliro's shipping step), so there is no shipping picker to build and no price, VAT or method id to send. The klarna-kco (Kustom) and qliro-q1 controllers answer for the widget; the page's part is the estimate before the checkout and the shipping block on the order.

// The estimate: an estimate, never a quote (the destination is not known yet). No lookup, `no-store`.
const { data: estimate } = await storefront.GET("/v1/cart/shipping-estimate", {
  params: { header: { "X-Cart-Token": token } },
});
if (estimate?.available) {
  const headline = estimate.options.find((option) => option.preselected); // `fee` is gross kronor, "49.00"
  // estimate.freeShipping: { free, threshold, remaining } — progress comes from here, never a hard-coded threshold
}
// `available: false` means show nothing about shipping. `reason: null`: no block published on the market, and the
// checkout works as before. `reason: "unavailable"`: a block that cannot be served now; the cart works, but
// POST /v1/checkout refuses a new attempt with 503 SHIPPING_UNAVAILABLE (Retry-After 60) until it is fixed.

// The order page: `order.shipping` is `OrderShippingDto | null`.
// null = the selection was not matched or confirmed (the charged shipping line is still in `order.lines`), or the
// market has no block. Show the block only when it is present; never read null as "no shipping was paid".
  • ShippingEstimateOptionDto: key, name, deliveryType (delivery, pickup or mailbox), fee, regularFee (the price without the free-shipping rule; set only when fee is "0.00" and that price is above 0, so null for an always-free method: render no comparison price then), labels, pointsAtCheckout (the pickup point is chosen in the checkout; none is listed here) and preselected. The estimate has no delivery time.
  • OrderShippingDto: option, name, deliveryType, carrier, fee, point (name, street, postal code, city; null when the carrier assigned it or after the privacy scrub) and deliveryTime (mode carrierEstimate, fixed or text; minDays and maxDays are each nullable: render only the bounds that are present, or text).
  • Do not re-render the widget when shipping changes, and do not write your own Qliro unlock: on a market with a shipping block Qliro's total includes the fee and so can differ from the cart's, and the qliro-q1 controller unlocks on the echoed cart version (MerchantUpdateVersion) or on the confirmed total (see the Qliro notes above).
  • Shipping never blocks a purchase. If a selection cannot be matched when the shopper pays, the order is accepted and normally held in Asstio with its reason (rarely the export waits for an operator instead); the page has nothing to do for it.

Live shipping view

Optionally show what the shopper has chosen inside the widget, from GET /v1/checkout/{attemptId}/shipping. The view is not a promise: the order's lines and totals stay the truth.

// Server route: forwards the view and Retry-After. The cart token stays on the server.
const r = await liveShippingFor(client, cartToken, attemptId);
// r.ok ? r.data : r.problem, with r.retryAfter as the Retry-After header

// Page:
mountCheckout(el, widget, {
  /* … */
  liveShipping: (attemptId) => callMyProxy(attemptId), // returns LiveShippingResult
  onShipping: (view) => {
    if (view === null) return showEstimate();            // invalidated: a change is in flight
    if (view.state === "selected") showLine(view.name, view.shippingInc, view.totalInc);
  },
});
  • liveShipping and onShipping are required together (one without the other throws at mount). Without them nothing shipping-related is bound, scheduled or called.
  • view.state: selected, unselected, unmatched, unavailable (with reason: syncing, closed, provider, throttled, mismatch, erased, not_supported, and retryAfterSeconds).
  • Members: goodsInc, shippingInc, totalInc, otherInc, totalSource, option, name, deliveryType, point, readAt, cartVersion. totalInc is the provider-reported total, before payment-method charges the provider does not report before purchase. name can differ from Kustom's display copy.
  • Freshness: a method change on both providers, and an address change on Kustom, typically follows the provider's event within a couple of seconds. A Kustom pickup-point change and a Qliro address change fire no client event we know of and are seen only by the safety net (every 45 to 60 s, best-effort, up to about 60 s), which runs only while the tab is visible.
  • The SDK owns the provider's shipping events while onShipping is set; do not bind them yourself.

Accounts: sign-in, sessions and saved carts

Shopper accounts are a server-only module, @asstio-dev/storefront/account, with a Next.js (15+) adapter, @asstio-dev/storefront/account/next, and one browser helper, @asstio-dev/storefront/account/browser. Every account call needs the site's server key (sfk_srv_…) and runs on your server; the session token travels in X-Shopper-Session, which the API refuses from a browser (SESSION_FROM_BROWSER) and which no CORS preflight allows. A site without accounts answers every account route 404 ACCOUNTS_DISABLED, and GET /v1/site has accounts: null — render no sign-in then.

Sign-in. startSignInAction(config, email, returnPath?) mails an 8-digit code and a link (the 202 is the same whether or not the address may sign in) and keeps the start's binding in the HttpOnly __Host-sf_signin cookie for 10 minutes. verifySignInAction(config, { code }) or { link } mints the session into the __Host-sf_session cookie. On the link's page, read the token with readLinkFragment() in the browser (it removes it from the URL) and hand it to a server action. A link opened in another browser has no binding: the answer is 409 SIGN_IN_CONFIRM_REQUIRED with maskedEmail and siteName — ask "Sign in on this device?" and call again with confirm: true. Any other failure is one code, SIGN_IN_INVALID: start a new sign-in. Redirect to the view's returnPath (or your default) yourself.

Sessions. Build a client per request, never a module singleton: shopperClient(config) reads the session cookie (createShopperClient({ baseUrl, serverKey, session, shopperIp, binding }) outside Next.js). AccountActionConfig and createShopperClient take the same context as createStorefrontClient: market, country and locale, each optional, or a binding. getSession, getMe and getMyCompany read who is signed in; switchPrincipalAction(config, principal) acts as another principal ("consumer" or a membership id), rotates the session and points your cart cookie at the new principal's saved cart, or clears it when that principal has none; signOutAction(config, { everywhere? }) clears the session, sign-in, cart and browser-cart cookies whatever the API answers. A session that no longer validates is 401 SESSION_INVALID on every route, never a silent signed-out answer: render signed-out, and let the next action clear the cookie.

Private data at a session change. A verify or switch that took effect, and every sign-out, returns dropPrivateData: true: the shopper is now someone else, so throw away what the browser still holds for the old one (a cart view, prices, account data) and read again. After a sign-in that includes the adopted cart: the guest's view of it goes. A switch keeps the rotated session and the cart cookie now names the new principal's own cart. A failed verify or switch changed nothing and has no such flag. On the server, never put priced private data in a shared cache or ISR.

Saved carts. With a session, POST /v1/cart returns the principal's saved cart (or creates one) and GET /v1/me/cart reads it; the cart routes work on it with its token and the session. A saved cart's token without its owner's session — another device signed out, another principal, another account — is 404 NOT_FOUND, exactly an unknown token; a principal that may not change the cart (a company viewer) is 403 PERMISSION_DENIED with permission: "cart.edit". Sign-in never merges carts: when the shopper had a browser cart A and a saved cart B, verify points your cart cookie (config.cartCookie) at B and keeps A in __Host-sf_browser_cart for 30 minutes; with no saved cart, the cookie stays on A (adopted, or still anonymous) and is cleared when the API names neither cart (the cookie held no usable cart). Offer "Add to saved cart" and call copyBrowserCartAction(config): each line of A is an ordinary POST /v1/cart/lines on B with Idempotency-Key: copy:{A}:{lineId}, so a retry never doubles a line. The result lists line ids as copied, skipped (the product is gone or cannot be sold) and failed (retry); the browser-cart cookie is cleared once nothing failed, at sign-out and at its expiry.

Checkout with a session. Pass the shopper client as { shopper } to startCheckout, syncCheckout, completeCheckout, getCheckoutStatus, liveShippingFor and getOrder: the call goes through it, so a saved cart checks out under its owner and the order records the consumer. Signed out, leave it out — the call is exactly today's. A company principal cannot check out yet (409 COMPANY_CHECKOUT_UNAVAILABLE). The confirmation and order pages of a consumer's checkout still open by the cart token and the order token alone, so a payment that returns to a signed-out tab completes.

import { getMe } from "@asstio-dev/storefront/account";
import { copyBrowserCartAction, shopperClient, signOutAction, startSignInAction, verifySignInAction, type AccountActionConfig } from "@asstio-dev/storefront/account/next";

// process.env.STOREFRONT_SERVER_KEY: the server key never reaches a browser bundle.
declare const STOREFRONT_SERVER_KEY: string;

const accounts: AccountActionConfig = {
  baseUrl: "https://api.storefront.asstio.com",
  serverKey: STOREFRONT_SERVER_KEY,
  market: "se",
  origin: "https://shop.example",   // decides Secure and the __Host- prefix (dropped on http://localhost)
  trustedHops: 1,                    // proxies in front of this server, for the shopper IP the sign-in limits use
  cartCookie: "cart",                // your cart cookie: sent at verify, pointed at the saved cart, read by the copy
};

// Your "use server" actions.
export async function startSignInForm(email: string) { return startSignInAction(accounts, email, "/account"); }
export async function verifyCode(code: string) { return verifySignInAction(accounts, { code }); }
export async function verifyLink(link: string, confirm = false) { return verifySignInAction(accounts, { link, confirm }); }
export async function addToSavedCart() { return copyBrowserCartAction(accounts); }
export async function signOutEverywhere() { return signOutAction(accounts, { everywhere: true }); }

// A server component: who is signed in. Signed out, or a session that no longer validates, renders signed-out.
export async function accountHeader() {
  const me = await getMe(await shopperClient(accounts));
  return me.ok ? me.data.email : null;
}

// Checkout under the session: the saved cart checks out under its owner, and the order records the principal.
export async function beginSignedInCheckout(savedCart: string) {
  const shopper = await shopperClient(accounts);
  return startCheckout(storefront, savedCart, { returnOrigin: "https://shop.example", shopper });
}

Favorites, stock watches and consent

Guest favorites, stock watches and the device's consent live in five entries (shopper-state spec):

  • @asstio-dev/storefront/account/next — shopperActions(config): favorites, stock watches (watches.create, list, cancel(id), stopAll() — the last one signed in only), the shopper's own state (read, erase), consent (read, history, put) and adopt(). Signed in they use /v1/me/*, as a guest the /v1/shopper/* relay. A guest's first write mints a shopper token into the HttpOnly __Host-sf_shopper cookie; no result ever carries it. Node runtime only: the module loads node:crypto.
  • @asstio-dev/storefront/account/browser — withShopperLock(actions): wrap your "use server" shopper actions in the browser so tabs never race the token cookie (two first adds would mint two tokens; a late answer could renew an erased token). Wrap your sign-out action too, and call coordinator.beforeSignOut() before it, outside the lock. Each action holds the lock until it settles. Without Web Locks they run unserialized. An action's shopper.owner is null when the account lookup failed: keep your current owner (coordinator.setOwner(null) ignores it).
  • @asstio-dev/storefront/consent — createConsentCoordinator({ site, owner, transport }), the browser's one writer of the consent cookies: a withdrawal takes effect at once, a grant only after the server recorded it. Its transport is { put: locked.consent.put }. Gate every measurement, personalization or ad tag on coordinator.effective(). advertising means ad-platform measurement: storing ad click identifiers on the device, sending conversions to ad platforms, and the frontend's own ad tags (Consent Mode ad_storage, ad_user_data, ad_personalization).
  • @asstio-dev/storefront/consent/server — readConsentCookie(cookies) (the same answer for SSR) and consentOwner(cookies, session).
  • @asstio-dev/storefront/shopper — the watch types ShopperWatch (owner projection) and RecipientWatch, the union Watch narrowed by projection, and cancelWatchByToken(client, token, "watch" | "all", { shopperIp? }) for the mail's cancel page. In the browser pass the publishable-key client from createStorefrontClient; on the server pass a server-key client and the shopper's IP (createShopperClient({ serverKey, shopperIp }), or { shopperIp } here), so the rate limit is the shopper's and never one bucket for everyone behind your server. It never sends a session or shopper token, and the API answers 204 whatever the token is, so show a fixed text.

Order attribution

Records where a shopper came from (UTM parameters, click ids, a cross-origin referrer) and sends it with the checkout, only for a device that grants measurement. Nothing happens on a site whose attribution block is absent or not enabled. Two entries: @asstio-dev/storefront/attribution (browser-safe: createAttributionCapture, the cookie codec) and @asstio-dev/storefront/attribution/next (server: recordLanding, recordLandingRoute, recordLandingAction, readAttribution, attributionForCheckout).

Mounting

  1. Add a route handler, the recommended wrapper: export const POST = recordLandingRoute(getSite, { origin }) in app/api/attribution/route.ts. It takes { href, referrer } as JSON, accepts only your own origin or a binding origin (otherwise 403), refuses a body above 16 KB with 413 (it stops reading there, with or without Content-Length), and answers 204. recordLandingAction is a Server Action body and works too, but setting a cookie from an action re-renders the current page.
  2. In a client component in the root layout create the capture once with createAttributionCapture({ send }), where send posts the landing to that route (keepalive: true). The capture holds nothing in memory: at flush it reads the landing from the browser's navigation entry and document.referrer and sends only a landing that can be a touch (a utm_* or click-id parameter, or a cross-origin referrer): at most once per page, and nothing where the entry is unavailable (an under-count, never a wrong landing). A plain page load posts nothing.
  3. Call capture.flush(...) after mount, and ag