storefront
npx skills add https://github.com/crystallizeapi/ai --skill storefrontCrystallize Storefront
A Crystallize storefront reads the catalogue from Discovery and does everything about a shopper on the Shop API. Nothing else is in the request path. That one rule settles most design questions, and breaking it is behind most of the slow pages, wrong prices and missing orders seen in real builds.
This skill is the workflow: the contract, the request path per page type, and the rules that keep cached pages
correct. The query and mutation details live in [[query]] and [[mutation]]; prices in [[pricing]]; payment in
[[payments]]. Detail for this skill is in references/.
Drawn from seventeen Crystallize storefront builds (September–November 2026, Next.js 16 with Cache Components on Vercel, all on Discovery and the Shop API). Draft reads through Discovery were verified on 2026-11-12: on an open Discovery,
publicationState: draftreturned the same 541 drafts with and without credentials. Where a claim comes from one build, it says so.
The contract in five lines
- Discovery: every catalogue read. Item by path, browse, search, typeahead, facets, variant groups,
translated paths, list and market prices, stock per location, ranking and similarity. Published content by
default; drafts with
publicationState: draft(on an open Discovery, to anyone). Eventually consistent. - Shop API: everything about a shopper. Carts, the price for this customer and market, promotions and
vouchers,
place, orders, payments, pipeline stages, the shopper’s order history, customers, bookings, subscription contracts, locks. - Catalogue API: the synchronous fallback. Per-customer price lists for display
(
priceFor(customerIdentifiers)), server-side, and reads that must be in sync with a publish: Discovery is updated asynchronously, Catalogue at once. Not for path lookups, preview or hreflang: Discovery does those. - Core API: never in the request path. Seeding, imports, scheduled jobs, webhooks, admin tools behind staff login. It is rate limited.
- Legacy PIM API: setup only. Markets, VAT types, pipelines, stock locations, tenant defaults.
The full decision table (task → API → call → token → where) is in references/api-contract.md.
Credentials, and what may run in the browser
| API | Endpoint | Credential | From the browser? |
|---|---|---|---|
| Discovery | https://api.crystallize.com/{tenant}/discovery |
None when open (the default); X-Crystallize-Static-Auth-Token when restricted |
Yes if open, and then everything it serves is public: every price variant, every market price list, every draft |
| Shop API | https://shop-api.crystallize.com/{tenant}/{cart,order,customer,…} |
A JWT from POST …/{tenant}/auth/token, minted with an access token pair scoped to this tenant (or unscoped) |
No. Server only. The browser holds the cart id, in an httpOnly cookie |
| Catalogue | https://api.crystallize.com/{tenant}/catalogue |
Open, static token or token pair, per tenant setting | Only open, published reads; contract prices are server-only |
| Core | https://api.crystallize.com/@{tenant} |
Token pair | Never |
- The Shop JWT is per tenant, not per shopper. Cache it on the server and refresh it before it expires. The
API default is one day;
@crystallize/js-api-clientdefaults to 12 hours. An expired or rejected token answers 401 with{ success: false }and noerrors: drop the cached token and retry once. - Ask for the scopes you use:
cart,cart:admin,order,customer,subscription-contract,booking,booking:admin,lock./booking/adminneeds bothbookingandbooking:admin: a token with onlybooking:adminis refused with “Invalid Scopes”. Mint a separate token forsubscription-contract; a token carrying every scope was seen to lack subscription access silently. - The Shop API reads products from the Catalogue with the request’s credentials. On a tenant whose Catalogue requires a token, every hydrate needs it.
- Never put a token in a
NEXT_PUBLIC_*(or any client-bundled) variable. See [[permissions]] for which token pair mints Shop tokens.
Before you start
- The tenant is ignited for Discovery, and every component you render is
discoverable(a non-discoverable component is simply absent from the schema). See [[query]]. - New shapes or components have been through an ignite and answer reliably: query a new field ten times in a row before shipping code that depends on it.
- You have an access token pair for the Shop API, scoped to this tenant, server-side only.
- If drafts, price lists or contract prices must stay private, Search & Discovery and Catalogue are restricted, Discovery has been re-ignited since, and an anonymous Discovery call is refused several times in a row.
- Languages, price variants, markets, VAT types and stock locations exist, and you know their identifiers
(they become Discovery field names:
nokPrice,<location>Stock). - Find a reference implementation with the capabilities you need (below).
Two small clients
Discovery, cached on the server, with retries on rate limits and gateway errors (trimmed from a working Next.js 16 storefront):
import { cacheLife, cacheTag } from "next/cache";
const ENDPOINT = `https://api.crystallize.com/${process.env.CRYSTALLIZE_TENANT_IDENTIFIER}/discovery`;
export async function discovery<T>( query: string, variables: Record<string, unknown> = {}, opts: { draft?: boolean } = {},) { // Draft reads (editor preview) are never cached. return opts.draft ? request<T>(query, variables) : cached<T>(query, variables);}
async function cached<T>(query: string, variables: Record<string, unknown>): Promise<T> { "use cache: remote"; cacheLife("hours"); cacheTag("discovery"); // the publish webhook clears this tag return request<T>(query, variables);}
async function request<T>(query: string, variables: Record<string, unknown>): Promise<T> { const headers: Record<string, string> = { "content-type": "application/json" }; // Only on a restricted Discovery; an open one takes no credentials. const token = process.env.CRYSTALLIZE_STATIC_AUTH_TOKEN; if (token) headers["X-Crystallize-Static-Auth-Token"] = token; let json; for (let attempt = 0; ; attempt++) { const res = await fetch(ENDPOINT, { method: "POST", headers, body: JSON.stringify({ query, variables }) }); const text = await res.text(); try { if (res.status === 429 || res.status >= 500) throw new Error(`Discovery ${res.status}`); json = JSON.parse(text); break; } catch (e) { if (attempt >= 4) throw e; await new Promise((r) => setTimeout(r, 250 * 2 ** attempt + Math.random() * 200)); } } if (json.errors) throw new Error(json.errors.map((e: { message: string }) => e.message).join("\n")); return json.data as T;}Shop API, server only, with the token cached in module scope:
const SHOP = `https://shop-api.crystallize.com/${process.env.CRYSTALLIZE_TENANT_IDENTIFIER}`;let jwt: { token: string; expires: number } | null = null;
async function token() { if (jwt && jwt.expires > Date.now() + 60_000) return jwt.token; const res = await fetch(`${SHOP}/auth/token`, { method: "POST", headers: { "content-type": "application/json", "x-crystallize-access-token-id": process.env.CRYSTALLIZE_ACCESS_TOKEN_ID ?? "", "x-crystallize-access-token-secret": process.env.CRYSTALLIZE_ACCESS_TOKEN_SECRET ?? "", }, body: JSON.stringify({ scopes: ["cart", "order"], expiresIn: 18000 }), }); const { token } = (await res.json()) as { token: string }; jwt = { token, expires: Date.now() + 18000 * 1000 }; return token;}
export async function shop<T>(query: string, variables = {}, endpoint: "cart" | "order" = "cart"): Promise<T> { for (let attempt = 0; ; attempt++) { const res = await fetch(`${SHOP}/${endpoint}`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${await token()}` }, body: JSON.stringify({ query, variables }), cache: "no-store", }); // A rejected token answers 401 with { success: false } and no `errors`: get a new one, once. if (res.status === 401 && attempt === 0) { jwt = null; continue; } const json = await res.json().catch(() => null); if (json?.errors) throw new Error(json.errors.map((e: { message: string }) => e.message).join("\n")); if (!res.ok || !json?.data) throw new Error(`Shop API ${endpoint}: HTTP ${res.status}`); return json.data as T; }}In Next.js with Cache Components, call await connection() at the top of shop() for anything per-shopper, so a
cart never ends up in a prerendered shell. See references/nextjs-pitfalls.md.
The request path, per page type
Any catalogue page (home, category, brand)
- Language and market come from the path (
/no/…), not a cookie. A cookie market means crawlers only ever see the default market’s prices. - A server component reads Discovery through the cached client. Build variables in a fixed order (the cache key is query + variables).
- Per-shopper parts (taste-ranked rails, “shopping as”, contract prices) stream behind
<Suspense>with real content as the fallback, so the shell is complete without them. - Card images ask for trimmed variants only (
variants(types: "webp", minWidth, maxWidth)). Rails and menus skipfacets, which cost about 17 KB per read. - Look up the item by full path, never by the last segment: paths are unique only within their folder.
query Resolve($path: String!) { search(language: en, filters: { path: { equals: $path } }) { hits { itemId shape name } }}Product listing (PLP) with one card per colourway
variantGroups groups a product’s variants by an attribute, so a listing card shows each colourway with its own
price range, stock and images, filtered to what the shopper asked for. It never removes a group or changes hits,
facets or paging: groups with a matching variant come first, the rest read matched: false. Trimmed from a
fashion build:
colours: variantGroups(by: ["colour"], filter: $variantFilter) { matched attributes { value } summary { matchedInStock(location: "web") price: matchedPrice(variant: "default") { min max } } representative { sku } images { url width height variants(types: "webp", minWidth: 500, maxWidth: 768) { width } } sizes: values(of: "size") { value sku matched inStock(location: "web") }}filter is a VariantFilterInput (exact operators only). Attribute names and values are case-sensitive. Every
group’s images come back, so image selection is most of the payload: trim it per context. See [[query]].
Product detail (PDP)
- One
search(filters: { path: { equals } })returns the product, variants, trimmed images, relations (already in the request’s language), breadcrumbs (which end with the item itself) and typed specs. - One aliased query by
itemIdgives the item’s path in every language, for hreflang and the language switcher (references/i18n-routing.md). - The buy box resolves the chosen options with
variant(selected: [{ attribute, value }]), the first variant carrying every pair, and passes its SKU to the cart. Stock comes from that variant’s<location>Stock. - List price from Discovery for everyone; the contract price from a cached server-side read for a signed-in buyer (below); booking availability from the Shop API, loaded after the product.
- JSON-LD and the Markdown twin come from the same typed rows. An unset boolean reads
false: treat it as “not stated”. See [[seo-geo]].
Search results
browse.<shape>(language, term: $term, options: { fuzzy: { fuzziness: SINGLE } }, sorting: { score: desc }).
Drop hits with score 0 (they matched only through a filter), and widen to DOUBLE when nothing is left. When
the query also uses rankBy, add { signal: relevance } or the term stops mattering ([[vector-ranking]]). The
search page is noindex, follow.
Cart and checkout
The cart is a server action over Shop hydrate; checkout is setCustomer → setMeta → place → payment →
createFromCart in the payment webhook. Outline below; full flow in
references/cart-checkout.md.
Caching and revalidation on publish
- Cache Discovery reads on the server, keyed on query + variables, tagged
discovery. - On publish, a Core webhook (
concern: "items", eventspublishandunpublish) calls a route that clears the tag. Page, JSON-LD, sitemap, Markdown twins and llms.txt then follow in one step.concern: "item"is accepted bycreateWebhookand never fires. - Cached functions never throw a transient error into the cache: retry inside, and fall back to empty.
- Per-customer data (order history, taste, contract prices) is cached per customer or organisation and tagged so
checkout can expire it (
updateTag). - Draft reads are never cached.
- Revalidation is billed on some hosts: one build found cache writes were most of its Vercel bill, and fixed it
with
cacheLife('hours')plus the webhook, and hover-only prefetch.
Code for the webhook route and its setup: references/caching-and-revalidation.md.
Translated paths and i18n routing
- Every URL starts with the language (
/en,/no); the proxy redirects/from a cookie, thenAccept-Language, then the default. - Paths are translated per language, so match items across languages by
itemId, never by slug. <html lang>, hreflang and schema.org use BCP 47 (nb), not the tenant’s language code (no). Addx-default.
Details and code: references/i18n-routing.md.
Cart and checkout UI
hydratereplaces the whole cart. Send every line, every time; a booked line must come back with itslineId,metaandbooking, or the reservation is released.- The hydrate answer is the source of truth for the drawer. On a cart line,
price.netis the line total;variant.price.netis the unit price. - Price context on every hydrate:
currency,selectedVariantIdentifier,taxRateas a fraction (0.25),decimals: 4(round for display only),marketsfor price lists, and the customer. - Re-hydrate a stored cart when it is stale, was built in another language, or for another customer.
- Optimistic UI on top: show the line at once; the hydrate takes 200–400 ms.
- After
placethe cart is locked. If order creation then fails, the shopper needs a new cart. createFromCartmoves the cart toordered; there is nofulfillafterwards.- New orders take seconds to minutes to appear in
orders(customerIdentifier): the confirmation page shows the ordercreateFromCartreturned, and says so.
B2B prices against a public Discovery
An open Discovery serves every price variant and every market price list to anyone who knows the field name. Confidential terms never go there. With price lists or contract prices, restrict Catalogue and Search & Discovery and read them with the static token from the server; Discovery needs a re-ignite after the change ([[query]]). Open APIs are fine for a catalogue whose prices are all public.
| Need | Where |
|---|---|
| List, sale, “from” price | Discovery <variant>Price, variantGroups.summary.price |
| Public market price | Discovery <variant>PriceFor(marketIdentifiers), only for the SKUs on screen (about 1.4 s per 100 products per market) |
| The buyer’s contract price, in the cart | Shop hydrate with the organisation as customer and its price-list markets in the price context. Re-hydrate when the customer changes: price lists apply only to a cart hydrated with them |
| The buyer’s contract price, on the page | Server-side, cached per organisation: a throw-away hydrate with the customer, or Catalogue priceFor(customerIdentifiers) |
- The customer on a B2B cart is the organisation (orders belong to it); the person who ordered goes in cart meta.
- Markets come from the server session. A market identifier works as a key: a guest cart that sends a contract market gets the contract price. Never take markets from the browser, a query string or a form field ([[pricing]]).
- Target organisations by
customerIdentifiersor markets. Customer-group price lists were reported failing withCustomerGroupNotFoundErroron several tenants; see [[pricing]]. - Show incl. or excl. VAT per segment. Prices in Crystallize are usually net; the market decides currency, price variant and VAT rate.
Draft preview
Draft preview is a Discovery read with publicationState: draft, done server-side behind the editor’s preview
mode, and never cached. Editors open it from a custom view in the Crystallize App, which frames the storefront
next to the item. Setup, code and verification: references/preview.md.
- Custom view (Settings → Custom views): a URL template such as
https://shop.example.com/api/preview?secret=…&language={{language}}&itemId={{itemId}}&path={{itemPath}}. Placeholders:{{language}},{{itemId}},{{itemPath}},{{itemExternalReference}},{{variantSku}}. See the Custom views doc. - Always turn on “Show responsive device toolbar in preview”. The editor switches between mobile and desktop in the App’s toolbar; the storefront only has to be responsive and adds no device buttons or preview chrome of its own.
- A preview route checks a secret, resolves the item’s storefront URL from its draft, by item id and
per language (paths are translated and have no
/{lang}prefix), turns on preview mode (Next’sdraftMode().enable()) and redirects. Redirect only to a path Discovery returned. - Every Discovery read in preview mode adds
publicationState: draft(every field that takeslanguageaccepts it, nesteditems/variantsincluded). In Next.js, readdraftMode().isEnabledinside the'use cache'client: off while prerendering, so normal traffic stays cached; with the cookie nothing is saved. - No caching,
noindex, and the App’sfrontend-preview-listener.jsloaded in preview mode only, so the view reloads when the editor saves. - Framing:
frame-ancestors 'self' https://app.crystallize.comon the preview route and preview-mode responses only; every other page keepsX-Frame-Options: SAMEORIGIN. - The preview cookie is
SameSite=None; Secure(it is set and read inside a third-party iframe), andPartitioned. Next’s draft cookie isLaxinnext dev: test the framed preview on a production build. - On an open Discovery every draft is public. Anyone who sends
publicationState: draftgets it, no credentials needed (verified 2026-11-12 on two tenants, including unpublished drafts read anonymously). The preview secret guards the preview mode, not the data. Don’t keep confidential or embargoed content in drafts on an open tenant; if drafts must stay private, restrict Discovery, re-ignite, and send the static token from the server. The restriction takes effect only afterigniteDiscoApiand a few minutes more ([[query]]). - Never render drafts to crawlers or the public. Preview responses are
noindexand uncached, the preview route is under aDisallowed path and not in the sitemap, and nothing in the store links to it.
Consistency the storefront has to live with
- Discovery is eventually consistent.
publishItemanswers before anything is indexed. New shapes and components need an ignite, and the new schema reaches the nodes over minutes; an error answered in that window can be cached per query body. - Discovery under load answered HTTP 200 with
errors: [{ message: "Response Error" }]after about 900 prerendered pages in one build. Retry on that message, cap prerender concurrency, or render on demand. - The Shop order list is a second store. Orders appear in
orders(customerIdentifier)after seconds to minutes. Read by id for anything you just wrote; never use the listing for idempotency. - Explicit
nullin Discovery variables is rejected. Leave the key out instead.
Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Pages slow, 429s in logs | Core or PIM in the request path | Discovery for reads, Shop API for the shopper |
| Contract prices visible to anyone | Negotiated prices in a price variant or market list on an open Discovery | Shop hydrate or Catalogue priceFor, server-side |
| Cart loses lines | hydrate sent only the changed line |
Send the whole cart every time |
| Line total multiplied by the quantity again | price.net on a cart line is the line total |
Use variant.price.net for the unit price |
| Order missing from the account page | Order listing lag | Show the returned order; say history updates shortly |
| Page stale after publish | No webhook, or concern: "item" |
concern: "items" → route that clears the discovery tag |
| Page broke after a model change | Schema not propagated; an error cached per query body | Ignite, wait for ten good answers, then ship |
| Embargoed product readable before launch | Drafts on an open Discovery are public, or Discovery restricted without a re-ignite | Restrict Discovery, re-ignite, use the static token; or keep it out of drafts |
| Crawlers see only the default market | Market chosen by cookie | Language and market in the path |
Googlebot gets no <title> or canonical |
Dynamic metadata streamed into <body>; cached shell served to Googlebot |
Cacheable metadata in the shell’s <head> (references/performance.md) |
| Search page fails for everyone | An explicit null in Discovery variables |
Omit the key |
og:image blank in link previews |
AVIF share image | Original format (JPEG/PNG) or WebP, never AVIF ([[responsive-images]]) |
Images
Use [[responsive-images]]: plain <picture>/<img> straight from media.crystallize.com, srcset from the
returned variants, sizes that match the CSS, WebP rather than AVIF, size selected. Preconnect to the media host
without crossOrigin. og:image and JSON-LD image use an absolute URL to the original format, never AVIF.
Reference implementations
superfast.shop lists live demo stores, one per industry, each on its own tenant with a storefront on Discovery and the Shop API, built agentically with the Crystallize MCP. Before designing a storefront, find one with the capabilities the user needs and read how it does it:
https://superfast.shop/demos.json: every store, its capabilities, live URL and build prompt, as JSON.https://superfast.shop/start.md: interviews the user and hands back a build prompt.https://superfast.shop/llms.txt; the list filters by URL, e.g.?cap-model=subscriptions,?audience=b2b.https://superfast.shop/demos/<id>andhttps://superfast.shop/demos/<id>/prompt.md: a store’s page and its “build your own like it” prompt. Each live store has its own/llms.txt.
| Store | Look at it for |
|---|---|
photo-store |
Typed specs as filters, vector ranking per shopper, an MCP server and an on-site assistant |
tools-universe |
Rentals and bookings, ETIM typed specs, battery platforms, quotes, stock per location, MCP, JSON-LD |
food-universe |
B2B invoice and credit limits, GS1 and allergens, recipes to basket, draft preview |
fashion-universe |
Colourways and sizes with variantGroups, sale pricing, multi-market |
lab-universe |
Approvals, budgets, contract and volume prices, standing orders |
screen-universe |
Subscriptions with trials, metered usage |
References
| File | Read it when |
|---|---|
| references/api-contract.md | Choosing the API, endpoint, token and place for any task |
| references/caching-and-revalidation.md | Caching Discovery, the publish webhook, per-customer caches |
| references/i18n-routing.md | Language and market routing, translated paths, hreflang, the language switcher |
| references/cart-checkout.md | Hydrate, place, order, bookings, quotes, the confirmation page |
| references/performance.md | LCP, prefetch, function region, prerendering, metadata in <head> |
| references/accessibility.md | Drawers, skip link, focus, forms, live regions |
| references/security-headers.md | Companion headers, CSP, frame-ancestors, cookies |
| references/preview.md | Draft preview in a Crystallize custom view: route, draft reads, framing |
| references/nextjs-pitfalls.md | Next.js 16 Cache Components and PPR traps |
Related skills
[[query]] and [[mutation]] hold the API details. [[pricing]] covers price variants, price lists and the cart price context; [[payments]] the provider session and webhook; [[bookable-resources]] and [[subscriptions]] their flows. [[vector-ranking]] ranks rails and search per shopper. [[responsive-images]] covers images. [[information-architecture]] covers paths. [[seo-geo]] makes the store findable and quotable; [[agentic-commerce]] lets AI agents shop it on the same code.
Reference Details
Accessibility
The accessibility tree is what screen readers read, and it is also what AI browsers and in-browser agents read and
act on. A drawer that is hidden but focusable, or a quantity that is a <span> between two buttons, is broken for
both. These are the gaps a Modern Web Guidance (MWG v1.0) audit found on two Crystallize storefronts, with the fix
for each.
Drawers and dialogs (cart, assistant, filters)
What was wrong: an <aside role="dialog"> without aria-modal; when closed, a wrapper with aria-hidden that
stayed focusable (only translated off-screen), so Tab reached the hidden close button and textarea; when open,
the page behind was not inert, focus did not move in or come back, and Escape was a hand-written listener.
Use a native <dialog> opened with showModal(). The browser then makes the rest of the page inert, exposes a
modal dialog, handles Escape and returns focus on close.
- Name it with
aria-labelledbypointing at its heading. Putautofocuson the first control. closedby="any"for light dismiss.- No
role="dialog", focus trap or Escape handler of your own. - Never
aria-hidden="true"on a focusable element or its parent. A closed drawer is not rendered, or isinert. - Don’t lock scroll with
overflow: hiddenon<html>or<body>(layout shift, broken sticky elements). Useoverscroll-behavior: containondialog:modalandoverflow: hiddenondialog::backdrop. - Closed drawers cast no shadow onto the page edge.
Skip link
Put a skip link first in <body>, before the header and mega menu (WCAG 2.4.1). One store had about 60 KB of
header and menu, with dozens of links, before <main>.
<body> <a href="#main" className="skip-link"> {t.skipToContent} </a> <Header lang={lang} /> <main id="main">{children}</main></body>Style .skip-link off-screen until :focus-visible.
Focus
- A focus indicator with a contrast ratio of at least 3:1 against what is around it. A lime outline measured 1.5:1 on the page’s off-white.
- Inputs must not replace the outline with a 1 px border change.
:focus-visible, not:focus.
Forms: quantity, steppers, errors, autofill
- Quantity is a labelled native control:
<input type="number" name="quantity" min="1">. Steppers have names that include the product (“Decrease quantity of Combi drill 18V”), not−or−1. An agent can then read and set the quantity instead of clicking N times, and an agentic form can build its schema from it. - Variant options are native radio inputs in a
fieldsetwith alegend. - Announce errors: a live region (
role="alert"for errors,role="status"for progress) or move focus to the message. A plain<p class="error">is silent. - Enter to submit in a textarea or a search box checks
isComposing(skip whene.nativeEvent.isComposing || e.keyCode === 229), so an IME user doesn’t send half-composed text. - Autofill on checkout fields:
autocomplete="email",name,shipping street-address,postal-code,cc-number, and so on. Offer guest checkout.
Structure
- One
<h1>per page, and an unbroken heading outline. Watch Suspense fallbacks: a fallback with its own<h1>plus the resolved content gave a category page two in the raw HTML. - Breadcrumbs:
<nav aria-label="Breadcrumbs"><ol>, the last item witharia-current="page", dividers in CSS. - Wrap search and filtering in
<search>rather than<form role="search">. - Landmarks: one
<main>, labelled<nav>s. - The search combobox:
role="combobox",aria-expanded,aria-controls,aria-activedescendant, alistbox, and a real GETactionso it works without JavaScript. - Facets as plain GET links: every filtered view is crawlable, linkable and usable by an agent without JavaScript.
Chat and streaming text
- A chat log is
role="log", but don’t update it token by token: debounce, or announce the finished message. - “Thinking” is
role="status"text or a<progress>, not anaria-labelon a<p>. - Render model output as elements, never with
innerHTML.
Motion
Don’t kill all motion with a global animation-duration: 0.01ms under prefers-reduced-motion. Drop the
movement (drawer slide, menu translate, scale on hover) and keep non-spatial transitions.
The storefront API contract
Which API a storefront calls for each task, with which token, from where. The rule in one line: Discovery for every catalogue read, the Shop API for everything about a shopper, Catalogue and Core only for the tasks named here.
Decision table
| Task | API | Call | Token / scope | Where |
|---|---|---|---|---|
| Item by path (product, category, document) | Discovery | search(language, filters: { path: { equals } }), then shape fragments |
none / static | server, cached |
| Category listing | Discovery | browse.<shape>(filters: { parentPaths: { equals } }) (any depth); the parentPaths facet for subfolders |
none / static | server, cached |
| Facets | Discovery | summary { facets }. Each selection option is its own field (<field>_<optionKeyCamel>, exists: true); a NumberFacet needs at least two boundaries |
none / static | server |
| Card per colourway | Discovery | variantGroups(by, filter, first) with matched, summary, representative |
none / static | server |
| Variant pick on the PDP | Discovery | variant(selected: [{ attribute, value }]), then the SKU into hydrate |
none / static | server |
| Search results | Discovery | term + options: { fuzzy: { fuzziness: SINGLE } }, sorting: { score: desc }; add { signal: relevance } when rankBy is used |
none / static | server |
| Typeahead | Discovery | filters: { name: { autocomplete: { term } } } plus the same term for scoring; drop score == 0. Or an in-memory index built from one Discovery snapshot |
none / static | server route or browser index |
| Translated paths, hreflang, sitemap | Discovery | One aliased query per language by itemId; a sitemap is one browse per language joined on itemId |
none / static | server, build |
| Personal ranking, “more like this” | Discovery | rankBy + context.userTaste (rebuilt from Shop order history) + nearestTo |
none / static | server |
| List, sale, “from” price | Discovery | <variant>Price, variantGroups.summary.price |
none / static | server |
| Public market price | Discovery | <variant>PriceFor(marketIdentifiers); only for the SKUs on screen |
none / static | server |
| Contract price for display (B2B) | Shop API, Catalogue | A throw-away hydrate with the customer, or Catalogue priceFor(customerIdentifiers), cached per organisation. Never Discovery |
cart / Catalogue token |
server |
| Stock on the page | Discovery | <location>Stock per variant, inStock, stock_<location> filters. A new stock location needs a re-ignite |
none / static | server |
| Create or change the cart | Shop /cart |
hydrate with the whole item list (it replaces), or addSkuItem; batch client changes into one hydrate |
cart |
server action |
| Price the cart for customer and market | Shop /cart |
context.price { currency, selectedVariantIdentifier, fallbackVariantIdentifiers, compareAtVariantIdentifier, markets, customerGroups, voucherCodes, decimals, taxRate } |
cart |
server |
| Customer on the cart | Shop /cart |
setCustomer, or hydrate(customer: { identifier, isGuest: false }); for B2B the organisation; before any booking |
cart |
server |
| Validate a voucher | Shop /cart |
validateVoucher(voucher) |
cart |
server |
| Lock the cart before charging | Shop /cart |
place (it hydrates one last time; charge its total) |
cart |
server |
| Order from the cart | Shop /order |
createFromCart(id, { pipelines, paymentStatus, payments }); cart meta is copied; no fulfill afterwards |
order |
server, payment webhook |
| Order without a cart (accepted quote, POS) | Shop /order |
create (takes relatedOrderIds) |
order |
server |
| Record payments | Shop /order |
addPayments / setPayments; paymentStatus is set once, at creation |
order |
server |
| Move the order through stages | Shop /order |
addToStage(id, pipelineId, stageId) (ids, not names), then setMeta |
order |
server, back office |
| Order confirmation page | Shop /order |
The order createFromCart returned; order(id) can be “not found” for a moment |
order |
server |
| Shopper’s order history | Shop /order |
orders(customerIdentifier, limit: 100); it lags and can be incomplete |
order |
server; identifier from the session |
| Customer record from the storefront | Shop /customer |
customer(input), addAddress, setMeta (synced to Core) |
customer |
server |
| Booking availability | Shop /cart |
availability, nearestAvailability, checkBooking (Discovery never serves availability) |
cart |
server, after the product |
| Hold, change, release a booking | Shop /cart |
bookSkuItem (one at a time per cart); re-hydrate without the line to release it |
cart |
server |
| Confirm a booking | Shop /cart |
confirmCartBooking before and after createFromCart, once cart.orderId is set |
cart |
server |
| Read or cancel any reservation (staff) | Shop /booking/admin |
reservation(id), cancel(id, reason), block, calendar; see [[bookable-resources]] |
booking + booking:admin (both; one alone is “Invalid Scopes”) |
server, staff |
| Subscription sign-up and account page | One store per tenant | Shop /subscription-contract or Core; see [[subscriptions]] |
own token / pair | server |
| Usage metering | Core only | trackSubscriptionContractUsage, one call per metered event, never per page view |
pair | server |
| Idempotency guard | Shop /lock |
acquire and release | lock |
server |
| Pipeline stage names for display | PIM | pipeline.getMany at build time; write the ids into the storefront’s data |
pair | build |
| Cache revalidation on publish | Core (setup) | createWebhook(concern: "items") with graphqlQuery and preserveDefaultPayload: true |
pair (setup) | setup; receiver is a server route |
| Draft preview | Discovery | publicationState: draft; never cached. On an open Discovery drafts are public; restrict it if they must stay private |
none / static | server, behind preview mode |
| Seller or approval queue across customers | Core | orders(filter: { … }) behind staff login, or an index fed by webhooks |
pair | back office server |
| Seeding, model, publish, ignite, taste | Core, PIM, mass operations | — | pair | scripts only |
Field names on Discovery (nokPrice, <location>Stock, price_default, specs_drilling_torque_number) are
generated from the tenant’s identifiers; read them from the schema, see [[query]].
Where the order lives
Write an order in one store and read it from the same store. A storefront that lists orders from the Shop API
creates them on the Shop API (createFromCart, or create without a cart). Core registerOrder is for orders
nobody reads from the edge, such as imports into a back office. The order store table in [[mutation]] is the
rule.
Shop API token rules
- Minted with
POST https://shop-api.crystallize.com/{tenant}/auth/tokenand{ scopes, expiresIn }, using an access token pair. A pair scoped to the tenant mints for that tenant only; an unscoped pair for any tenant its user belongs to ([[permissions]]). The@before the tenant is optional on the Shop API. - Per tenant, not per shopper. Cache it server-side; refresh before
exp. Expiry is one day by default in the API and 12 hours in@crystallize/js-api-client. "exp" claim timestamp check failedmeans the cached token expired. A rejected token answers 401 with{ success: false }and noerrors.- The Shop API allows browser calls only from Crystallize origins and localhost. Production calls are server-side (server action or route), always.
Things that look like contradictions
- “Discovery is public.” It is open by default and can be restricted with a static token, which takes effect only after a re-ignite. When open, everything it serves is public.
- “Catalogue for exact paths.” Discovery resolves paths. Catalogue
variantscame back empty on several tenants; keep it for per-customer price lists. - Customer price resolution. Discovery resolves markets only. The Shop API resolves the cart’s customer (price lists inherited from parent customers). Catalogue resolves any customer for display.
- Payments code that reads Core. That runs in the payment webhook, not in page code; it is not the request path. See [[payments]].
- Deterministic secondary sort. Discovery applies sort keys in schema order, so a second key such as
itemIdcan replace a primary that sorts after it. Use one key per sort, or check the order;scoreis safe as the primary.{ itemId: asc }alone is stable for full scans.
Caching Discovery and revalidating on publish
Discovery is fast, but a storefront that reads it on every request pays for it in latency and rate limits. Cache every published read on the server, clear the cache when something is published, and never cache what is per-shopper or a draft.
Cache published reads, keyed on query and variables
In Next.js 16 with Cache Components, a 'use cache' function is keyed on its arguments. Pass the query string and
variables, tag the entry, and pick a life:
async function cached<T>(query: string, variables: Record<string, unknown>): Promise<T> { "use cache: remote"; cacheLife("hours"); cacheTag("discovery"); return request<T>(query, variables, false);}'use cache: remote'on serverless hosts. The default in-memory cache lives per instance, so a read paid for on one instance was paid again on the next. The remote handler is shared by every instance.cacheLife('hours'), not minutes. Every revalidation is a cache write, and on Vercel those are billed: one build found Runtime Cache writes were about $140 of a $226 cycle with a one-minute life. Hours plus the publish webhook keeps pages fresh without the bill.- Build variables in a fixed order. The cache key is the serialised arguments;
{ a, b }and{ b, a }are two entries, and a prerender then misses its own cache. - Keep clocks out of cache keys. A taste vector whose decay used
Date.now()made every render’s keys differ (“unexpected cache miss after cache warming”). Round time to the day. - Cached reads never throw a transient error into the cache. Retry inside the request (429 and 5xx, with
backoff). A failing query inside
'use cache'broke background revalidation in one build; another made cached reads return an empty result on failure rather than throw. - Rails and menus skip
facets(about 17 KB per read) and select only the image widths they render.
Revalidate on publish with a webhook
Crystallize calls a URL when an item is published or unpublished. Register the webhook once, from a setup script on the Core API (trimmed from a working seed step):
// The default payload is { id, type, tenantId, language, userId, webhookId }; the query adds the item's path.const ITEM_QUERY = `query ($id: ID!, $language: String!) { item(id: $id, language: $language) { ... on Item { id shapeIdentifier tree { path } } }}`;
// concern is `items` (plural): `item` is accepted by createWebhook but never fires.const WEBHOOKS = [ { name: "storefront-revalidate-publish", concern: "items", event: "publish" }, { name: "storefront-revalidate-unpublish", concern: "items", event: "unpublish" },];
for (const w of WEBHOOKS) { const input = { ...w, url: "https://shop.example/api/revalidate", method: "POST", headers: [ { name: "x-revalidate-secret", value: process.env.REVALIDATE_SECRET }, { name: "content-type", value: "application/json" }, ], preserveDefaultPayload: true, graphqlQuery: ITEM_QUERY, graphqlQueryTarget: "next", }; await core( `mutation ($input: CreateWebhookInput!) { createWebhook(input: $input) { ... on Webhook { id } ... on BasicError { errorName message } } }`, { input }, );}Make the script idempotent: list webhooks(first: 100) first, and updateWebhook the ones that exist by name.
Keep the secret in a header, never in the URL.
The receiving route checks the secret and clears tags. With one discovery tag, everything follows at once:
import { revalidateTag } from "next/cache";import { NextResponse, type NextRequest } from "next/server";
export async function POST(req: NextRequest) { const secret = process.env.REVALIDATE_SECRET; if (!secret || req.headers.get("x-revalidate-secret") !== secret) return NextResponse.json({ ok: false }, { status: 401 }); revalidateTag("discovery", "max"); return NextResponse.json({ ok: true });}Finer tags are possible: the payload carries item.tree.path from the webhook’s query, so a route can clear
product:<slug> and categories instead of everything. One build measured a summary edit showing on production
21 seconds after publish, with stale-while-revalidate ('max').
Publishing is asynchronous (publishItem answers before anything is indexed), so in principle the webhook can
arrive before Discovery serves the new version. The builds did not measure this; if a page re-renders with old
content, delay the revalidation a few seconds.
Pages, JSON-LD, the sitemap, Markdown twins and llms.txt all read through the same cached client, so one tag clears them all. See [[seo-geo]].
Per-customer caches
Order history, the taste vector built from it, and contract prices change rarely and are slow to read. Cache them per customer or per organisation, with a tag the checkout can expire:
export const historyTag = (buyer: string) => `orders:${buyer}`;
export async function tasteForBuyer(buyer: string) { "use cache: remote"; cacheLife("hours"); cacheTag(historyTag(buyer)); const orders = await orderHistory(buyer); // Shop API orders(customerIdentifier) const today = Math.floor(Date.now() / 86_400_000) * 86_400_000; // stable all day return tasteOf(orders, today);}
// In the checkout server action, after createFromCart:updateTag(historyTag(buyer));A read inside 'use cache' must not call connection() or other request APIs: split the Shop client into a
request-only function for these and a connection()-marked one for cart calls.
Never cache
- Draft reads. Preview reads (
publicationState: draft) go straight to Discovery. In Next.js, switch ondraftMode()inside the cached client: see preview.md. - Carts. Every cart read and write is request data.
- Anything keyed on a cookie that is not part of the cache key.
Prefetch is a cost, too
Prefetching every link in view multiplies cached reads and, on hosts that bill cache reads and writes, the bill. Prefetch on intent (hover, focus, touch) instead. See performance.md.
Cart and checkout on the Shop API
The browser holds the cart id in an httpOnly cookie. Every cart read and write is a server action or route calling the Shop API with the server’s JWT. Mutation shapes and their options are in [[mutation]]; the price context in [[pricing]]; payment providers in [[payments]].
The cart is a hydrate
hydrate replaces the whole cart. A server action reads the current cart, applies the change to the full list of
lines, and hydrates all of them (trimmed from a working storefront):
"use server";import { cookies } from "next/headers";import { refresh } from "next/cache";
async function change(lang: string, update: (lines: Map<string, number>) => void) { const jar = await cookies(); const customer = await currentCustomer(); // the signed-in buyer, or undefined const cart = await getCart(jar.get("cart")?.value, lang, customer); // Booked lines pass through untouched; the rest are edited by SKU. const booked = (cart?.lines ?? []).filter((l) => l.booking); const lines = new Map((cart?.lines ?? []).filter((l) => !l.booking).map((l) => [l.sku, l.quantity])); update(lines); const items = [...booked.map(lineInput), ...[...lines].map(([sku, quantity]) => ({ sku, quantity }))]; const next = await hydrate(cart?.id, items, lang, customer); jar.set("cart", next.id, { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30 }); refresh(); return next.count;}
export const addToCart = (sku: string, quantity: number, lang: string) => change(lang, (l) => l.set(sku, (l.get(sku) ?? 0) + quantity));export const setQuantity = (sku: string, quantity: number, lang: string) => change(lang, (l) => (quantity > 0 ? l.set(sku, quantity) : l.delete(sku)));The hydrate itself, with the price context for the language’s market:
const FIELDS = `id state isStale updatedAt context customer { identifier } items { lineId name quantity meta variant { sku product { path name } price { net } } price { net } } total { net gross taxAmount }`;
export async function hydrate( id: string | undefined, items: LineInput[], language: string, customer?: CartCustomer, markets: string[] = [],) { const m = MARKET[language]; const { hydrate } = await shop<{ hydrate: RawCart }>( `mutation Hydrate($input: CartInput!) { hydrate(input: $input) { ${FIELDS} } }`, { input: { ...(id ? { id } : {}), ...(customer ? { customer } : {}), items: items.filter((i) => i.quantity > 0), context: { language, price: { currency: m.currency, selectedVariantIdentifier: m.priceVariant, pricesHaveTaxesIncludedInCrystallize: false, taxRate: m.vat, // a fraction: 0.25 decimals: 4, // exact line and tax amounts; round for display only markets, // the buyer's price-list markets, from the server session: whoever sends a market gets its prices }, }, }, }, ); return toCart(hydrate);}price.neton a cart line is the line total;variant.price.netis the unit price. Order lines carry the unit price.- A booked line keeps its booking only if it comes back with its
lineId,metaandbooking. Hydrating without it releases the reservation. See [[bookable-resources]]. - An unknown SKU was seen both failing the whole call and silently dropping the line. Check SKUs against Discovery in parallel, and check the answer for the line you added.
- Cart meta becomes order meta:
createFromCartcopies it.
Reading a stored cart
Re-hydrate when the stored cart could be priced wrong: it is stale, it was built in another language, or for another customer (a company’s price lists only apply to a cart hydrated with that company).
export async function getCart( id: string | undefined, language: string, customer?: CartCustomer, markets: string[] = [],) { if (!id) return null; const { cart } = await shop<{ cart: RawCart | null }>(`query Cart($id: UUID!) { cart(id: $id) { ${FIELDS} } }`, { id, }).catch(() => ({ cart: null })); if (!cart || cart.state !== "cart") return null; // placed or ordered: start a new one const other = cart.context.language !== language || (cart.customer?.identifier ?? undefined) !== customer?.identifier; if (cart.isStale || other) return hydrate(id, toCart(cart).lines.map(lineInput), language, customer, markets); return toCart(cart);}The drawer
- Show the line at once (optimistic), then replace the drawer with the hydrate’s answer. The hydrate takes about 200–400 ms; the optimistic line shows in a few milliseconds.
- Batch rapid quantity changes into one hydrate.
- Quantity is a labelled native control, and steppers are named after the product (accessibility.md). An agent or a screen reader can then read and set it.
Checkout
The order of calls matters. In a server action:
- Hydrate one last time with the customer and the final lines (product names in line meta if you want them on the order).
setCustomer. For B2B, the organisation, with the person who ordered in cart meta.setMeta(merge: true): market, segment, PO reference, project.place. The cart is now locked; chargeplace’stotal. If order creation fails after this, the shopper needs a new cart.- Bookings:
confirmCartBooking(cartId)before the order, which checks the holds still stand. - Payment: create the provider session on the server from the placed total ([[payments]]). In the provider’s webhook, verify, then:
createFromCart(id, { type, paymentStatus, payments, pipelines })on/order, all in the input, not chained. Nofulfillafterwards:createFromCartalready moves the cart toordered.- Bookings again: poll
cart { orderId }until it is set (about 0.5 s), thenconfirmCartBookingagain, which links the reservations to the order. - Delete the cart cookie, expire the buyer’s cached history (
updateTag), show the confirmation.
await shop(`mutation($id: UUID!, $c: CustomerInput!) { setCustomer(id: $id, input: $c) { id } }`, { id, c: customer });await shop(`mutation($id: UUID!, $meta: [KeyValueInput!]!) { setMeta(id: $id, meta: $meta, merge: true) { id } }`, { id, meta,});await shop(`mutation($id: UUID!) { place(id: $id) { id } }`, { id });
const { createFromCart: order } = await shop<{ createFromCart: { id: string } }>( `mutation($id: UUID!, $input: OrderFromCartInput!) { createFromCart(id: $id, input: $input) { id } }`, { id, input: { type: "standard", paymentStatus: "paid", payments: [{ provider: "custom", method: "card", amount: cart.gross, transactionId: providerReference }], pipelines: [{ identifier: pipelineId, stage: stageId }], // ids from PIM pipeline.getMany at build time }, }, "order",);- A guest is
{ isGuest: true, identifier: email, firstName, lastName, email }; a signed-in buyer is{ identifier, isGuest: false, … }. Put the customer on the cart before any booking. additionalInformation: nullis refused: leave the key out. The error is a bare “Output validation error”, which doesn’t name the field.- Pipeline and stage ids, not names. Read them with PIM
pipeline.getManyat build time.
Quotes and invoice
A quote is createFromCart with type: "quote", no payment, and a quotes pipeline. Accepting it creates the
order with Shop create (lines and prices from the quote, relatedOrderIds: [quoteId]), then moves the quote’s
stage. Invoice checkout is paymentStatus: "unpaid" with a custom payment, for signed-in trade buyers, after a
credit check against their open orders.
The confirmation page
- Show the order
createFromCartreturned.order(id)can answer “not found” for a moment after creation; retry if you must read it. - Booking details come from the order meta snapshot.
- Later visits list
orders(customerIdentifier, limit: 100)on/order. New orders can take seconds to minutes to appear there, and paging withlimit/skipwas inconsistent: read one page, and say on the confirmation page that history updates shortly.
Agents in the checkout
An AI agent’s basket has no cookie: it travels as a cartId, and a signed hand-off link lets the shopper’s
browser adopt it and finish payment in the store. See [[agentic-commerce]].
Language and market routing, translated paths, hreflang
Crystallize translates item paths per language, so /en/sawing/circular-saw-x and /no/sager/sirkelsag-x are
the same item. A storefront routes on the language in the path, resolves the item by its path in that language,
and finds the same item in other languages by itemId.
Language (and market) in the path
Put the language, and the market when it differs from the language, in the first path segment. Do not choose the market by cookie: crawlers carry no cookies, so they only ever see the default market’s prices, and the JSON-LD then has to say so.
A proxy (Next.js 16 proxy.ts, formerly middleware.ts) sends a bare URL to a language: the cookie, then
Accept-Language, then the default. Trimmed from a working storefront:
import { NextResponse, type NextRequest } from "next/server";
const LANGS = ["en", "no", "sv", "nl"];
export function proxy(request: NextRequest) { const { pathname } = request.nextUrl; if (LANGS.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`))) return NextResponse.next(); const cookie = request.cookies.get("lang")?.value; const accepted = (request.headers.get("accept-language") ?? "").toLowerCase(); const fromHeader = LANGS.find((l) => accepted.startsWith(l) || (l === "no" && /^(nb|nn)/.test(accepted))); const lang = LANGS.includes(cookie ?? "") ? cookie : (fromHeader ?? "en"); request.nextUrl.pathname = `/${lang}${pathname === "/" ? "" : pathname}`; return NextResponse.redirect(request.nextUrl);}
// Keep Next internals, API routes and files (robots.txt, sitemap.xml, icons) out of the language redirect.export const config = { matcher: ["/((?!_next|api|favicon.ico|icon|apple-icon|.*\\..*).*)"] };- Icon routes (
icon,apple-icon),/.well-known/*, OAuth and webhook routes stay outside the language proxy. - The proxy also serves Markdown twins (
.md,Accept: text/markdown); see [[seo-geo]]. - Map each language to its market in one place: currency, price variant identifier, VAT rate, locale.
export const MARKET = { en: { currency: "EUR", priceVariant: "default", vat: 0.21, locale: "en-IE" }, no: { currency: "NOK", priceVariant: "nok", vat: 0.25, locale: "nb-NO" }, sv: { currency: "SEK", priceVariant: "sek", vat: 0.25, locale: "sv-SE" },} as const;Tenant language codes vs BCP 47
Use BCP 47 for <html lang>, hreflang, og:locale and schema.org inLanguage. A tenant’s language code is not
always one: Norwegian content in a tenant language no is Bokmål, nb.
export const HREFLANG = { en: "en", no: "nb", sv: "sv", nl: "nl" };export const OG_LOCALE = { en: "en_IE", no: "nb_NO", sv: "sv_SE", nl: "nl_NL" };In Discovery, a tenant language with a hyphen becomes camelCase in the TenantLanguage enum (nb-no is nbNo).
The same item in every language
Paths are translated and can be re-slugged, so never match by slug. One aliased query by itemId returns the
item’s path in every language:
export async function pathsForItem(itemId: string) { const q = LANGS.map( (l) => `${l}: search(language: ${l}, filters: { itemId: { equals: $id } }, pagination: { limit: 1 }) { hits { path } }`, ).join("\n"); const data = await discovery<Record<string, { hits: { path: string }[] }>>(`query Paths($id: String!) { ${q} }`, { id: itemId, }); return Object.fromEntries(LANGS.flatMap((l) => (data[l].hits[0] ? [[l, `/${l}${data[l].hits[0].path}`]] : [])));}
/** Next.js `alternates`: canonical for this language, hreflang for every language, x-default. */export function alternates(paths: Record<string, string>, lang: string) { return { canonical: absolute(paths[lang]), languages: { ...Object.fromEntries(LANGS.flatMap((l) => (paths[l] ? [[HREFLANG[l], absolute(paths[l])]] : []))), "x-default": absolute(paths.en ?? paths[lang]), }, };}- A language without the item has no hit: leave it out of hreflang rather than pointing at a 404.
- For a sitemap, one
browseper language, joined onitemId(see [[seo-geo]]). - Folders map across languages the same way. A folder’s topic path is a usable cross-language key when folders mirror a taxonomy.
- A renamed path goes to the item’s path history: 301 old URLs to the current path, and keep them out of the sitemap. See [[information-architecture]].
The language switcher
Link each language to its front page (so it works without JavaScript), and on click ask a route for the current page’s path in the target language:
// GET /api/language?to=no&path=/en/sawing/x → { href: "/no/sager/x" }const APP_PAGES = new Set(["", "cart", "account", "search"]);
export async function GET(req: NextRequest) { const to = req.nextUrl.searchParams.get("to") ?? ""; const [pathname, query = ""] = (req.nextUrl.searchParams.get("path") ?? "/").split("?"); const [, from, ...rest] = pathname.split("/"); const target = (path: string) => NextResponse.json({ href: `/${to}${path}${query ? `?${query}` : ""}` }); if (APP_PAGES.has(rest[0] ?? "")) return target(rest.length ? `/${rest.join("/")}` : ""); const item = await resolveItem(`/${rest.join("/")}`, from); // Discovery: path → itemId const path = item ? await pathInLanguage(item.itemId, to) : null; // Discovery: itemId → path return target(path ?? "");}Facet values that are topic paths are language-independent, so a filtered category keeps its filters across the switch. Prefetching the target language’s page on hover makes the switch feel instant.
Content that is missing in a language
An item exists per language, but its text components may be empty in one. Test for content, not for a hit: a product with no name or description in a language is a fallback case (show the default language’s text, or leave the item out of that language’s listings and sitemap), not a page to render empty.
Next.js 16 pitfalls on a Crystallize storefront
Most builds behind this skill used Next.js 16 (16.3–16.4) with cacheComponents: true on Vercel. These are the
traps they hit, with what worked. They are framework behaviour rather than Crystallize behaviour, so re-check
them on the version you run.
Shape of the app
- A static shell plus cached Discovery reads; per-shopper parts stream behind
<Suspense>. The layout reads no cookies. A layout that reads cookies makes every route dynamic, and thenstaleTimes.dynamic(for example 20 s) is needed, or a prefetched payload is thrown away the moment it arrives. - A page that depends on
paramssits behind<Suspense>, so the route’s shell (layout and skeleton) is shared by every link to it. Next 16.4 with partial prefetching errors onawait paramsoutside a boundary. - Make the fallback real content where you can. While a category’s filters and personal ranking stream, the fallback is the same category in its default order (cached), not a skeleton.
- Every internal link is a
next/link, prefetched on intent (performance.md). Test prefetching in a production build in a visible browser:next devdoesn’t prefetch, and a hidden or background tab prefetches nothing and doesn’t reveal streamed Suspense content (it waits forrequestAnimationFrame).
Request data and the prerender
await connection()before Core or Shop API reads and beforenew Date()in a request-time render. An uncachedfetchdoes not mark the render dynamic by itself, andnew Date()after it errors as an “unstable value during prerendering”.- A read inside
'use cache'must not callconnection(). Keep two entry points to the Shop API client: one that marks the render dynamic (carts) and a plain request for cached per-customer reads (order history). - Client components calling
usePathname()in a layout need a<Suspense>with a static fallback, ornext buildfails prerendering. 'use server'files may export only async functions. Keep cookie names and constants in another module.
Cache keys
- Arguments to a cached function must be identical on every render. Next renders a prerender twice (warm-up, then final). Build objects and arrays in a fixed order (sort SKU lists, sort keys); an order that depends on an API response misses the cache the second time (“Unexpected cache miss after cache warming phase”) and the prefetch answers 503.
- Keep the clock out of keys. Day-bucket anything time-based.
- Cached functions never throw. A failed read during warming leaves no entry and becomes a miss; one build
returns
{ error }withcacheLife('seconds')instead. The same warning was still seen in Vercel logs with deterministic arguments and was benign (the part became a dynamic hole). - Large cached reads bloat
.meta. A 2.5 MB index read directly during prerender made each page’s.meta526 KB (240 MB of the build). Reading it through a small keyed cache function brought it to 55 KB per page.
404s and redirects under a PPR shell
notFound()orpermanentRedirect()inside<Suspense>streams HTTP 200: the status is sent with the shell. The page still renders “not found” and carriesnoindex, so it doesn’t get indexed, but crawlers and monitoring see a 200.- What was tried: resolving the lookup in a cached function outside Suspense with
export const instant = falseworked in one round and not in a later one (still open). The pattern that worked: the proxy checks a cached index of valid paths and rewrites misses to a static route that callsnotFound(). dynamicParamsisn’t available with Cache Components.
Metadata for crawlers
A dynamic generateMetadata streams into <body>. With a cached shell on a CDN, Googlebot got pages with no
<title>, canonical or hreflang at all. Give every sitemap path its own prerendered shell
(generateStaticParams) and keep generateMetadata free of request APIs. Full write-up in
performance.md; crawler side in
[[seo-geo]].
Bots in htmlLimitedBots that reached catch-all pages unknown at build hit “Expected the resume to render
Loading states
loading.tsxon the segment that changes replaces the visible page and hides optimistic UI. Moving it one level up kept sibling navigation instant in one build (a colour switch went from 813 ms to 26 ms).- Don’t remove
<Suspense>wrappers because streamed content “never appears” in an automated browser: that is the hidden-tab behaviour above, not a bug.
Prefetching
- With Cache Components, the default
<Link>prefetch of a 16-card grid cost 136 KB on arrival. Intent prefetch outside the first row brought it to 37 KB. partialPrefetching(Next 16.3) gave intermittent 503s on shell-route prefetches in one build, and worked in others. Test it with your routes before relying on it.
Deploying on Vercel
- Set the function region (
"regions": ["fra1"]invercel.json, and on the project) next to the tenant. vercel env add --forcedoes not overwrite sensitive variables, and their values can’t be read back. One site ran on fixtures without anyone noticing. Usermthenadd, and expose a no-secrets status route (mode, tenant, a live probe).next startlocally differs from Vercel: it doesn’t send the fontLink: rel=preloadheader Vercel sends, and it upgraded the App Shell after the first visit while production didn’t. Compare local with local, and test crawler behaviour on the deployment.
Performance
What made Crystallize storefronts fast or slow in practice, plus the gaps a Modern Web Guidance (MWG v1.0) audit found on a live store. Images are covered by [[responsive-images]]; read it rather than repeating it here.
Run next to the API
Put server functions in the region nearest the tenant’s API and media (fra1 on Vercel for EU tenants):
{ "regions": ["fra1"] }Every page makes several Discovery reads; a transatlantic hop on each one adds up to hundreds of milliseconds.
Prefetch on intent, not on view
A framework link that prefetches every card in view renders every linked page on the server. On a category page with a mega menu, that was most of one demo’s hosting bill. Prefetch on hover, focus or touch:
"use client";import Link from "next/link";import { useState, type ComponentProps } from "react";
export function IntentLink(props: Omit<ComponentProps<typeof Link>, "prefetch">) { const [intent, setIntent] = useState(false); const show = () => setIntent(true); return <Link {...props} prefetch={intent} onMouseEnter={show} onTouchStart={show} onFocus={show} />;}Only the hovered link counts: opening a menu must not count as intent for all its links. Speculation rules do not apply to an App Router site, which navigates client-side.
Prerender, or render on demand
Prerendering every product page puts the whole catalogue through Discovery during the build. One build got
HTTP 200 with errors: [{ message: "Response Error" }] after about 900 pages. Options:
- Prerender what the sitemap lists, with capped concurrency and a retry on “Response Error”.
- Render on demand and cache, for very large catalogues.
Either way, every URL served must have its own metadata in <head> (below).
The LCP image
- Get the LCP resource into the early HTML. On one store, product and category pages had the LCP image’s
<link rel="preload">at byte 282,186 of the HTML, after a 60 KB header and mega menu. Stream above-the-fold content first, and keep the hero out of a late Suspense boundary. Putting the LCP image in the PPR shell was the biggest listing LCP win in another build. - Preconnect to the media host, without
crossOrigin:<img>requests are no-cors and won’t reuse a CORS connection. In React:preconnect('https://media.crystallize.com')fromreact-domin the root layout. - At most one or two
fetchpriority="high"images and preloads per page. One home page had 5 image preloads and 9 high-priority images. - Hidden mega-menu images get
fetchpriority="low", or are not rendered until the menu opens. One store rendered about 62 menu images into every page’s HTML. - Discovery has no dominant colour or blur hash; generate placeholders at import if you need them.
Payload
- Ask Discovery only for the image widths a slot uses (
variants(types: "webp", minWidth, maxWidth)). Cards up to about 1024 px, gallery 1920, chat cards 500. One build cut a listing read from 345 KB to 108 KB by selecting widths only. Repeatedvariants { images }on a product with 260 sizes made 24 cards 8.2 MB and broke the cache. - Skip
facetson rails and menus. - Large cached reads bloat the RSC payload of every page that uses them.
content-visibility: autoon long below-the-fold sections.
Fonts
Self-host with next/font (display: swap, size-adjust fallbacks); preload only the one or two faces used above
the fold.
Field data
Measure in the field: web-vitals (attribution build) beaconed to your own route. Without it, INP, LCP and CLS
from real shoppers are unknown.
Pitfall: metadata must be in the cached shell’s <head>
Found in the MWG audit and confirmed on a live store.
- With Next.js Cache Components and PPR, a dynamic
generateMetadatais streamed into<body>instead of the static shell’s<head>. - On Vercel, real Googlebot user agents were served the cached shell (
x-vercel-cache: HIT) with no<title>, description, canonical or hreflang on product and category pages. bingbot and AI crawlers gotBYPASSand a full<head>. Browsers got the title about 300 KB into the HTML. Google ignores canonical and hreflang outside<head>. htmlLimitedBotsdoesn’t help when the cached shell wins.- A catch-all route without
generateStaticParamsserves one App Shell for every URL, and that shell can’t hold metadata that depends on the path.
The rule: keep metadata cacheable.
- Build
generateMetadataonly from cached Discovery reads, with no request-time APIs (cookies(),headers(),searchParams), so it lands in the shell’s<head>for every user agent. - Give every sitemap path its own prerendered shell with
generateStaticParams. Items published after the build get the App Shell on their first visit and are prerendered then. - A search page’s metadata must not read
searchParams: make it static (the page isnoindexanyway).
export async function generateStaticParams({ params }: { params: { lang: string } }) { return (await catalogPaths(params.lang)).map((p) => ({ path: p.split("/").filter(Boolean) }));}
export async function generateMetadata({ params }: PageProps<"/[lang]/[...path]">): Promise<Metadata> { const { lang, path } = await params; // params only: no cookies, headers or searchParams return itemMetadata("/" + path.map(decodeURIComponent).join("/"), lang); // cached Discovery reads}Verify with the real Googlebot strings, desktop and smartphone, not a shortened UA, and look at
x-vercel-cache and where <title> sits. A local next start upgraded the App Shell after the first visit while
production did not, so test the deployment:
UA='Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Chrome/138.0.0.0 Safari/537.36'curl -sI -A "$UA" https://shop.example/en/some/product | grep -i x-vercel-cachecurl -s -A "$UA" https://shop.example/en/some/product | head -c 4000 | grep -o '<title>[^<]*</title>\|rel="canonical"[^>]*\|hreflang="[^"]*"'Repeat with the smartphone Googlebot UA, bingbot and an AI crawler. The same rule, from the crawler’s side, is in [[seo-geo]].
Low-priority items from the audit
- Declare
color-scheme(<meta name="color-scheme" content="light">for a light-only design) andtheme-color. - A web app manifest (
app/manifest.ts). Cache-Control: public, max-age=0, must-revalidaterather thanno-store, so nothing blocks the back/forward cache.
Frontend preview with custom views
Editors preview a draft inside the Crystallize App: a custom view frames your storefront next to the item they are editing. The App supplies the frame, the device toolbar and the reload; the storefront supplies one route that turns preview mode on, and pages that read drafts in that mode. From a working Next.js 16 storefront (tools-universe, Cache Components, verified with a production build on 2026-11-12). Read the App side in the docs: Custom views.
1. The custom view (in the App)
Settings → Custom views → Add custom view: a name and a URL template. The App fills these placeholders for the item that is open:
| Placeholder | Value |
|---|---|
{{language}} |
The language the editor is working in (en, no, …) |
{{itemId}} |
The item id: stable across languages and renames. Prefer it |
{{itemPath}} |
The Crystallize path: no language prefix, translated per language |
{{itemExternalReference}} |
The external reference, if you route by it |
{{variantSku}} |
The selected variant’s SKU, if the product page selects variants by URL |
https://shop.example.com/api/preview?secret=…&language={{language}}&itemId={{itemId}}&path={{itemPath}}- Always turn on “Show responsive device toolbar in preview”. The editor then switches between mobile and desktop widths in the App’s toolbar.
- The storefront adds no preview chrome. No device buttons, no frame, no banner: it only has to be responsive, which it already is. The App draws the toolbar and the reload button.
- The secret ends up in the tenant’s settings, readable by anyone who can open them. Use a value only for preview.
By API: custom views are tenant preferences. The legacy PIM API has
tenant { setPreferences(tenantId, input: { frontends: [{ name, url }] }) }; Core only reads them
(tenant { preferences { frontends { name url responsive authentication { key } } } }). The input has no
responsive, so the device toolbar is switched on in the App, and setPreferences replaces the whole list: read
frontends first and send every existing view back, knowing their responsive and authentication can’t be
carried and will be reset. Adding a view in the App is safer.
2. The preview route
One GET route: check the secret, resolve the item’s storefront URL from its draft in the requested
language, turn on preview mode, redirect. In Next.js:
import { cookies, draftMode } from "next/headers";import { redirect } from "next/navigation";import { createHash, timingSafeEqual } from "node:crypto";
const same = (a: string, b: string) => timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
export async function GET(request: Request) { const params = new URL(request.url).searchParams; const secret = params.get("secret"); if (!process.env.PREVIEW_SECRET || !secret || !same(secret, process.env.PREVIEW_SECRET)) return new Response("Invalid preview secret", { status: 401 });
// Redirect only to a path Discovery returned, never to a parameter (no open redirect). const target = await previewTarget(params.get("language"), params.get("itemId"), params.get("path")); if (!target) return new Response("No storefront page for this item in this language", { status: 404 });
(await draftMode()).enable(); // Partitioned (CHIPS): kept by browsers that block third-party cookies, and scoped to the App's site. if (process.env.NODE_ENV !== "development") { const jar = await cookies(); const value = jar.get("__prerender_bypass")?.value; if (value) jar.set({ name: "__prerender_bypass", value, httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/", }); } redirect(target);}Resolve by item id, per language. The Crystallize path has no language prefix and is translated, so the
storefront URL is /{lang} plus the path in that language, and the item may map to a special route (the home
landing page to /{lang}):
async function previewTarget(language: string | null, itemId: string | null, path: string | null) { const lang = isLang(language) ? language : "en"; const id = itemId ?? (path ? await itemIdForPath(path, lang) : null); // a path alone: try every language if (!id) return null; const data = await discovery<{ search: { hits: { path: string; externalReference?: string }[] } }>( `query PreviewTarget($id: String!) { search(language: ${lang}, filters: { itemId: { equals: $id } }, pagination: { limit: 1 }) { hits { path externalReference } } }`, { id }, { draft: true }, ); const hit = data.search.hits[0]; if (!hit) return null; return hit.externalReference === "page:home" ? `/${lang}` : `/${lang}${hit.path}`;}Resolve from the draft: a renamed or not-yet-published item has its new path only there. Look a bare path up in
every language: {{itemPath}} may be in another language than {{language}}.
Add an exit route (/api/preview/exit, POST for forms; with a GET link, prefetch={false}) that calls
draftMode().disable() and also deletes the partitioned cookie with Partitioned; a partitioned cookie is only
deleted by a Set-Cookie that carries the attribute. Next keeps one Set-Cookie per name, so set the partitioned
deletion only where the partitioned cookie was set (production).
Other frameworks: the same route sets your own signed, httpOnly preview cookie with the attributes in section 5,
and your loaders branch on it.
3. Draft reads through Discovery
In preview mode, every Discovery read asks for drafts: add publicationState: draft next to language. Every
Discovery field that takes language also takes it: search, autocomplete, every browse field, and the
nested relation fields items(language:) and variants(language:). One rewrite covers a whole query:
export const draftQuery = (query: string) => query.replace(/\((\s*language:\s*[^,)\s]+)(?![^)]*publicationState)/g, "($1, publicationState: draft");With Next.js Cache Components, put the switch inside the cached client. draftMode().isEnabled is readable
in 'use cache' (and 'use cache: remote'); it is false while prerendering and for every request without the
cookie, so normal traffic stays cached and prerendered. With the cookie, Next re-runs every cached function on
each request and saves nothing:
async function cached<T>(query: string, variables: Record<string, unknown>): Promise<T> { "use cache: remote"; if ((await draftMode()).isEnabled) return request<T>(draftQuery(query), variables); // not saved cacheLife("hours"); cacheTag("discovery"); return request<T>(query, variables);}Then the storefront’s own pages are the preview: same routes, same views, no /preview copy to keep in step.
Drafts are public on an open Discovery. publicationState: draft needs no credentials there (verified on two
tenants). The secret protects the preview mode: uncached rendering, noindex, framing by the App. It does
not protect the data. To keep drafts private, restrict Discovery, re-ignite
(igniteDiscoApi; the setting reaches Discovery only after that, and a few minutes later), and send the static
token from the server.
4. Live reload
The custom-views doc asks preview pages to load the App’s listener. Load it in preview mode only:
async function PreviewListener() { const { isEnabled } = await draftMode(); return isEnabled ? <script defer src="https://app.crystallize.com/static/frontend-preview-listener.js" /> : null;}It posts { frontendPreview: { loaded: true } } to the parent and reloads the page on
{ crystallize: { reloadDueToStaleItem: true } }, which the App sends when the editor saves.
5. No cache, noindex, framing and cookies
- No caching. Next serves draft-mode responses
Cache-Control: private, no-cache, no-storeand skips every cache layer. Elsewhere, mark preview responsesno-storeyourself and never let a CDN key them without the cookie. noindex. In the root layout’sgenerateMetadata,robots: { index: false, follow: false }whendraftMode().isEnabled(false while prerendering, so the static shell keeps its robots), plusX-Robots-Tag: noindex, nofollowon preview responses. Keep/api/inrobots.txt’sDisallow.- Framing. The App runs on one origin,
https://app.crystallize.com(pim.crystallize.comredirects there). Let it frame the preview route and preview-mode responses only; everything else keepsX-Frame-Options: SAMEORIGINandframe-ancestors 'self':
async headers() { const preview = "frame-ancestors 'self' https://app.crystallize.com"; const draftCookie = [{ type: "cookie" as const, key: "__prerender_bypass" }]; return [ { source: "/:path((?!api/preview(?:/|$)).*)", missing: draftCookie, headers: [ { key: "X-Frame-Options", value: "SAMEORIGIN" }, { key: "Content-Security-Policy", value: "frame-ancestors 'self'" }, ], }, { source: "/:path*", has: draftCookie, headers: [ { key: "Content-Security-Policy", value: preview }, { key: "X-Robots-Tag", value: "noindex, nofollow" }, ], }, { source: "/api/preview/:path*", headers: [ { key: "Content-Security-Policy", value: preview }, { key: "X-Robots-Tag", value: "noindex, nofollow" }, ], }, ];}Matching on the cookie’s presence is enough: a forged cookie only makes the page framable by the App, for the
browser that forged it. Add http://localhost:* only if you frame a local server.
- Cookies. The preview cookie is set and read inside a third-party iframe, so it must be
SameSite=None; Secure;LaxorStrictis never sent there, and preview silently shows published content. Next’s__prerender_bypassisSameSite=None; Securein production builds butLaxinnext dev, so test the framed preview against a production build over HTTPS. AddPartitionedfor browsers that block third-party cookies (Chrome with third-party cookies off, incognito); Safari’s tracking prevention may still refuse cookies in the frame, so tell editors which browsers you support.
Verify
/api/previewwith a wrong secret answers 401; with the right one, 307 to/{lang}/…and aSet-Cookie: __prerender_bypass=…; Secure; HttpOnly; SameSite=none; Partitioned.- A page with the cookie has
frame-ancestors 'self' https://app.crystallize.com, noX-Frame-Options,X-Robots-Tag: noindex,<meta name="robots" content="noindex, nofollow">and the listener script; without it,X-Frame-Options: SAMEORIGINandindex, follow. - Log the outgoing Discovery bodies: with the cookie every query carries
publicationState: draftand is sent on every request; a normal visit afterwards makes no Discovery request (the published cache was not touched). - In the App, open an item, pick the custom view, switch device widths, save a change and watch it reload.
Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| The view is blank or “refused to connect” | X-Frame-Options/frame-ancestors 'self' on the preview responses |
Allow https://app.crystallize.com, on preview responses only |
| Preview shows published content inside the App only | The preview cookie is SameSite=Lax (or blocked as third-party) |
SameSite=None; Secure; Partitioned; test a production build over HTTPS |
| Preview works in English, 404s in other languages | Redirected to {{itemPath}} as-is: paths are translated, no /{lang} |
Resolve {{itemId}} per language from the draft |
| A renamed or new item 404s in preview | The target was resolved from published data | Resolve with publicationState: draft |
| Shoppers saw a draft | Draft reads cached, or a cache keyed without the cookie | Switch inside the cached client on draftMode(); no-store on preview |
| Every page became dynamic | Preview checked with cookies()/headers() in a shared layout |
draftMode(): off during prerender, so the static shell is unchanged |
| Preview pages indexed | No noindex in preview mode |
robots from draftMode(), X-Robots-Tag on preview responses |
| “Exit preview” link ends preview before it is clicked | A prefetched <Link> to a GET exit route |
POST, or prefetch={false} |
| The view doesn’t follow the editor’s saves | The App’s listener isn’t loaded | frontend-preview-listener.js in preview mode |
| Device buttons inside the preview | Preview chrome built into the storefront | Remove it; turn on the App’s responsive device toolbar |
| Treating the secret as access control for drafts | Drafts are public on an open Discovery | Restrict Discovery, re-ignite, use the static token if drafts must stay private |
Security headers
A live Crystallize storefront audited against Modern Web Guidance v1.0 sent only strict-transport-security. No
Content Security Policy, no nosniff, no Referrer-Policy, no framing protection. This matters more once a store
has agent tools: WebMCP tools act with the shopper’s session, so an XSS becomes an agent acting as the shopper.
Companion headers: always
Cheap, and they break nothing on a typical storefront. From a working next.config.ts:
const nextConfig: NextConfig = { async headers() { return [ { source: "/:path*", headers: [ { key: "X-Content-Type-Options", value: "nosniff" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()", }, { key: "X-Frame-Options", value: "SAMEORIGIN" }, { key: "Content-Security-Policy", value: "frame-ancestors 'self'" }, ], }, // The one exception is editor preview in a Crystallize custom view: see "Routes embedded in // Crystallize" below and preview.md. // Not on the OAuth pages: an MCP client may open the consent page in a popup and read the result // through window.opener after the redirect back, which COOP: same-origin would cut. { source: "/:path((?!oauth(?:/|$)|(?:en|no|sv|nl)/oauth(?:/|$)).*)", headers: [{ key: "Cross-Origin-Opener-Policy", value: "same-origin" }], }, ]; },};Permissions-Policy: payment=()blocks the Payment Request API. Leavepaymentout if a provider’s button uses it in your page.- If a payment provider opens a popup and reads
window.opener, exclude its return route from COOP the same way as the OAuth pages, or usesame-origin-allow-popups. Strict-Transport-Securityusually comes from the host; check it is there.
Routes embedded in Crystallize
Deny framing everywhere except where the Crystallize App frames you, and allow only the App there. The App runs on
https://app.crystallize.com (pim.crystallize.com redirects to it); a *.crystallize.com wildcard is broader
than needed.
Draft preview in a custom view. The App frames the preview route, then the storefront pages it redirects to,
in preview mode. Relax framing for the preview route and for requests carrying the preview cookie, and keep
X-Frame-Options and frame-ancestors 'self' for everyone else (Next.js, where the cookie is
__prerender_bypass):
async headers() { const preview = "frame-ancestors 'self' https://app.crystallize.com"; const draftCookie = [{ type: "cookie" as const, key: "__prerender_bypass" }]; return [ { source: "/:path((?!api/preview(?:/|$)).*)", missing: draftCookie, headers: [ { key: "X-Frame-Options", value: "SAMEORIGIN" }, { key: "Content-Security-Policy", value: "frame-ancestors 'self'" }, ], }, { source: "/:path*", has: draftCookie, headers: [{ key: "Content-Security-Policy", value: preview }, { key: "X-Robots-Tag", value: "noindex, nofollow" }] }, { source: "/api/preview/:path*", headers: [{ key: "Content-Security-Policy", value: preview }, { key: "X-Robots-Tag", value: "noindex, nofollow" }] }, ];}The preview cookie is set and read inside a third-party iframe, so it must be SameSite=None; Secure (and
Partitioned); a Lax cookie is never sent in the frame. Full setup: preview.md.
A custom view or a legacy App with its own routes (from two builds with embedded views) gets the same
frame-ancestors, on those routes only:
async headers() { const csp = { key: "Content-Security-Policy", value: "frame-ancestors 'self' https://app.crystallize.com" }; return [ { source: "/app", headers: [csp] }, { source: "/app/:path*", headers: [csp] }, ];}Keep these routes out of the site-wide frame-ancestors 'self' and X-Frame-Options rule, or the stricter one
wins. Add http://localhost:* in development if you embed a local server.
Content Security Policy
None of the builds enforces a script CSP yet. The audit’s recommendation:
- Start with
Content-Security-Policy-Report-Onlyand move to enforcing once the reports are clean. script-srcwith a nonce or hashes and'strict-dynamic';object-src 'none';base-uri 'none';require-trusted-types-for 'script'.img-srcnames the Crystallize media host (or your custom media domain). Discovery and the Shop API are called from the server, soconnect-srcdoes not need them.- A per-request nonce conflicts with a static PPR shell. A nonce forces dynamic rendering, and hashes don’t
fit streamed inline scripts. With Cache Components, either accept dynamic HTML, or ship the parts of CSP that
need no nonce (
object-src,base-uri,frame-ancestors,img-src) and decide the script policy explicitly. - JSON-LD in
<script type="application/ld+json">is data, but escape<so content can’t close the tag:
export function JsonLd({ data }: { data: unknown }) { return ( <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</g, "\\u003c") }} /> );}The MCP App’s CSP
An MCP App resource declares its own CSP to the host. List the store’s origin (for the client bundle) and the media host, and nothing else:
_meta: { ui: { csp: { resourceDomains: [site, "https://media.crystallize.com"] }, prefersBorder: false } }The MCP endpoint itself answers CORS (Access-Control-Allow-Origin: *, and exposes WWW-Authenticate and
Mcp-Session-Id), because hosts call it from their own origins. See [[agentic-commerce]].
Cookies
First-party session and cart cookies are httpOnly, SameSite=Lax, Path=/, and should be Secure with the
__Host- prefix (which requires Secure, Path=/ and no Domain). The audited stores had the first three and
lacked Secure and the prefix. The exception is the preview cookie, which the Crystallize App’s iframe needs as
SameSite=None; Secure; Partitioned (see above).
jar.set("__Host-cart", cart.id, { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 60 * 60 * 24 * 30,});The cookie holds the cart id only. Tokens never reach the browser.
Secrets
- Crystallize token pairs, the Shop JWT, webhook secrets and OAuth signing secrets live in server environment
variables, never in
NEXT_PUBLIC_*. - On Vercel, mark them sensitive.
- The revalidation webhook checks its secret from a header.
Staging and demo deployments
Several builds send X-Robots-Tag: noindex, nofollow site-wide unless an ALLOW_INDEXING variable is set, so
previews and staging never get indexed:
async headers() { if (process.env.ALLOW_INDEXING === "true") return []; return [{ source: "/:path*", headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow" }] }];}
Crystallize AI