# The catalog in the admin Design Types, edit products at scale, manage media, run bulk updates and publish per language in the OrbCommerce Admin. OrbCatalog's screens live under **Products** (grid, Categories, Registers, Media, [Import](/docs/admin/import), Types and Overview), **Settings**, and **Connections → Products** in the OrbCommerce Admin. The active shop and language are chosen from the switcher under your merchant name. ## Design a Type Open _Products → Types_, choose a Type (such as _Coffee_) and select **Add attribute**. Pick a field type (text, rich text, number, choice, choices, yes/no, date, image, link to a product or category, or money), name it, and mark its flags: translated, required, filterable, shown in list, searchable, or a variant axis. Reuse shared attributes across Types (for example _Roast_ or _Brand_) so filters work across your entire catalog. Before **Publish types** applies changes, the admin previews the exact impact: - Removed attributes disappear from live products within ten minutes while staying in drafts under _Retired_. - Newly required attributes leave existing live products online until republished, and **Republish everything that passes** updates eligible products in one click. ## Unit prices For goods sold by weight, volume, length or area, configure _Types → `` → Details → Unit price_ (e.g. `1 kg`, `1 l`, `1 m`, `1 m²`, `100 g` or `100 ml`). Every variant then requires a matching **Net content** (such as `250 g` or `0.75 l`) before it can publish. Unit prices are calculated automatically from the active price and net content whenever an Offer is read, so scheduled sales update the unit price automatically. A `250 g` bag of coffee at €12.90 displays €51.60 / 1 kg. ## Find and edit products The product grid uses keyset pagination built for catalogs up to 2,000,000 products. Filter as you type by Type, category, status, completeness, any filterable attribute, or full-text search across names, refs and SKUs. - **Inline editing:** Click any cell, type and press `Tab` to save in the background. Concurrent edits to different fields merge cleanly; conflicting edits on the same field show both values inline. - **Category filtering:** Use _Products → Filters → Category_ (or _Categories → Show in Products_) to filter by a specific category. Category filters do not include child categories automatically and appear as removable chips. - **Source-owned fields:** Fields managed by a PIM or ERP appear locked with the Source's name. Press `?` anywhere to view keyboard shortcuts. ## Bulk edits Filter the grid to the products you want, then choose **Set**, **Add**, **Remove** or **Adjust by percent** for attributes, categories or prices (base prices or scheduled sales). Every bulk action shows a count and preview first and applies exactly what was previewed in the background. **Undo** reverts all values and prices that nobody edited in the meantime, leaving ERP-owned prices untouched. ## Manage product lifecycle ### Hand a Source product to editors Open an imported product and select **Ownership → Hand over**. Once confirmed, Sources no longer overwrite that product document (prices and stock keep their own owners). The product retains its ref, SKUs, live version, draft and history, and nothing is published until you choose to. ### Change a product's Type Open the product and choose **⋯ → Change Type**. Pick the new Type and map variant options for any variant axes. Before creating the new draft, the admin previews: - Fields that will be dropped on publish (kept beside the draft until then) - Tax class or appointment settings copied onto variants so prices and bookings stay intact - Any storefront URL changes caused by the new Type - Missing required fields per live language Changing a Type saves a draft without publishing. Live shoppers, search and webhooks keep the previous version until you publish. ### Withdraw a product Choose **⋯ → Withdraw** on an editor-owned product to remove it immediately from storefronts, search and OrbCart and free its SKUs. Its version history stays intact. Choose **⋯ → Bring back** to restore it, provided no other product has claimed its SKUs. ## Appointment settings Configure default capabilities, duration, buffers, lead time and resource selection under _Types → Appointments_. On a product's **Appointments** tab, each variant uses the Type default unless you turn off **Use Type default** and define a complete override. - **Per appointment:** Duration applies once per booking regardless of quantity. - **Per unit:** Duration multiplies by the appointment line quantity. ## Media library _Products → Media_ stores images for the entire family, including OrbPage. Organize assets in folders up to two levels deep, or browse product images automatically collected from products and Sources. - **Deduplicated uploads:** Uploading an identical file reuses the existing asset. - **Metadata and focal point:** Click any asset to inspect where it is used (products, categories and OrbPage content), edit localized alt text and set the focal point used by all crops. - **Replace in place:** **Replace** keeps the asset ID and aspect ratio, updating every page once caches purge. - **Safe deletion:** Assets currently in use cannot be deleted. Deleted assets leave pickers immediately (with **Undo**) and are retained for 30 days before permanent removal. ## Publish and schedule Each product displays completeness per language (translations, images and required attributes). - **Publish:** Releases all complete languages. You can also publish a single language (e.g. _Publish English_) while keeping other draft edits unpublished. - **Schedule:** Freezes the current draft to go live at an exact minute across product pages, categories and URLs. Publishing immediately replaces any pending scheduled version. - **History:** Lists every version with author and timestamp, with one-click **Restore**. ## Next steps | You want to | Read | | ------------------------------- | ------------------------------------------ | | Import products from a file | [Import a file](/docs/admin/import) | | Sync products from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Ask AI Chat to edit drafts | [AI Chat](/docs/admin/chat) | | Read published products in code | [Read the catalog](/docs/catalog/storefront) | # AI Chat Enable AI Chat with your Vercel AI Gateway key, control spending, review proposed edits, and opt in to order and checkout diagnostics. Press ⌘J (`Ctrl+J` on Windows/Linux) or click the sparkle icon at the bottom of the sidebar to open AI Chat beside any screen. When viewing a product, Chat already knows which product is open so you can ask directly: _"Shorten this description to 300 characters in the tone of the other coffees."_ Conversations persist across reloads and browser tabs. Drag the inner edge to resize the drawer (320 px to half the window); on mobile it opens as a sheet. Use **Stop** to interrupt a response or the pencil icon to start a fresh conversation. ## Turn it on AI Chat is off by default and sends nothing until the owner enables it under _Settings → AI Chat_. It connects exclusively through your own [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) account. | Setting | What it configures | | ---------------- | ------------------------------------------------------------------------------------------ | | API key | Your Vercel AI Gateway key. Verified live, stored sealed, and never shown again. | | Model | Any tool-capable language model from your gateway, grouped by provider with token pricing. | | Content | Explicit opt-in to send product and page content. Nothing leaves without this enabled. | | Cart diagnostics | Separate opt-in to send operational Order and Checkout data, off by default. | | Limits | Monthly shop cap and daily per-person cap in USD (UTC), with live spend readouts. | Only the owner can edit these settings. If your chosen model is scheduled for retirement by the gateway, a notice appears in Settings and the drawer; once retired, AI Chat pauses until the owner selects a replacement. ## What AI Chat can do AI Chat acts strictly with your own staff permissions using short-lived 5-minute tokens kept in server memory: - **OrbCatalog ([MCP endpoint](/docs/catalog/agents)):** Searches, creates, duplicates and edits product drafts (including variants, categories and existing media). Cannot edit Source-owned fields, change prices or stock, or delete products. - **OrbPage:** Lists pages and templates, reads draft and live content plus declared sections, and proposes new pages or targeted edits without overwriting untouched sections. Cannot inject raw HTML/CSS or publish pages. - **OrbCart ([MCP endpoint](/docs/cart/agents#diagnose-orders-and-checkouts-over-mcp)):** Finds Orders and Checkouts that need attention and reads their current status. Requires **Orders view**, respects Location access, and never searches by customer or moves money. ### Every write requires human approval AI Chat never saves or publishes changes silently: 1. **Inline or dialog review:** Short Catalog and Page edits display a before/after diff with **Approve** and **Reject** right in chat. Larger changes open a full **Review** dialog without leaving your current screen. 2. **Exact-revision safety:** Approval saves only that exact change against that exact revision. If someone edited the draft in the meantime, approval is blocked and only **Reject** is offered. 3. **Separate publish approval:** Publishing is always a separate proposal showing which languages will go live. 4. **Personal and time-limited:** Only the person who requested the edit can approve it, and pending approvals expire after 15 minutes. Retrying after a dropped connection never saves twice. ## Spending limits Vercel AI Gateway bills in USD, so limits are tracked in USD. While a turn runs, the admin reserves an estimated hold (16,000 tokens at the model's higher rate) and settles to actual input, cached input and output usage when the turn finishes. When a user's daily limit or the shop's monthly limit is reached, new messages are blocked with a clear message explaining which limit was hit. ## Privacy and data retention - **External processing:** Messages and read content go to Vercel AI Gateway and the selected model provider under your Vercel account. Cart diagnostics, when enabled, include Order and Cart identifiers and operational facts, not buyer details. Do not paste buyer data or checkout links into Chat. Confirm provider region, logging and retention settings before enabling access. - **Cart context:** Cart answers stay in your private conversation, even if the owner later switches Cart diagnostics off. Chat never sends them again as context for new turns. Ask for a fresh read when you follow up on an Order or Checkout. - **No content in admin logs:** Failed turns log only the request ID and error type, never prompts or product data. - **30-day retention:** Each staff member has one private conversation per shop stored in Cloudflare Durable Objects. Conversations are automatically deleted 30 days after the last message (or immediately when starting a new chat). ## Next steps | You want to | Read | | --------------------------------------- | ------------------------------------------ | | Connect external MCP clients to Catalog | [Catalog agents](/docs/catalog/agents) | | Manage products in the admin | [The catalog in the admin](/docs/admin/catalog) | | Configure AI column suggestions | [Import a file](/docs/admin/import) | # Admin design system Build admin screens with @orbcommerce/ui, migrate from earlier components, and verify accessibility with startAudit. Every screen in the OrbCommerce Admin is built with `@orbcommerce/ui` and `@orbcommerce/ui/theme.css`. Using the shared components keeps custom modules consistent across light and dark mode automatically. ## A screen in `@orbcommerce/ui` Here is a settings screen with an optimistic toggle, undo toast and rollback on error: ```tsx import { Page, PageHeader, Row, Rows, Section, Switch, toast } from "@orbcommerce/ui"; import { useState } from "react"; export function FleetSettings({ save }: { readonly save: (pickup: boolean) => Promise }) { const [pickup, setPickup] = useState(true); async function change(next: boolean) { const before = pickup; setPickup(next); if (await save(next)) { toast("Pickup changed", { undo: () => void change(before) }); } else { setPickup(before); toast.error("Pickup was not saved. Try again."); } } return ( }>
void change(next)} />
); } ``` ## Core rules - **Import from `@orbcommerce/ui` only.** Load `@orbcommerce/ui/theme.css` once at the app root. - **Layout classes only.** Screens may use layout utilities (`flex`, `grid`, `gap-*`, `min-w-0`, widths, spacing) plus `font-medium`, `font-mono`, `tabular-nums` and `text-ink-muted`. Visual classes (`bg-*`, `text-sm`, `border`, `rounded-*`, `shadow-*`) belong in components and are rejected by `orbcommerce/no-visual-classes`. - **All copy in `defineWords`.** Never hardcode user-facing strings; see [Admin languages](/docs/admin/languages). - **One primary action per surface.** Only show a primary button when it can be clicked; use `IconButton` with `heldBack` when explaining why an action is temporarily unavailable. - **Undo over confirm.** Prefer immediate optimistic updates with `toast(..., { undo })`. Reserve `Confirm` for irreversible actions and name their scope (e.g. _Remove from Clay & Crema_). - **At most two rounded layers.** `Rows`, `FoldingRows` and `Card` are each a surface: do not nest them inside another `Card`. Put a `DataTable` inside `Card flush`. - **Match the control to the data.** Use `Select` or `Combobox` instead of `Segmented` for dynamic or long lists, and a multi-select `Combobox` instead of toggle chips. ## Migrating from earlier `@orbcommerce/ui` ### Screens and layout | Old | New | Note | | --------------------------- | ------------------------------------------------- | --------------------------------------- | | `ScreenHeader` with `aside` | `Page` with `PageHeader` | Status beside title, actions at the end | | `Card` with `icon` | `Card` or `Section`, no icon | Title and content align to one edge | | `columns`, `mainColumn` | `DetailLayout` | Main cards plus side column | | Sidebar list beside content | `SettingsLayout` | Collapses to a picker on mobile | | Padded `Table` screen | `ListPage` + `Tabs` + `ListToolbar` + `DataTable` | | | `Table` inside `Card` | `Card flush` around `DataTable` | First column stays visible on mobile | | "Show more" button | `DataTable` `onEndReached` | | | Eyebrow heading | `Section` or `description` | | | `Quiet` count in header | Count in `Section` or `Card` `actions` | | | `Back` | `BackButton` with `to` | Renders _Back to …_ automatically | ### Fields and controls | Old | New | Note | | ----------------------------------- | -------------------------------------- | ------------------------------------------ | | `Labelled`, `Field` with `extras` | `Field` with `hint`, `error`, `aside` | | | `Advice`, `Note` | `Field` `error`/`hint`, or `Notice` | Colour reserved for errors | | `Labelled` settings in `Card` | `Rows` + `Row` under `Section` | Row labels its control and renders `error` | | `ToggleBox` | `Row` with `Switch`, or `Segmented` | | | Large `Segmented` | `Select`, or `Combobox` for long lists | | | Toggle chips | Multiple `Combobox` | | | `Popover` + `SearchInput` | `Combobox` with `OptionGroup` | Use `note` for prices or counts | | Manual `-` / `+` stepper | `NumberField` with `stepper` | Constrained with `min` and `max` | | `DateTimeField` | `DateField` with `time` | | | `fieldBox` around textarea + button | `Textarea` with `lines` and `actions` | | | Inline validation text | `Field` `error` + `useComplaint` | | ### Actions, overlays and status | Old | New | Note | | ------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------- | | `Button` `default` / `outline` | `primary`, `secondary`, `ghost` | `tone="danger"` for destructive actions | | `Button disabled` while loading | `Button busy` | | | `IconButton` `tip` | `IconButton` `label` (+ `heldBack`) | | | Per-row trash icon | `RowMenu` + `Confirm` | | | `Confirm` `label`/`question` | `Confirm` `trigger`, `title`, `consequence`, `action` | | | `MenuChoices` / `MenuCheckItem` | `MenuRadioGroup` / `MenuCheckboxItem` | | | `toast` with description/action | `toast` with one sentence and `undo` | Supports `id`, `seconds`, `persist`, `onExpire` | | `Orb` / `Badge` old tones | `Tone`: `positive`, `neutral`, `warning`, `negative`, `accent`, `info` | | | `Note` (empty) / `Unavailable` | `Empty` / `Problem` with retry | | | Custom charts | `Meter`, `Sparkline`, `AreaChart` | One metric per chart | ## Common pitfalls - **Never use `outline-none` on focusable elements.** In Tailwind 4 it removes `focus-visible:outline-*` too. - **Never wrap links or controls in an `overflow-hidden` truncating box.** It clips focus rings; truncate the element itself. - **Keep one control per `Row`.** Multiple controls share the same accessible label; use `Field` instead. - **Do not place `Section` directly in CSS Grid cells.** Its top margin misaligns adjacent cells. - **Define `cell`, `editor` and `rowEnd` renderers at module level.** Inline JSX factories cause rows to remount on every render. ## Audit your screen Run `startAudit()` from `@orbcommerce/ui/audit` in a Vitest browser test across light/dark mode and 1440 px / 390 px viewports: ```ts skip="Vitest browser test example" const audit = startAudit(); render( true} />); expect(await audit.findings()).toEqual([]); ``` `startAudit()` walks the rendered screen with real `Tab` presses and catches missing or clipped focus rings, unexpected horizontal table overflow, dialogs/sheets that fail to restore focus on `Escape`, and console errors. ## Next steps | You want to | Read | | --------------------------- | ----------------------------------------- | | Build a custom admin module | [Your own module](/docs/admin/your-own-module) | | Add localized UI copy | [Admin languages](/docs/admin/languages) | # Import a file Import products from CSV, JSON Lines or Excel files, preview every change before writing, and undo safely. Use _Products → Import_ to bring products into OrbCatalog from spreadsheets or exports when no PIM is connected. Nothing is written until you review the preview. ## Upload and import ### Upload your file Drop a **CSV**, **JSON Lines** or **Excel (`.xlsx`)** file onto the screen, up to **50 MB** and **100,000 rows**. The catalog parses the file on the server, never in your browser. Each row represents one variant; rows sharing the same product ref are grouped into one product. CSV files support commas, semicolons or tabs, and prices accept both `12,90` and `12.90`. ### Map columns Choose the target **Type**, then review how each file column maps to a catalog field (product ref, SKU, localized name, Type attributes, categories, shop price or ignored). - **Proposed:** Common headers (`SKU`, `Name DE`, `Preis DE`, etc.) map automatically. - **Remembered:** Subsequent files with matching headers reuse your last mapping. - **AI suggestions (optional):** Add your own [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) key under _Settings → System → Import suggestions_ to get column mapping suggestions with confidence indicators. Without a key, nothing leaves the catalog. ### Preview changes Select **Preview** to scan the entire file and see exact counts of **new**, **changed**, **unchanged** and **refused** products, along with before/after diffs. Refused rows show their line number and exact cause: - Unknown option for a choice attribute (e.g. `Colour: Pick one of the options.`) - Duplicate SKU within the file or already owned by another product - Missing product ref, unknown Type, invalid price, or missing required attribute - Attempt to overwrite a field owned by a PIM Source Changing the column mapping marks the preview stale until you run **Preview** again. ### Run or undo Select **Run** to apply the exact previewed changes in the background. Products edited by someone else after the preview are skipped and counted. New products are saved as **drafts** (never published automatically) and remain fully editor-owned. Re-importing the same file a second time reports zero changes. Select **Undo** to preview and revert an import: newly created products that were not edited or published since are removed, added variants that remain unchanged are removed, and previous field values and prices are restored. ## Next steps | You want to | Read | | -------------------------------- | ------------------------------------------------ | | Edit and publish imported drafts | [The catalog in the admin](/docs/admin/catalog) | | Sync continuously from a PIM/ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Publish your first product | [Your first product](/docs/get-started/first-product) | # Admin languages Set the display language of the OrbCommerce Admin, localize custom modules with type-safe dictionaries, and add new languages. The OrbCommerce Admin runs in one language at a time across every screen, including labels, messages, dates, times and numbers. English (`en`) and German (`de`) are built in. ## Set the admin language Choose the language in `apps/admin/src/modules.ts`: ```ts skip="Admin install configuration" export const language: Language = "de"; ``` Dates, times and numbers follow this setting rather than the browser locale. The admin refuses to start if any installed module is missing a sidebar label for the configured language. ## Localize your own module Each package keeps its copy in a `words/` folder (`en.ts`, `de.ts`, `index.ts`) so an install ships only the words of its installed products. Define English first, then type every other language against `typeof en` so missing keys fail at compile time: ```ts browser import { defineWords } from "@orbcommerce/ui"; const en = { jobs: { newJob: "New fleet job", jobCount: (count: number) => (count === 1 ? "1 job" : `${count} jobs`), }, }; const de: typeof en = { jobs: { newJob: "Neuer Fuhrparkauftrag", jobCount: (count: number) => (count === 1 ? "1 Auftrag" : `${count} Aufträge`), }, }; export const { useWords: useFleetWords, wordsIn: fleetWordsIn } = defineWords({ en, de }); ``` - **Inside React components:** Read strings with `useFleetWords().jobs`. - **Outside React (e.g. sidebar labels):** Read strings with `fleetWordsIn(language).jobs`. - **Dates and numbers:** Format values with `useFormats()` from `@orbcommerce/ui`, and collect dates or times with `DateField` (with `time` when needed). For German copy, use the polite form (_Sie_), short action verbs, and consistent domain terms across products (_Bestellung_, _Termin_, _Standort_, _Produkt_, _Kategorie_, _Gutschein_, _Rabatt_, _Mitarbeitende_). ## Add a new language 1. Add the language code to `languages` in `packages/ui/src/language.tsx` (`export const languages = ["en", "de", "fr"] as const`). 2. Run typecheck: TypeScript lists every package missing the new language. 3. Copy `en.ts` to the new locale file in each package, translate the strings, and register it in `defineWords({ en, de, fr })`. 4. Update `language` in `apps/admin/src/modules.ts`. ## Next steps | You want to | Read | | ------------------------------- | ----------------------------------------- | | Build a custom admin module | [Your own module](/docs/admin/your-own-module) | | Follow the admin UI conventions | [Design system](/docs/admin/design-system) | # Bring your own screens into the admin Add custom areas, Order page slots, staff-authenticated APIs and external OAuth 2.1 apps to the OrbCommerce Admin. You can extend the OrbCommerce Admin with your own modules without modifying OrbCart's or OrbCatalog's screens. For example, a **Fleet** module can add its own sidebar area, render a card on every Order page and place a **New fleet job** button in the Order list header, all hidden from staff who lack permission. An admin module runs with the signed-in staff member's permissions and forwards their staff token to your API. Only install code you own and would deploy yourself. ## 1. Define routes and your module Create an area with `ownArea("fleet")`. Its ID becomes both its URL prefix (`/fleet`) and its permission name in the staff token. Group sub-routes under a pathless place route so the shell recognizes them as part of the same navigation item: ```ts title="src/fleet-routes.ts" import { ownArea } from "@orbcommerce/shell"; import { createRoute, lazyRouteComponent } from "@tanstack/react-router"; const fleetArea = ownArea("fleet"); const jobsPath = createRoute({ getParentRoute: () => fleetArea, path: "jobs" }); const jobsPlace = createRoute({ getParentRoute: () => jobsPath, id: "fleet-jobs" }); export const jobListRoute = createRoute({ getParentRoute: () => jobsPlace, path: "/", component: lazyRouteComponent(() => import("./job-list"), "JobList"), }); export const newJobRoute = createRoute({ getParentRoute: () => jobsPlace, path: "new", component: lazyRouteComponent(() => import("./new-job"), "NewJob"), }); export const jobRoute = createRoute({ getParentRoute: () => jobsPlace, path: "$jobId", component: JobPage, }); function JobPage() { const { jobId } = jobRoute.useParams(); return `Job ${jobId}`; } export const jobsRoute = jobsPlace.addChildren([jobListRoute, newJobRoute, jobRoute]); export const fleetRoutes = fleetArea.addChildren([jobsPath.addChildren([jobsRoute])]); ``` Register the area, sidebar places and role levels with `defineModule()`. The owner assigns these roles under _Settings → Staff_: ```ts title="src/fleet.ts" import { defineModule } from "@orbcommerce/shell"; import { ClipboardList, Truck } from "lucide-react"; import { fleetRoutes, jobsRoute } from "./fleet-routes"; export const fleet = () => defineModule({ id: "fleet", areas: [ { route: fleetRoutes, label: () => "Fleet", icon: Truck, places: [{ label: () => "Jobs", icon: ClipboardList, route: jobsRoute }], }, ], roles: { fleet: ["view", "edit"] }, }); ``` ### Query your API from a screen Use `useApi("fleet")` to send authenticated requests to `/api/fleet` on the admin's origin, and `` to link to an Order without importing OrbCart: ```tsx title="src/job-list.tsx" import { Linked, useApi } from "@orbcommerce/shell"; import { Page, PageHeader } from "@orbcommerce/ui"; import { useSuspenseQuery } from "@tanstack/react-query"; import { fleetJobsQuery } from "./fleet-api"; export function JobList() { const jobs = useSuspenseQuery(fleetJobsQuery(useApi("fleet"))).data; return ( }>
    {jobs.map((job) => (
  • {job.vehicle} ·{" "} {job.order}
  • ))}
); } ``` Parse API responses with Zod at the boundary: ```ts title="src/fleet-api.ts" import type { ModuleApi } from "@orbcommerce/shell"; import { queryOptions } from "@tanstack/react-query"; import { z } from "zod"; const FleetJob = z.object({ id: z.string(), order: z.string(), vehicle: z.string() }); export const fleetJobsQuery = (api: ModuleApi, order?: string) => queryOptions({ queryKey: ["fleet", "jobs", order], queryFn: async () => { const query = order === undefined ? "" : `?order=${encodeURIComponent(order)}`; const answer = await api.fetch(new Request(`${api.url}/jobs${query}`)); if (!answer.ok) throw new Error(`The fleet answered ${answer.status}.`); return z.array(FleetJob).parse(await answer.json()); }, }); ``` ## 2. Verify staff tokens in your API The admin only controls UI visibility. Your API must verify every request using `staffTokens()` and `may()` from `@orbcommerce/kernel`: ```ts title="fleet-api/src/index.ts" worker import { may, staffTokens } from "@orbcommerce/kernel"; import { jobsFor, NewJob, planJob } from "./jobs"; // The admin URL whose JWKS verifies staff tokens. const tokens = staffTokens({ issuer: "https://admin.example.com", clock: Date }); export default { async fetch(request) { const verified = await tokens.verify(request); if (verified.status === "unavailable") return new Response(null, { status: 503 }); if (verified.status !== "staff") return new Response(null, { status: 401 }); const { staff } = verified; const url = new URL(request.url); if (url.pathname !== "/jobs") return new Response(null, { status: 404 }); if (request.method === "GET") { if (!may(staff, "fleet", "view")) return new Response(null, { status: 403 }); return Response.json(await jobsFor(url.searchParams.get("order"))); } if (!may(staff, "fleet", "edit")) return new Response(null, { status: 403 }); const job = NewJob.safeParse(await request.json()); if (!job.success) return new Response(null, { status: 400 }); return Response.json(await planJob(job.data, staff.id), { status: 201 }); }, } satisfies ExportedHandler; ``` - **Store `staff.id`**, not `staff.name`, since display names can change. - **Location scoping:** If records belong to Locations, check `mayAt(staff, job.location)` (or `holdsEveryLocation(staff)` for global records) in your query and return `404` for records outside the person's assigned Locations. ## 3. Extend Order screens with slots OrbCart exposes three slots: `order.head`, `order.side` and `orders.head`. Slot components receive `at` (the Order number) and `record` (the already-loaded Order): ```tsx title="src/job-card.tsx" import { useApi } from "@orbcommerce/shell"; import type { SlotProps } from "@orbcommerce/shell"; import { Card, Row, Rows } from "@orbcommerce/ui"; import { useSuspenseQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { fleetJobsQuery } from "./fleet-api"; import { jobsRoute } from "./fleet-routes"; export function FleetJobCard({ at }: SlotProps) { const jobs = useSuspenseQuery(fleetJobsQuery(useApi("fleet"), at)).data; if (jobs.length === 0) return null; return ( {jobs.map((job) => ( {job.id} ))} ); } ``` Add an action button to the Order list header: ```tsx title="src/new-job-button.tsx" import { Button } from "@orbcommerce/ui"; import { Link } from "@tanstack/react-router"; import { Plus } from "lucide-react"; import { newJobRoute } from "./fleet-routes"; export function NewFleetJobButton() { return ( ); } ``` Attach both slots lazily in `defineModule()` so the Order page never waits on your bundle: ```ts title="src/fleet.ts" import { defineModule, lazySlotComponent } from "@orbcommerce/shell"; import { ClipboardList, Truck } from "lucide-react"; import { fleetRoutes, jobsRoute } from "./fleet-routes"; export const fleet = () => defineModule({ id: "fleet", areas: [ { route: fleetRoutes, label: () => "Fleet", icon: Truck, places: [{ label: () => "Jobs", icon: ClipboardList, route: jobsRoute }], }, ], slots: { "order.side": { Component: lazySlotComponent(() => import("./job-card"), "FleetJobCard") }, "orders.head": { Component: lazySlotComponent(() => import("./new-job-button"), "NewFleetJobButton"), }, }, roles: { fleet: ["view", "edit"] }, }); ``` Slots are isolated: if a slot throws, only that card shows a **Retry** fallback while the Order page keeps working. To mutate an Order itself (such as marking units shipped), define an [Order action](/docs/cart/order-actions) instead of mutating from a slot. ## 4. Install the module in the admin Add your module to `apps/admin/src/modules.ts`: ```ts title="apps/admin/src/modules.ts" import { fleet } from "./fleet"; export const modules = [/* catalog(), cart(), page(), search(), mail(), */ fleet()] as const; ``` Then register its proxy target in `apps/admin/src/forward/forward.server.ts` (`fleet: { name: "Fleet", by: "url", address: "FLEET_URL" }`) and set `FLEET_URL` in the admin's `wrangler.jsonc`. The proxy forwards the staff token and strips admin cookies. ## 5. Connect an external non-React app (OAuth 2.1) To link an existing tool written in any language from the sidebar with single sign-on (no iframe, no second password), register it as a merchant app using OAuth 2.1 Authorization Code + PKCE (`apps/example-merchant-app` shows the full flow): ```ts title="apps/admin/src/apps.server.ts" export const merchantApps = [ { id: "fleet", name: "Fleet", url: "https://fleet.example.com", redirectUris: ["https://fleet.example.com/callback"], }, ]; ``` ```ts title="src/fleet.ts" import { defineModule } from "@orbcommerce/shell"; import { Truck } from "lucide-react"; export const fleet = () => defineModule({ id: "fleet", apps: { orders: [{ label: () => "Fleet", icon: Truck, url: "https://fleet.example.com" }], }, roles: {}, }); ``` Verify the delegated 5-minute access token in your app using `delegatedTokens()` from `@orbcommerce/kernel`: ```ts title="app/index.ts" worker import { delegatedTokens, may } from "@orbcommerce/kernel"; const tokens = delegatedTokens({ issuer: "https://admin.example.com", resource: "https://fleet.example.com", clock: Date, }); export default { async fetch(request) { const verified = await tokens.verify(request); if (verified.status === "unavailable") return new Response(null, { status: 503 }); if (verified.status !== "delegated") return new Response(null, { status: 401 }); if (!verified.scopes.has("staff:profile")) return new Response(null, { status: 403 }); if (!may(verified.staff, "orders", "view")) return new Response(null, { status: 403 }); return Response.json({ name: verified.staff.name, roles: verified.staff.roles }); }, } satisfies ExportedHandler; ``` Check `iss` and `state` on your OAuth callback (RFC 9207) and store tokens in `HttpOnly` cookies. Access tokens expire after 5 minutes, so removing a staff member revokes access quickly and invalidates their next refresh. ### Delegated access for MCP clients External MCP clients using Client ID Metadata Documents discover authorization metadata automatically at `/.well-known/oauth-protected-resource/mcp` and `/.well-known/oauth-authorization-server`, then ask the staff member to approve scoped access on the admin's consent screen. Product scopes and MCP resources are registered in `packages/auth/src/delegation.ts`. ## Next steps | You want to | Read | | ------------------------------- | ------------------------------------------ | | Follow the admin UI conventions | [Design system](/docs/admin/design-system) | | Localize your module's copy | [Admin languages](/docs/admin/languages) | | Run custom actions on an Order | [Order actions](/docs/cart/order-actions) | | Extend Catalog product screens | [The catalog in the admin](/docs/admin/catalog) | # Add to cart and a mini cart Build a React add-to-cart button and header mini cart with an HttpOnly Cart token cookie. This recipe builds an **Add to bag** button for `DAYBREAK-250G-BEANS` (€12.90) and a header mini cart that shows live Lines and totals, survives reloads and resets after a purchase. **Prerequisites:** a React Router storefront and OrbCart running locally ([Quickstart](/docs/get-started/orbcart)). Copy `ORBCART_URL` and `ORBCART_PUBLISHABLE_KEY` into `.env` as `VITE_ORBCART_URL` and `VITE_ORBCART_PUBLISHABLE_KEY`. ## 1. Create the client and cookie route ```ts title="app/commerce.ts" import { createCommerce } from "@orbcart/client"; export const commerce = createCommerce({ url: import.meta.env.VITE_ORBCART_URL, key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY, }); ``` Add `app/cart-cookie.server.ts` and the `/cart-token` route from [Keep the Cart across reloads](/docs/cart/carts#store-the-token-in-a-cookie) so the Cart token stays in an `HttpOnly` cookie. ## 2. Wrap the app in `CartProvider` ```tsx title="app/root.tsx" import type { CommerceCart } from "@orbcart/client"; import { CartProvider, OrbCartProvider } from "@orbcart/react"; import "@orbcart/react/styles.css"; import { Outlet, useLoaderData } from "react-router"; import type { LoaderFunctionArgs } from "react-router"; import { cartCookie } from "./cart-cookie.server"; import { commerce } from "./commerce"; import { MiniCart } from "./mini-cart"; export async function loader({ request }: LoaderFunctionArgs) { const token: unknown = await cartCookie.parse(request.headers.get("Cookie")); return { cartToken: typeof token === "string" ? token : undefined }; } export default function App() { const { cartToken } = useLoaderData(); return (
Clay & Crema
); } function rememberCart(cart: CommerceCart) { void fetch("/cart-token", { method: "POST", body: new URLSearchParams({ token: cart.token }) }); } ``` ## 3. Add the button and mini cart ```tsx title="app/add-to-bag.tsx" import { CommerceError, describe } from "@orbcart/client"; import { useShoppingCart } from "@orbcart/react"; import { useState } from "react"; const words = describe("en-GB"); export function AddToBag({ reference }: { reference: string }) { const { add } = useShoppingCart(); const [adding, setAdding] = useState(false); const [problem, setProblem] = useState(); async function addToBag() { setAdding(true); setProblem(undefined); try { await add(reference); } catch (error) { if (!(error instanceof CommerceError)) throw error; setProblem(words.problem(error.problem.code)); } finally { setAdding(false); } } return ( <> {problem &&

{problem}

} ); } ``` Render `` on your product page, and mount `` in the header: ```tsx title="app/mini-cart.tsx" import { isSubmitted, unitsIn } from "@orbcart/client"; import type { CommerceCart } from "@orbcart/client"; import { Cart, Totals, useCart, useShoppingCart } from "@orbcart/react"; export function MiniCart() { const { cart } = useShoppingCart(); return cart ? : Bag (0); } function Bag({ cart }: { cart: CommerceCart }) { const bag = useCart({ cart }); if (!bag.cart) return Bag; if (isSubmitted(bag.cart)) return Bag (0); const { estimate } = bag.cart; return (
Bag ({unitsIn(bag.cart)}) Check out
); } ``` ## Result - Clicking **Add to bag** updates the header to **Bag (1)** showing Daybreak at €12.90 with a quantity stepper and estimate. - Exceeding stock displays the limit inline under the Line; reloading or opening another tab shows the same bag; after checkout, the bag resets to **Bag (0)**. ## Next steps | You want to | Read | | ------------------------------------ | ----------------------------------------------------------------- | | Build the `/checkout` page in React | [React checkout](/docs/cart/react-checkout) | | Add a discount code input to the bag | [Free shipping and a welcome code](/docs/cart/free-shipping-and-codes) | | Manage Carts without React | [Carts](/docs/cart/carts) | # AI agents Let shopping agents check out over UCP, hand off to your storefront or complete via AP2 mandates, and receive signed order updates. AI shopping agents check out through the same Carts, Quotes, Offers and Orders as your storefront using the [Universal Commerce Protocol](https://ucp.dev) (UCP). Add one `agents` block to a Channel and OrbCart serves the protocol. ## Enable UCP on a Channel At most one Channel per environment can serve agents, and `orderPage` is required so UCP can link every Order: ```ts title="src/worker.ts" members="Channels" de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", payments: { card: "adyen", google_pay: "adyen" }, orderPage: "https://clayandcrema.de/orders", agents: { continueUrl: "https://clayandcrema.de/checkout/continue", }, }, ``` Verify your UCP profile locally against port `8797`: ```sh curl -s http://localhost:8797/.well-known/ucp | jq '.ucp.capabilities | keys' ``` ```json [ "dev.ucp.shopping.checkout", "dev.ucp.shopping.discount", "dev.ucp.shopping.fulfillment", "dev.ucp.shopping.order" ] ``` ## How an agent purchase flows ### The agent builds the checkout A signed agent platform (`UCP-Agent` header + RFC 9421 HTTP message signature verified against its profile keys) creates a checkout session and adds Lines, address and shipping. Unsigned requests are refused. ### The buyer approves With the default `consent: "storefront"`, the agent sends the buyer to your `continueUrl` with a short-lived `handoff` code so the buyer reviews the Quote and pays on your own checkout. ### Order creation and updates The resulting Order runs your normal `deliverOrder` hand-off (`order.created` marks `journey.origin: "agent"`). If the platform declared an order `webhook_url`, OrbCart pushes signed RFC 9421 updates (retried up to 72 hours, no personal address data) whenever the Order is created, fulfilled or refunded. ## Build the continue page Redeem the `handoff` query parameter with `commerce.continueCheckout(handoff)`, store the Cart token in your [cart cookie](/docs/cart/carts#store-the-token-in-a-cookie) with `Referrer-Policy: no-referrer`, and redirect to `/checkout`: ```ts title="app/routes/checkout.continue.ts" browser import { CommerceError } from "@orbcart/client"; import { redirect } from "react-router"; import type { LoaderFunctionArgs } from "react-router"; import { cartCookie } from "../cart-cookie.server"; import { commerce } from "../commerce"; export async function loader({ request }: LoaderFunctionArgs) { const handoff = new URL(request.url).searchParams.get("handoff"); if (!handoff) return redirect("/"); try { const cart = await commerce.continueCheckout(handoff); return redirect("/checkout", { headers: { "Set-Cookie": await cartCookie.serialize(cart.token), "Referrer-Policy": "no-referrer", }, }); } catch (error) { if (error instanceof CommerceError) return redirect("/"); throw error; } } ``` ## Let buyers agree inside the agent Set `consent: "mandate"` with Google Pay on Adyen to allow in-agent approval via an **AP2 checkout mandate** (closed mandates signed within 5 minutes): ```ts members="ChannelConfig" agents: { continueUrl: "https://clayandcrema.de/checkout/continue", consent: "mandate", googlePay: { merchantId: "BCR2DN4T...", merchantName: "Clay & Crema" }, }, ``` Whether an in-agent order button meets statutory requirements (such as § 312j BGB in Germany) is your legal decision. The default `consent: "storefront"` keeps final consent on your own page. ## UCP endpoints | Method | Path | Purpose | | ------------- | -------------------------------------- | ----------------------------------------------------------------- | | `GET` | `/.well-known/ucp` | Shop UCP profile and capabilities | | `POST` | `/ucp/checkout-sessions` | Create a checkout session | | `GET` / `PUT` | `/ucp/checkout-sessions/{id}` | Read or update Lines, address, shipping and codes | | `POST` | `/ucp/checkout-sessions/{id}/complete` | Complete with an AP2 mandate | | `POST` | `/ucp/checkout-sessions/{id}/cancel` | Cancel before payment (`409 checkout_not_cancelable` once paying) | | `GET` | `/ucp/orders/{id}` | Read an Order created by the calling platform | Agents cannot set custom [extensions](/docs/cart/extensions); if a required Cart extension is missing, the agent hands the session to your `continueUrl`. ## Diagnose Orders and Checkouts over MCP Staff agents use a separate, read-only endpoint at `/mcp`. A Worker needs `PUBLIC_URL` and `STAFF_ISSUER`; the admin's `CART_URL` must match `PUBLIC_URL`. Connect a client using OAuth with the exact endpoint as its resource and `cart:orders.read` as its scope. The endpoint accepts MCP `2026-07-28` and also requires **Orders view**. | Tool | What it returns | | ---------------- | ----------------------------------------------------------------------------------------------------- | | `find_orders` | Orders by Channel, payment or fulfilment status, or whether they need attention. | | `read_order` | Current status, captured and refunded amounts, offline balance due, issues and recent payment events. | | `find_checkouts` | Carts with operational issues before an Order exists; requires access to every Location. | | `read_checkout` | The current status, missing field names and issues for a known Cart ID. | Use `read_order` with an exact Order ID or number even if the Order has not appeared in `find_orders`. Lists can lag and return up to 25 results; pass `next` back as `after` with the same filters. `read_order` returns the latest 25 payment events and indicates when there are more. OrbCart refuses an answer over 64 KB rather than cutting it off. The tools do not return buyer details, checkout or Order access tokens, payment setup or provider references. They do not search by customer, retry payments, issue refunds or change any state. OrbCart reports what it knows about a Payment, not why a provider failed. The owner's [AI Chat setting](/docs/admin/chat) applies only to the admin's model. External clients need the staff member's OAuth consent instead. ## Customize | You want to | Do this | Default | | ---------------------------------------- | ----------------------------------------------------- | ------------------- | | Keep final checkout consent on your site | Leave `consent` omitted or `"storefront"` | `"storefront"` | | Allow in-agent checkout via AP2 | Set `consent: "mandate"` and configure `googlePay` | Storefront hand-off | | Track agent-originated Orders | Check `journey.origin === "agent"` on `order.created` | Same Order pipeline | ## Next steps | You want to | Read | | ---------------------------------------- | ---------------------------------------- | | Set up the required read-only Order page | [The order page](/docs/cart/order-page) | | Test full purchases in Vitest | [Testing](/docs/cart/testing) | | Review agent signature security | [Security](/docs/cart/security) | | Expose your catalog to AI agents | [Catalog for AI agents](/docs/catalog/agents) | # Appointments in checkout Reserve bookable service visits or rentals during checkout, commit them atomically with Orders, and reschedule booked visits. Appointments are a beta feature powered by [OrbCatalog](/docs/catalog) capacity and OrbCart's hold and outbox lifecycle. Storefronts select a time on the Cart Line; OrbCart reserves and commits it atomically with the Order. ## Connect appointments and add a Line Wire the five signed appointment contracts and register the `AppointmentSelection` Line extension in `defineCommerce`: ```ts worker import { AppointmentSelection, defineCommerce, http } from "@orbcart/runtime"; export default defineCommerce({ channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE" } }, offers: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/offers`), appointments: { reserve: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/appointments/reserve`), release: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/appointments/release`), commit: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/appointments/commit`), freeTimes: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/appointments/free-times`), move: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/appointments/move`), }, extensions: { appointment: { on: "line", schema: AppointmentSelection } }, }); ``` Add a bookable service Line through `@orbcart/client`: ```ts browser import { createCommerce } from "@orbcart/client"; const commerce = createCommerce({ key: "pk_test_example", url: "https://commerce.clayandcrema.de", }); const cart = await commerce.cart(); await cart.add("GRINDER-SERVICE", { quantity: 1, configuration: { appointment: { location: "loc_roastery0001", start: "2026-11-14T09:00:00.000Z", group: "visit-1", context: { Machine: "Manual espresso grinder" }, }, }, }); ``` `context` holds readable labels visible only to authorised calendar staff (never in events). ## Visits, resources, rentals and configured durations - **Grouped visits:** work Lines sharing a Location, `start` and `group` run sequentially in Cart order inside one Appointment and reserve/commit together. Query grouped slots with `catalog.appointments.visitFreeTimes({ location, services: [{ sku, quantity, selectedOptions }], from, days })`. - **Resources (`place`, `person`, `asset`):** each concrete resource has capacity `1`. Capabilities within one requirement must coexist on a single resource; separate requirements claim distinct resources: ```json { "mode": "work", "requirements": [ { "capabilities": ["bench", "calibration"] }, { "capabilities": ["technician"] } ], "duration": { "minutes": 45, "per": "appointment" }, "buffer": { "before": 0, "after": 15 } } ``` - **Rentals (`mode: "rental"`):** pass an explicit `end` instead of work duration; assets stay occupied overnight and across closed days while pickup and return fall within opening hours. - **Configured durations:** publish `durationOptions` alongside SKU needs and pass `selectedOptions` on the Line (and optional `selection.units` for per-unit durations). Unknown keys or durations over 24 hours are refused; merchant `offers` must validate the exact selected keys. - **Virtual teams:** save a Location with `virtual: true` and `services: ["appointments"]` (omitting `address` and `coordinates`) for scheduling teams without physical premises. ## External Source-led schedules When an external ERP leads capacity for a Location, assign one Source via `PUT /panel/appointments/source` and push `appointmentGroups`, `appointmentMappings`, `appointmentCapacity` (up to 56 days / 50,000 slots with `usableUntil`) and optional `appointmentSchedules` (up to 50 resources) under `/sync/v1/appointments`. - Mappings bind `(location, capability)` to `{ kind: "local" }` or AND/OR Source group alternatives. - Fresh snapshots never silently erase local claims; inspect occupancy and gaps with `staff.appointmentCalendar({ location, from, to })` and `appointmentDiagnostics({ location, from, to, limit })`. ## Hold lifetime, payment and commit - **Holds:** Quotes reserve capacity until `hold.expiresAt`. Changing appointment Lines or a declined/cancelled payment releases the old hold immediately. - **Pre-payment validation:** expired appointment Quotes are rejected rather than silently replaced; live selections extend through the Channel's `paymentWindow` (or `PaymentProvider.checkoutValidity`, such as PayPal's 3-hour window) before starting payment. - **Durable commit:** `commitHold` commits appointments exactly once (including for `pay_on_site` Orders). If capacity is gone after a delayed payment, the Order records `appointment_not_committed` with affected Line IDs for staff follow-up. - **Reading status:** buyers and staff read `order.appointments` (`pending`, `confirmed` with native IDs and `location`/`resources`, or `unavailable`). ## Move a booked visit Staff with `orders:edit` at the appointment's Location can read free slots and reschedule the whole visit atomically: | Operation | Endpoint | Response | | ----------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------- | | Read free starts (1–14 days) | `GET /v1/orders/{order}/appointments/{appointment}/free-times?from=…&days=7` | `{ status: "available", times: [{ start, end }] }` | | Move visit (with `Idempotency-Key`) | `POST /v1/orders/{order}/appointments/{appointment}/move` with `{ start, notifyBuyer }` | `{ status: "moved" \| "time_taken" \| "unknown", order }` | - Repeat the exact same `Idempotency-Key` and body after `unknown` (different input under the same key returns `422 idempotency_key_reused`). - Calendar-side moves or cancellations sync back to OrbCart via `POST /v1/orders/{order}/appointment-changes` and emit a signed `order.appointments_changed` event (`notifyBuyer` tells your event receiver whether to email the buyer). ## Customize | You want to | Do this | Default | | ----------------------------------------------- | -------------------------------------------------------------- | -------------------------- | | Require extra capabilities for multi-job visits | Set `settings.appointments.multiWorkplace` in Catalog | None | | Schedule teams without a street address | Set `virtual: true` on an appointment-only Location | Physical premises required | | Sync capacity from an external ERP | Push groups, mappings and capacity via `/sync/v1/appointments` | Local Catalog resources | ## Next steps | You want to | Read | | ---------------------------------------------- | -------------------------------------------------------------- | | Query public free times and SKU needs | [Read the catalog](/docs/catalog/storefront#free-appointment-times) | | Tax on-site workshop services at your Location | [Tax](/docs/cart/tax#work-performed-at-your-location) | | Notify buyers on `order.appointments_changed` | [Order events](/docs/cart/order-events) | | Host appointment contracts over HTTP | [Contracts in another system](/docs/cart/remote-contracts) | # Sending the buyer's emails Send order confirmations, withdrawal receipts, failed-payment notices and abandoned-cart reminders from OrbCart events. OrbCart does not send emails itself. Subscribe your mail endpoint to OrbCart's signed events, load the current record with your secret key (since events carry no personal data), and send through your own mail system. | Email | Event | Load with `@orbcart/admin` | | -------------------------- | ------------------------------------ | ----------------------------------------------- | | Order confirmation | `order.created` | `admin.orders.get(event.subject)` | | Withdrawal receipt | `withdrawal.received` | `admin.withdrawals.get(event.data.withdrawal)` | | Gift card delivery | `gift_card.issued` (with `order`) | `admin.giftCards.delivery(event.data.giftCard)` | | Payment failed / cancelled | `payment.failed`, `payment.canceled` | `admin.carts.get` or `admin.orders.get` | | Abandoned cart reminder | `cart.abandoned` | `admin.carts.get(event.subject)` | ## Wire up your mail receiver Attach your mail endpoint in `defineCommerce` and verify every incoming delivery with `verifyEvent()`: ```ts title="src/worker.ts" import { defineCommerce, http } from "@orbcart/runtime"; export default defineCommerce({ channels, offers, events: { mails: http("https://mail.clayandcrema.de/orbcart", { types: [ "order.created", "payment.failed", "payment.canceled", "cart.abandoned", "withdrawal.received", ], }), }, }); ``` ```ts title="mail.clayandcrema.de/orbcart.ts" import { createAdmin, verifyEvent } from "@orbcart/admin"; import type { EventOf } from "@orbcart/admin"; const admin = createAdmin({ url: env.ORBCART_URL, key: env.ORBCART_SECRET_KEY }); export async function handle(request: Request): Promise { const event = await verifyEvent(request, { url: env.ORBCART_URL }); switch (event.type) { case "order.created": await confirmOrder(event); break; case "payment.failed": case "payment.canceled": await paymentDidNotGoThrough(event); break; case "cart.abandoned": await cartLeftBehind(event); break; case "withdrawal.received": await confirmWithdrawal(event); break; } return new Response(null, { status: 204 }); } ``` Return `2xx` only after the mail is sent or durably queued, and deduplicate by `event.id` (OrbCart retries failures for 72 hours with the same ID). ## Order confirmation and withdrawal receipt ### Order confirmation ```ts continues async function confirmOrder(event: EventOf<"order.created">) { const order = await admin.orders.get(event.subject); await mail.send({ idempotencyKey: event.id, to: order.contact.email, locale: order.locale, template: "order-confirmation", data: { number: order.number, lines: order.quote.lines.map((line) => ({ title: line.offer.title, quantity: line.quantity, })), total: order.quote.totals.total, shipTo: order.quote.shipTo, orderUrl: order.url, }, }); } ``` Include your terms and withdrawal policy in the email (matching the exact `version` listed in `order.quote.legal`) so the buyer receives them on a durable medium. ### Receipt of a withdrawal Send a receipt for every `withdrawal.received` event (whether matched to an Order or not) repeating only what the shopper submitted and `receivedAt`, so the email never leaks whether an order exists: ```ts continues async function confirmWithdrawal(event: EventOf<"withdrawal.received">) { const declared = await admin.withdrawals.get(event.data.withdrawal); await mail.send({ idempotencyKey: event.id, to: declared.email, template: "withdrawal-receipt", data: { name: declared.name, number: declared.number, goods: declared.goods.type === "some" ? declared.goods.description : "all", receivedAt: declared.receivedAt, locale: declared.locale, }, }); } ``` Declarations stay readable for 180 days. `order.withdrawn` notifies your ERP later once recorded on an Order and needs no second email. ## Payment failed and abandoned cart ### Payment did not go through Ignore buyer-initiated `cart_changed` and `payment_method_changed` cancellations. Delay 15 minutes before mailing so buyers who retry immediately are not interrupted: ```ts continues async function paymentDidNotGoThrough(event: EventOf<"payment.failed" | "payment.canceled">) { const { reason } = event.data; if (reason === "cart_changed" || reason === "payment_method_changed") return; await jobs.later({ minutes: 15, key: event.id, job: () => mailUnpaidBuyer(event) }); } async function mailUnpaidBuyer(event: EventOf<"payment.failed" | "payment.canceled">) { const { amount, method } = event.data; const to = event.subject.startsWith("ord_") ? (await admin.orders.get(event.subject)).contact.email : await emailIfStillUnpaid(event.subject); if (!to) return; await mail.send({ idempotencyKey: event.id, to, template: "payment-did-not-go-through", data: { amount, method }, }); } async function emailIfStillUnpaid(cartId: string) { const cart = await admin.carts.get(cartId); return cart.lifecycle.status === "open" ? cart.contact?.email : undefined; } ``` ### Abandoned cart reminder `cart.abandoned` fires after `abandonedAfterHours` (24 hours by default). Verify marketing consent before sending: ```ts continues async function cartLeftBehind(event: EventOf<"cart.abandoned">) { const cart = await admin.carts.get(event.subject); const email = cart.contact?.email; if (!email || cart.lifecycle.status !== "open" || !(await agreedToMarketing(email))) return; await mail.send({ idempotencyKey: event.id, to: email, template: "cart-left-behind", data: { lines: cart.lines.map((line) => ({ title: line.offer?.title, image: line.offer?.image, quantity: line.quantity, })), cartUrl: "https://clayandcrema.de/cart", }, }); } ``` ## OrbPage form notifications If you run the family mail worker alongside [OrbPage](/docs/page), OrbPage also emits signed `form.submitted` events (containing only form and submission IDs, verified via `verifyEvent` from `@orbpage/client`). Routing lives in OrbPage's private deployment config (`FORM_EVENTS`, `EVENT_SIGNING_KEY`, `FORM_NOTIFICATIONS`); the mail worker reads answers over its private `PAGE_NOTIFICATIONS` Service Binding (`FormNotifications` entrypoint). Team notifications and visitor confirmations retry independently for 72 hours, and private snapshots expire after 180 days. ## Current limits Not possible today: - **Cart return links:** OrbCart cannot mint a cross-device guest Cart link yet; link to your `/cart` or `/checkout` page (which restores the Cart on the same browser or for signed-in buyers). - **Automatic confirmation-mail monitoring:** watch `admin.receivers.list()` for a growing `backlog`. ## Customize | You want to | Do this | Default | | ----------------------------------- | --------------------------------------------------------------------- | ------------------------- | | Change abandoned-cart delay | Set `abandonedAfterHours` (1–720) on the Channel | `24` hours | | Deliver to a Worker instead of HTTP | Use `service("MAILER")` under `events` | Signed `http()` endpoint | | Send gift card codes to buyers | Subscribe to `gift_card.issued` and call `admin.giftCards.delivery()` | Not subscribed by default | ## Next steps | You want to | Read | | ---------------------------------------------- | ------------------------------------------- | | Inspect the full event catalog and retry rules | [Order events](/docs/cart/order-events) | | Set up the read-only Order page link | [The order page](/docs/cart/order-page) | | Implement the EU withdrawal flow | [The withdrawal function](/docs/cart/withdrawal) | | Sell and deliver gift cards | [Gift cards](/docs/cart/gift-cards) | # Carts Create Carts, manage Lines, persist Cart tokens safely across reloads, and handle errors with @orbcart/client. `@orbcart/client` manages Carts in the browser, on your server, or in an agent. Every mutation returns the complete updated Cart, so you never need a second request to refresh totals. ## Connect and add a Line Create one client with your OrbCart publishable key (`pk_test_…` from [`orbcart dev`](/docs/cart/cli), never a Stripe key): ```ts title="lib/commerce.ts" import { createCommerce } from "@orbcart/client"; export const commerce = createCommerce({ url: process.env.ORBCART_URL, key: process.env.ORBCART_PUBLISHABLE_KEY, }); ``` Pass `language: "en"` if your storefront switches languages; localised text (such as [shipping titles](/docs/cart/shipping#in-several-languages)) returns in that language while prices stay fixed to the Channel. Create a Cart and add an item, or do both in one request: ```ts const cart = await commerce.cart(); const current = await cart.add("DAYBREAK-250G-BEANS", { quantity: 2 }); ``` ```ts const cart = await commerce.cart({ lines: [{ reference: "DAYBREAK-250G-BEANS", quantity: 2 }] }); ``` The browser sends only references and quantities; prices always come from your `offers` contract. ## Read, update and remove Lines Inspect the returned Cart snapshot and update Lines by their `line.id` (not by SKU): ```ts current.lines; // [{ id, reference, quantity, status, offer: { title, price } }] current.estimate.totals; // { subtotal, discount, shipping, tax, total } current.missing; // ["ship_to", "email"] current.changes; // [{ type: "price_changed", line, from, to }] current.shippingMethods; // [{ id: "standard", title, price, deliveryTime }] current.paymentMethods; // [{ id: "card", provider: "stripe", flow: "inline" }] current.lifecycle; // { status: "open" } ``` ```ts const [line] = current.lines; await cart.setQuantity(line.id, 3); await cart.remove(line.id); ``` Adding the same reference again increments that Line's quantity. Always render `current.changes` so buyers see price updates or out-of-stock notices immediately. ## Set contact, addresses and shipping ```ts await cart.setContact({ email: "anna@example.com" }); await cart.setShipTo({ name: "Anna Berg", line1: "Bergstraße 12", postalCode: "10115", city: "Berlin", country: "DE", }); await cart.setShipping("express"); ``` Without a separate billing address, `shipTo` is used for billing. Call `cart.setBillTo(address)` or `cart.removeBillTo()` when billing differs. You can also pass all details in one call to [`cart.quote()`](/docs/cart/quotes). Query country-specific postal code and region rules once per country: ```ts const format = await commerce.addressFormat("IE"); // { postalCode: { required, pattern, kind: "eircode" }, region: { required, kind: "county", options } } ``` ## Keep the Cart across reloads Persist `cart.token` in your session and reopen it later with `openCart()` (no network call) and `read()`: ```ts const cart = commerce.openCart(savedToken); const current = await cart.read(); ``` A Cart token grants access to that Cart and its personal details. Never put it in URLs, analytics or logs. Store it in an `HttpOnly`, `Secure`, `SameSite=Lax` cookie for up to 180 days. ### Store the token in a cookie In React Router, store the token in an `HttpOnly` cookie and expose a same-origin route to update it: ```ts title="app/cart-cookie.server.ts" import { createCookie } from "react-router"; export const cartCookie = createCookie("cart", { httpOnly: true, secure: true, maxAge: 15_552_000, // 180 days }); ``` ```ts title="app/routes/cart-token.ts" import type { ActionFunctionArgs } from "react-router"; import { cartCookie } from "../cart-cookie.server"; export async function action({ request }: ActionFunctionArgs) { if (request.headers.get("Origin") !== new URL(request.url).origin) { return new Response(null, { status: 403 }); } const token = (await request.formData()).get("token"); if (typeof token !== "string") return new Response(null, { status: 400 }); return new Response(null, { status: 204, headers: { "Set-Cookie": await cartCookie.serialize(token), "Cache-Control": "no-store" }, }); } ``` See [Add to cart and a mini cart](/docs/cart/add-to-cart) for the full storefront integration. ## After a purchase and storefront state Once a purchase is submitted (`ordered` or waiting on a payment provider), move the buyer to a fresh Cart. Repeated calls within 24 hours return the same next Cart so open tabs stay in sync: ```ts import { isSubmitted } from "@orbcart/client"; if (isSubmitted(current)) { const next = await commerce.continueShopping(cart.token); saveCartToken(next.token); } ``` ### One shopping Cart for the whole storefront `createShoppingCart()` manages creation on first add, post-purchase rollover, sign-in hand-off and expired Cart recovery automatically for any framework: ```ts import { createShoppingCart } from "@orbcart/client"; const shopping = createShoppingCart({ commerce, token: savedToken, onCartChange: (cart) => saveCartToken(cart.token), }); shopping.subscribe((cart) => render(cart)); await shopping.follow(savedToken); await shopping.add("DAYBREAK-250G-BEANS"); ``` In React, [`CartProvider`](/docs/cart/react-checkout#a-cart-for-the-whole-storefront) wraps `createShoppingCart()`. ## Handle errors Refused mutations throw `CommerceError`. When the error is recoverable, `error.problem.cart` holds the current Cart: ```ts import { CommerceError } from "@orbcart/client"; try { await cart.enterCode(input.value); } catch (error) { if (error instanceof CommerceError && error.problem.code === "code_invalid") { showFieldHint("This code does not apply to your bag."); } else { throw error; } } ``` See [Errors](/docs/cart/errors) for every error code. ## Customize | You want to | Do this | Default | | -------------------------------------- | --------------------------------------------------------------------------------------- | ----------------------- | | Localise shipping and method labels | Pass `language` to `createCommerce()` | Channel's `locale` | | Create and populate a Cart in one call | Pass `{ lines }` to `commerce.cart()` | Empty Cart | | Change idle Cart lifetime | Set `expiresAfterDays` on the Channel | `180` days | | Use React hooks instead of the store | Wrap your app in [`CartProvider`](/docs/cart/react-checkout#a-cart-for-the-whole-storefront) | Plain `@orbcart/client` | ## Next steps | You want to | Read | | ------------------------------------------ | ------------------------------------------------ | | Turn a Cart into a signed Quote and Order | [Quotes & payments](/docs/cart/quotes) | | Build a header bag with cookie persistence | [Add to cart and a mini cart](/docs/cart/add-to-cart) | | Drop in the ready-made React checkout | [React checkout](/docs/cart/react-checkout) | | Look up every client error code | [Errors](/docs/cart/errors) | # A checkout with a page per step Give contact, delivery and payment their own routes in React Router while keeping Cart state in charge. This recipe maps `/checkout/contact`, `/checkout/delivery` and `/checkout/payment` to one `` component so browser back/forward, reloads and payment redirects always land on the right step. **Prerequisites:** a React Router storefront and a Cart ([Add to cart and a mini cart](/docs/cart/add-to-cart)). See [Run in steps](/docs/cart/react-checkout#run-in-steps) for single-page steps. ## 1. Render one `/checkout/:step` route ```tsx title="CheckoutStepPage.tsx" import { useNavigate, useParams } from "react-router"; import type { CommerceCart } from "@orbcart/client"; import { Checkout, CheckoutAddress, CheckoutContact, CheckoutExtensions, CheckoutPayment, CheckoutShipping, CheckoutStep, CheckoutSummary, } from "@orbcart/react"; import "@orbcart/react/styles.css"; export function CheckoutStepPage({ cart }: { cart: CommerceCart }) { const { step = "contact" } = useParams(); const navigate = useNavigate(); return ( navigate(`/checkout/${name}`)} onOrdered={(order) => navigate(`/orders/${order.number}`)} > ); } ``` ## 2. How navigation and state behave `onStepChange(name)` fires when the buyer clicks **Continue**, clicks **Change** (or a notice button), or visits a step URL the Cart does not allow yet (for example `/checkout/payment` before entering an email). Always navigate to `/checkout/${name}` **without** preserving old query parameters such as `?payment=…`. | What persists | Where | | --------------------------------- | ------------------------------------------------------ | | Saved step values | On the Cart (saved on **Continue**) | | Unsaved form drafts | Tab `sessionStorage` per Cart (cleared when ordered) | | Server refusals & decline notices | Carried across step navigation to the target step | | Card details | Never carried across pages (stays on the payment step) | ## Result - Clicking **Continue** navigates to the next incomplete step and focuses its heading. - Browser Back, reloads, early URL visits and failed provider redirects all land on the correct step with entered details preserved. ## Next steps | You want to | Read | | --------------------------------------------------- | -------------------------------------------------------- | | Explore all `` props, regions and theming | [React checkout](/docs/cart/react-checkout) | | Add Apple Pay, Google Pay and PayPal buttons | [Express checkout](/docs/cart/express-checkout) | | Build multi-step checkout outside React | [A checkout without React](/docs/cart/checkout-without-react) | # A checkout without React Build a framework-free checkout page in plain TypeScript using @orbcart/client's checkout store. This recipe builds a complete checkout page in plain HTML and TypeScript using `cart.checkout()` from `@orbcart/client`. Vue, Svelte and Solid apps subscribe to the same store. **Prerequisites:** a Cart with at least one Line, its token rendered into the page as `savedToken`, and `card` mapped in your Channel's [`payments`](/docs/cart/payments). ## 1. Markup ```html title="checkout.html"

``` ## 2. Subscribe to the checkout store ```ts title="src/checkout.ts" import { createCommerce, describe, formatMoney } from "@orbcart/client"; import type { CheckoutState } from "@orbcart/client"; import type { MountedPayment } from "@orbcart/client/payment"; const locale = "en-GB"; const words = describe(locale); const commerce = createCommerce({ url: import.meta.env.VITE_ORBCART_URL, key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY, }); const checkout = commerce.openCart(savedToken).checkout(); const form = document.querySelector("#details")!; const field = document.querySelector("#payment-field")!; const total = document.querySelector("#total")!; const notice = document.querySelector("#notice")!; const orderButton = document.querySelector("#order")!; orderButton.textContent = words.orderButton; let card: Promise | undefined; checkout.subscribe(render); void checkout.start(); form.addEventListener("submit", (event) => { event.preventDefault(); const data = new FormData(form); const value = (name: string) => String(data.get(name) ?? ""); void checkout.submitDetails({ contact: { email: value("email") }, shipTo: { name: value("name"), line1: value("line1"), postalCode: value("postalCode"), city: value("city"), country: value("country"), }, }); }); orderButton.addEventListener("click", async () => { const method = checkout.state.paymentMethod; if (method) await checkout.placeOrder({ payment: card ? await card : method.id }); }); function render(state: CheckoutState) { if (state.order) { form.hidden = field.hidden = orderButton.hidden = true; notice.textContent = `Thank you. Your order number is ${state.order.number}.`; return; } form.hidden = state.resuming !== undefined; notice.textContent = state.notice ? words.notice(state.notice).join(" ") : ""; total.textContent = state.quote ? formatMoney(state.quote.totals.total, locale) : ""; orderButton.hidden = state.stage === "details"; orderButton.disabled = state.stage !== "quoted" || state.busy !== undefined; const method = state.paymentMethod; if (state.quote && method?.flow === "inline") card ??= checkout.mountPayment(method.id, field); } ``` - **Multiple methods:** render `state.paymentMethods`, call `checkout.choosePayment(id)`, and mount an `inline` field when needed; `redirect` methods need no mounted field. - **Billing without delivery:** check `state.fields` (`bill_to: "required"` under [`billingAddress: "required"`](/docs/cart/configuration#contactfields-and-billingaddress)) and submit `{ contact, billTo }` rather than inventing `shipTo`. ## 3. Optional: split details across steps `submitDetails()` saves only the fields you pass, and `detailsRegionOf()` maps `missing` entries to `"contact"`, `"address"`, `"shipping"` or `"extensions"`: ```ts title="src/steps.ts" import { createCommerce, detailsRegionOf } from "@orbcart/client"; const commerce = createCommerce({ url: import.meta.env.VITE_ORBCART_URL, key: import.meta.env.VITE_ORBCART_PUBLISHABLE_KEY, }); const checkout = commerce.openCart(savedToken).checkout(); void checkout.start({}, { keepNotice: true }); export const saveContact = (email: string) => checkout.submitDetails({ contact: { email } }); export const contactComplete = () => !checkout.state.cart?.missing.some((entry) => detailsRegionOf(entry) === "contact"); ``` ## Result - Invalid fields surface through `state.notice` formatted by `describe(locale)`. - Submitting valid details reveals the binding total, card field and legal order button; 3-D Secure, price changes, declines, slow payments and redirect returns are handled automatically without double-charging. ## Next steps | You want to | Read | | ----------------------------------------------------- | ---------------------------------------- | | Call `quote()`, `mountPayment()` and `pay()` directly | [Quotes & payments](/docs/cart/quotes) | | Look up every notice and error code | [Errors](/docs/cart/errors) | | Test the full checkout in Vitest | [Test a purchase](/docs/cart/test-a-purchase) | # CLI Use the orbcart CLI to run your commerce Worker locally, issue test keys and sync EU VAT rates. The `orbcart` CLI ships with `@orbcart/runtime`. Run it from your commerce Worker's directory: ```sh pnpm exec orbcart ``` | Command | What it does | | -------------------- | ---------------------------------------------------------- | | `orbcart dev` | Runs your Worker locally and writes keys for a storefront. | | `orbcart keys issue` | Issues API keys for a deployed `test` environment. | | `orbcart tax sync` | Imports today's EU VAT rates. | | `orbcart tax status` | Prints the current EU VAT import status. | Staff accounts are managed in the OrbCommerce Admin, not through the CLI. See [Staff access](/docs/cart/security#staff-access-in-the-admin). ## `orbcart dev` Start your Worker locally with `wrangler dev` and write its keys to your storefront's env file: ```sh pnpm exec orbcart dev --channel de --channel ch --keys ../storefront/.dev.vars ``` By default, `orbcart dev` listens on port `8787` (override with `--port`) and writes these entries into the `--keys` file: ```dotenv ORBCART_URL=http://localhost:8787 ORBCART_PUBLISHABLE_KEY=pk_test_... # first channel ORBCART_PUBLISHABLE_KEY_CH=pk_test_... # each additional channel, by name ORBCART_SECRET_KEY=sk_test_... ``` Existing keys that the environment still recognizes are preserved, and the file is left untouched when nothing changes so file watchers are not triggered unnecessarily. Any extra flags pass straight through to `wrangler dev`, such as `--port 8797` or `--env-file ../../.dev.vars`. For startup scripts that wait on readiness, pass `--ready-file ` to write a secret-free marker once keys are validated and written. ## `orbcart keys issue` Issue keys for a deployed `test` Worker: ```sh pnpm exec orbcart keys issue --env test --channel de --url https://shop-commerce-test.example.workers.dev ``` This writes `ORBCART_URL`, a publishable key and the secret key to `.orbcart/keys/test-de.env` with owner-only permissions. | Option | Default | | ----------------- | ---------------------------------- | | `--keys ` | `.orbcart/keys/test-.env` | | `--worker ` | `-test` | | `--config ` | `wrangler.jsonc` | `orbcart keys issue` currently supports `test` environments only and requires Wrangler to be logged in to the same Cloudflare account. The generated file contains a secret key: never commit or share it. ## `orbcart tax` Trigger or inspect the daily EU VAT rate import: ```sh pnpm exec orbcart tax sync --env test pnpm exec orbcart tax status --env test ``` `sync` runs the import immediately and exits non-zero if today's rates are unavailable. `status` prints the current state and always exits `0`. See [Tax](/docs/cart/tax#prime-and-verify-after-first-deploy). ## Planned commands `orbcart deploy` (one-step environment setup) and `npm create orbcart` (project scaffolding) are planned, not available yet. Until then, follow [Deployment](/docs/run/deployment). ## Next steps | You want to | Read | | ---------------------------- | ------------------------------------------ | | Run the local stack | [OrbCart quickstart](/docs/get-started/orbcart) | | Deploy OrbCart to Cloudflare | [Deployment](/docs/run/deployment) | | Call the HTTP API directly | [HTTP API](/docs/cart/http-api) | # Concepts The mental model of OrbCart: who owns what, the core terms of a purchase, and why it is designed this way. **You own the catalog. OrbCart owns the purchase.** Products, prices and stock stay in your systems. OrbCart takes a reference and a quantity, asks your systems for current facts, and turns them into a signed Quote, a Payment and an Order. Two front doors lead into one Cart: your storefront, where the buyer shops with a publishable key, and AI agents, which buy for a buyer over UCP with signed requests. The Cart holds the purchase from its Lines to the Quote, the Payment and the Order, in a Worker in your own Cloudflare account. Behind it, your systems answer through small contracts for prices, stock, tax and the hand-off to your ERP, and the payment provider moves the money and reports back by webhook. Both doors follow the same rules. A storefront or an agent can only express what the buyer wants. Everything binding, from unit prices to the final total, is calculated on the server. ## Core terms ### Offer **What you are willing to sell right now.** Your [offers function](/docs/cart/offers) returns an Offer whenever OrbCart needs current product facts: ```ts value="OfferedReference" { reference: "DAYBREAK-250G-BEANS", title: "Daybreak · 250 g · Whole bean", price: { amount: 1290, currency: "EUR" }, taxCategory: "standard", shipping: { weightInGrams: 270 }, } ``` An Offer is not a catalog record: it carries no images, descriptions or categories. Those stay in your storefront. Money is always an integer in minor units paired with its currency (`1290` + `EUR` = €12.90). Use `formatMoney()` to display it. ### Line **One item the buyer chose:** a reference and a quantity. OrbCart assigns every Line its own `id`: ```ts browser await cart.add("DAYBREAK-250G-BEANS", { quantity: 2 }); ``` Add items by **reference**. Update or remove them by **Line ID**. ### Cart **The purchase while it takes shape.** It holds Lines, contact details, addresses, shipping choice and discount codes. Every mutation returns the full Cart, including two fields your UI relies on: - `estimate` is the current, non-binding price. `estimate.excludes` lists what is not included yet, such as `"shipping"` or `"tax"`. - `missing` lists what the buyer still needs to provide, in checkout order: `["ship_to", "email"]`. ### Quote **The exact deal the buyer agrees to.** A Quote freezes the Lines, prices, tax, shipping and total. It is cryptographically signed and expires after at most 30 minutes. If anything changes before the buyer pays, OrbCart responds with `quote_changed`, a fresh Quote and the list of changes. A buyer is never charged a total they did not approve. ### Payment **The money movement for one accepted Quote.** A provider such as Stripe, Adyen, Mollie, PAYONE, PayPal or Amazon Pay moves the funds. OrbCart initiates the Payment, tracks it and never guesses its outcome: an unclear response becomes `unknown` until the provider confirms it. ### Order **The immutable record of an agreed purchase.** It preserves the signed Quote even when your prices change later. Payment, shipping and refunds evolve beside it, while the agreed purchase itself never changes. Handing the Order to your ERP is a separate step, retried until your ERP accepts it. ### Environment and Channel An **Environment** is an isolated deployment (such as `test` or `live`) with its own Worker, keys and data. A **Channel** is one market or storefront inside an Environment. Each Channel defines its currency, tax rules, shipping methods, payment providers and allowed browser origins. A publishable key belongs to one Channel. | Environment | Channel | Currency | Tax | Payment methods | | ----------- | ------- | -------- | --------- | -------------------- | | `live` | `de` | `EUR` | EU VAT | Card, PayPal, Klarna | | `live` | `ch` | `CHF` | Swiss VAT | Card, TWINT | ## Design principles - **The server decides.** Clients send references, quantities and choices. Prices, tax, discounts and totals are computed only on the server, so tampered requests have nothing to alter. - **The Quote freezes the deal.** Consent, Payment and Order all point to one signed Quote. If a price moves mid-click, the buyer gets a new Quote instead of an unexpected charge. - **Retries are safe.** Every mutation carries an `Idempotency-Key`, so retries replay the original response instead of duplicating work. The SDKs handle keys automatically. - **Every state has one owner.** Each Cart is a Durable Object that owns its Quotes, Payment and Order. Lists and dashboards read a copy, never making decisions from it. - **Your catalog is asked, not copied.** There is no import or sync to maintain. OrbCart calls `offers` when it needs facts, and you can [invalidate a price](/docs/cart/offers#end-a-sale-early) immediately when a sale ends. ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------ | | Trace one purchase end to end | [How it works](/docs/cart/how-it-works) | | Understand keys, tokens and trust | [Security](/docs/cart/security) | | Configure markets, shipping and rules | [Configuration](/docs/cart/configuration) | | Connect your own prices and stock | [Offers](/docs/cart/offers) | # Configuration Configure markets, shipping, payments, tax, legal texts and integrations in one defineCommerce call. Your commerce Worker exports OrbCart's Durable Objects and one `defineCommerce()` call. Only `channels` and `offers` are required; everything else is optional. ## The smallest configuration ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; export * from "@orbcart/runtime/objects"; export default defineCommerce({ channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", tax: "eu-standard", shipping: { DE: [{ id: "standard", title: "Standard delivery", price: 495 }] }, payments: { card: "stripe", paypal: "paypal" }, origins: ["https://clayandcrema.de"], returnUrl: "https://clayandcrema.de/checkout", }, }, offers, }); ``` OrbCart validates your entire configuration when the Worker starts. Invalid values fail deployment; missing provider keys or a `returnUrl` outside `origins` fail every request with `internal` and log the reason, never only the first buyer. ## Top-level options | Option | Required | Purpose | | ------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `channels` | Yes | Your markets by key (such as `de`, `ch`, `b2b`). At least one. | | `offers` | Yes | Prices and product facts for Cart Lines ([Offers](/docs/cart/offers)). | | `inventory` | No | Stock checks and reservations ([Inventory](/docs/cart/inventory)). | | `pickupLocations` | No | Catalog Locations contract required when any Channel defines a `pickup` rule ([Shipping](/docs/cart/shipping#collect-at-a-store-pickup)). | | `appointments` | No | Bookable service appointments contract ([Appointments](/docs/cart/appointments)). | | `paymentProviders` | No | Custom payment provider implementations ([Payment provider](/docs/cart/payment-provider)). | | `deliverOrder` | No | Push every new Order to your ERP ([ERP hand-off](/docs/cart/inventory#hand-orders-to-your-erp)). | | `fetchOrders` | No | Set `true` when your ERP polls Orders instead of `deliverOrder`. | | `events` | No | Receivers for Order and Cart events ([Order events](/docs/cart/order-events)). | | `orderActions` | No | Custom admin actions on Orders ([Order actions](/docs/cart/order-actions)). | | `orderNumbers` | No | Format, counter and per-Channel numbering of Orders ([Order numbers](#order-numbers)). | | `giftCards` | No | Code format, expiry and value limits ([Gift cards](/docs/cart/gift-cards)). | | `identity` | No | Signed-in buyer JWT verification ([Identity](/docs/cart/identity)). | | `extensions` | No | Typed custom fields on Carts or Lines ([Extensions](/docs/cart/extensions)). | ## Channel options Each Channel is one market with its own currency, tax, shipping and payment rules: | Option | Example | Purpose | | --------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------- | | `identity` | `"catalog"` | Read `currency`, `pricesIncludeTax` and `locale` from OrbCatalog instead of setting them here. | | `currency` | `"EUR"` | ISO 4217 currency code (one per Channel, unless `identity: "catalog"`). | | `pricesIncludeTax` | `true` | `true` for gross prices (B2C), `false` for net prices (B2B). | | `locale` | `"de-DE"` | Default language for Orders and confirmations. | | `tax` | `"eu-standard"` | Tax rule or contract ([Tax](/docs/cart/tax)). | | `taxRounding` | `"total"` | Set `"line"` if your ERP rounds tax per Line. | | `shipping` | `{ DE: [...] }` | Delivery and pickup rules by country ([Shipping](/docs/cart/shipping)). | | `shippingRates` | `async (…) => […]` | Live rate contract required when a shipping rule uses `price: "quoted"`. | | `payments` | `{ card: "stripe" }` | Payment methods mapped to providers ([Payments](/docs/cart/payments)). | | `discounts` | `[{ id, code, percentage }]` | Seed discounts created on first run ([Discounts](/docs/cart/discounts)). | | `contactFields` | `{ phone: "optional" }` | Extra contact fields beyond email. | | `billingAddress` | `"required"` | Require full billing address even for pickup or digital carts. | | `abandonedAfterHours` | `24` | Idle hours before emitting `cart.abandoned`. | | `expiresAfterDays` | `180` | Idle days (1 to 365) before deleting an unordered Cart. | | `origins` | `["https://clayandcrema.de"]` | Browser origins allowed to call this Channel. | | `returnUrl` | `"https://clayandcrema.de/checkout"` | Redirect return page for PayPal, Klarna, iDEAL and similar. | | `orderPage` | `"https://clayandcrema.de/orders"` | Base URL for read-only [Order links](/docs/cart/order-page). | | `agents` | `{ continueUrl }` | Enable AI agent checkouts ([AI agents](/docs/cart/agents)). | | `legal` | `{ withdrawal_policy: { url, version } }` | Versioned legal texts linked at checkout and hashed in Quotes. | ### `origins` and `returnUrl` List exact origins (`scheme://host[:port]`, no path or trailing slash). In `test`, `localhost` is always allowed. `returnUrl` is required whenever a Channel enables a redirect payment method and must belong to one of the Channel's `origins`. That page calls [`cart.resume()`](/docs/cart/quotes#5-return-from-a-redirect). ### `contactFields` and `billingAddress` Checkout always asks for an email address. Ask for extra contact fields only when needed (a shipping rule's `requires` can also require a field for that method alone): ```ts members="ChannelConfig" contactFields: { phone: "optional" }, ``` By default, non-shipping and pickup Carts require only a billing country. Set `billingAddress: "required"` to require a full billing name and address (`bill_to`, `bill_to_postal_code`, `bill_to_region`) on every Cart, including express checkout: ```ts members="ChannelConfig" billingAddress: "required", ``` ### `legal` Keep your legal texts on your own pages and declare their URL and `version` per Channel. OrbCart links them beside the order button and hashes each version into every Quote: ```ts members="ChannelConfig" import withdrawalPolicy from "./legal/widerruf.txt"; legal: { terms: { url: "https://clayandcrema.de/agb", version: "2026-09-01" }, withdrawal_policy: { url: "https://clayandcrema.de/widerruf", version: "2026-06-19", content: withdrawalPolicy, // optional: hashes the text itself }, privacy_policy: { url: "https://clayandcrema.de/datenschutz", version: "2026-05-01" }, }, ``` Bump `version` when a policy changes; existing Quotes keep their original version, and the next Quote surfaces `legal_updated`. In `live`, every Channel must declare `withdrawal_policy` and `privacy_policy` (`terms` is optional). ## Multiple markets Add one Channel entry per market. Your `offers` function receives the Channel's `currency`, and [`orbcart dev`](/docs/cart/cli) issues one publishable key per Channel: ```ts members="CommerceConfig" channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", tax: "eu-standard", shipping: { DE: [standard], AT: [standard] }, payments: { card: "adyen", paypal: "paypal", klarna: "adyen" }, }, ch: { currency: "CHF", pricesIncludeTax: true, locale: "de-CH", tax: swissVat, shipping: { CH: [swissPost] }, payments: { card: "adyen", twint: "adyen" }, }, }, ``` ## Order numbers Every Order gets its number once its payment is decided, in a format you choose. Text in the format stays as written; the tokens fill in: | Token | Writes | | ------------ | ------------------------------------------------------------------------------------- | | `{seq}` | The counter, such as `4711`. `{seq:6}` pads it with zeros to `004711`. | | `{random:8}` | 8 random digits, 6 to 15 allowed. Nobody can tell from them how many Orders you take. | | `{yyyy}` | The UTC year of the Order, such as `2026`. `{yy}` writes `26`. | A format has exactly one `{seq}` or `{random:N}`. Text may use letters, digits, `.` and `-`. ```ts members="CommerceConfig" orderNumbers: { format: "OF-{seq:7}", startAt: 1_123_324, // the next number of your old shop channels: { b2b: { format: "{yyyy}-B-{seq:4}", restart: "yearly" }, // 2026-B-0001, from 1 each year outlet: { format: "OUT-{random:8}" }, // OUT-48291034 }, }, ``` - **One counter per numbering.** A Channel under `channels` counts on its own; every other Channel shares the environment's counter. - **Numbers per store.** `locations` gives the Orders of a Location a format of its own. An Order belongs to the Locations where it is picked up, where its goods come from and where its appointments are; what ships from your own stock belongs to none. The first Location with a format names the Order, so a mixed Cart takes the store's format, and every store counts on with the environment's counter: ```ts members="CommerceConfig" orderNumbers: { format: "FW-{seq}", // online shop only: FW-1001 locations: { loc_store17: { format: "F17-{seq}" }, // anything from store 17: F17-1002 loc_store03: { format: "F03-{seq}" }, }, }, ``` - **`startAt`** is the counter's first value, so numbering continues where an older system stopped. It counts only for a counter that has never numbered an Order. - **`restart: "yearly"`** starts the counter at 1 each UTC year, and so needs `{yyyy}` or `{yy}` in the format. - **Unique, whatever you change.** No two Orders share a number. Change a format later and new Orders follow it while existing ones keep theirs; a counter skips any number that was already given, and random digits are drawn again. The deployment fails if two counters would write numbers of the same shape, such as `A-{yyyy}-{seq}` and `A-2026-{seq}`. - **Found however it is typed.** `admin.orders.get()`, the admin's search and withdrawals find an Order regardless of case, separators and leading zeros: `ng 2026 4711` finds `NG-2026-004711`, and so does the counter alone, `4711`, while only one Order has it. The admin recognizes the formats you number in now. - **Size `{random:N}` generously.** Pick enough digits that your Orders over the years fill less than 1% of them, such as 8 digits for up to a million Orders. ## Time budgets and Worker bindings Every attached contract receives `context.signal` and aborts if its budget expires: | Contract | Default timeout | | ---------------------------------------- | --------------- | | `offers`, `inventory.*`, `tax` | 3 seconds | | `orderActions.*.run`, `events` receivers | 10 seconds | | `deliverOrder` | 30 seconds | Override any timeout by passing `{ run, timeoutMs }`: ```ts members="CommerceConfig" offers: { run: (lines, context) => pricing.offers(lines, context), timeoutMs: 5_000 }, ``` ### Worker vars and secrets Configure these in `wrangler.jsonc` and via `wrangler secret put`: | Name | Kind | Purpose | | --------------------------------------------------------- | ------- | --------------------------------------------------------------------------- | | `MERCHANT` | var | Your slug (such as `clayandcrema`), recorded in every Quote. | | `ENVIRONMENT` | var | `live`, `test` or `preview-{name}`. | | `PUBLIC_URL` | var | Optional public API base URL for print links, OpenAPI and event schemas. | | `ROOT_SECRET` | secret | 32 random bytes (base64url). Never replace routinely on a live environment. | | `STRIPE_*`, `ADYEN_*`, `MOLLIE_*`, `PAYONE_*`, `PAYPAL_*` | secret | Credentials for configured [payment providers](/docs/cart/payments). | | `HYPERDRIVE` | binding | Optional Postgres binding for admin Order, Cart and Event lists. | ## Customize | You want to | Do this | Default | | --------------------------------- | ----------------------------------------------- | ----------------------------- | | Customise Order numbers | Set `orderNumbers: { format: "CC-{seq}" }` | `{yyyy}-{seq:6}` | | Require full billing on all carts | Set `billingAddress: "required"` on the Channel | Country-only for non-shipping | | Increase a contract timeout | Wrap the contract with `{ run, timeoutMs }` | 3s / 10s / 30s | | Replace core ports or add plugins | See [Extend OrbCart](/docs/cart/extend) | Built-in Cloudflare runtime | ## Next steps | You want to | Read | | ------------------------------------- | ----------------------------- | | Connect your product prices and facts | [Offers](/docs/cart/offers) | | Configure shipping and store pickup | [Shipping](/docs/cart/shipping) | | Set up payment providers | [Payments](/docs/cart/payments) | | Deploy your Worker to Cloudflare | [Deployment](/docs/run/deployment) | # Discounts Configure automatic promotions, promo codes, free shipping, single-use code batches and redemption limits. Your team creates, pauses and ends discounts in the admin under _Orders → Discounts_ (or through the Admin API at `/v1/discounts`). OrbCart evaluates them, allocates them across Lines, and records them on Carts, Quotes and Orders. ## Seed discounts and apply codes Declare starter discounts on a Channel to create them on first run. Once created, they belong to your team: later deploys never overwrite edits made in the admin, and ended discounts stay ended. ```ts title="src/worker.ts" members="ChannelConfig" discounts: [ { id: "welcome", code: "WELCOME10", percentage: 10 }, ], ``` Buyers apply or remove codes case-insensitively on the Cart: ```ts browser await cart.enterCode("welcome10"); await cart.removeCode("WELCOME10"); ``` ## Common discount shapes ```ts alternatives value="Discount" // €5 off orders from €40 { id: "five-off", code: "FIVE", amount: 500, minimumSubtotal: 4000 } // Free standard shipping from €50 (automatic; express stays paid) { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] } // 20% off every unit tagged "coffee" for one weekend { id: "weekend", scope: "line", percentage: 20, tags: ["coffee"], from: "2026-10-09T22:00:00Z", until: "2026-10-11T22:00:00Z", } // First 500 buyers, once each { id: "launch", code: "LAUNCH", percentage: 15, limit: { total: 500, perBuyer: 1 } } // Exclusive: never stacks with other discounts { id: "vip", code: "VIP30", percentage: 30, combination: "exclusive" } ``` ## Discount options | Option | Example | Purpose | | ----------------------- | ------------------------------------ | ----------------------------------------------------------------------------------- | | `id` | `"welcome"` | Unique identifier in Quotes and Orders across the environment. | | `percentage` / `amount` | `10` or `500` | Percentage off, or fixed minor units off (choose one). | | `code` | `"WELCOME10"` | Requires entry by the buyer; omit for automatic discounts. | | `scope` | `"order"` | `"order"` (default), `"line"` (per matching unit) or `"shipping"`. | | `references` | `["DAYBREAK-250G-BEANS"]` | Restrict to specific Offer references. | | `tags` | `["coffee"]` | Restrict to Offers carrying these tags. | | `minimumSubtotal` | `5000` | Pre-discount minimum; shipping discounts count only matching shipped Lines. | | `methods` | `["standard"]` | Shipping discounts only: eligible rule IDs (omit for all methods). | | `from`, `until` | `"2026-10-09T22:00:00Z"` | Active window in RFC 3339 (`[from, until)`). | | `limit` | `{ total: 500, perBuyer: 1 }` | Total and per-buyer redemption caps. | | `except` | `{ tags: ["clearance"] }` | Offers excluded from both the discount and its `minimumSubtotal`. | | `locations` | `{ included: ["loc_roastery0001"] }` | Include or exclude Orders tied to specific Locations. | | `combination` | `"exclusive"` | `"combinable"` (default) stacks; `"exclusive"` keeps only the best single discount. | Gift cards (`giftCard: true` on the Offer) are never discounted and never count toward `minimumSubtotal`. ## Single-use code batches and limits Generate single-use code batches in the admin by choosing a prefix and count (for example `ROAST` × `500` → `ROAST-7QK2-M4XA`) and export them as CSV. - **Held during checkout:** a Quote reserves the code (and any `limit.total` / `limit.perBuyer` slot) while valid, and an active payment holds it until completion so two buyers cannot race for the last use. - **Released on failure, spent on order:** failed or cancelled payments release the code; cancelled or refunded Orders do not. - **Per-buyer tracking:** `perBuyer` counts [signed-in buyers](/docs/cart/identity) by identity and guests by email address. ## What buyers see - A code that cannot apply anywhere is rejected with `code_invalid` and not stored. - A stored code that temporarily stops qualifying (such as dropping below `minimumSubtotal`, or choosing express when a code only frees `standard`) stays on the Cart and reports `code_invalid` in `cart.changes` (`reason: "shipping_method"` includes the eligible `methods`). - Applied discounts appear in `estimate.discounts` and `quote.discounts` with their deducted amounts. ## Redeem codes in your ERP Your `offers` contract receives every entered code in `context.codes`. Return redeemed codes in `appliedCodes`; OrbCart only checks its own discounts for codes that `offers` did not redeem: ```ts export const offers: OffersContract = async (lines, { codes, currency }) => { const prices = await erp.prices(lines, { codes, currency }); return prices.map((price) => ({ reference: price.sku, title: price.name, price: { amount: price.amount, currency }, taxCategory: "standard", appliedCodes: price.redeemedCodes, })); }; ``` ## Customize | You want to | Do this | Default | | ---------------------------- | ------------------------------------------------------------------------ | ------------------------------- | | Offer free standard shipping | Add a `scope: "shipping"` discount with `methods: ["standard"]` | Shipping is charged | | Exclude clearance items | Set `except: { tags: ["clearance"] }` on the discount | All non-gift-card items qualify | | End a tag-based sale early | Call `admin.offers.invalidate` ([Offers](/docs/cart/offers#end-a-sale-early)) | Expires at Offer TTL | | Evaluate promos in your ERP | Read `context.codes` in `offers` and return `appliedCodes` | OrbCart discount engine | ## Next steps | You want to | Read | | ------------------------------------------------------ | ----------------------------------------------------------------- | | Follow a complete free-shipping and welcome-code build | [Free shipping and a welcome code](/docs/cart/free-shipping-and-codes) | | Add custom fields to Carts and Lines | [Extensions](/docs/cart/extensions) | | Sell and redeem gift cards | [Gift cards](/docs/cart/gift-cards) | | Invalidate cached Offer sales | [Offers](/docs/cart/offers) | # Send paid Orders to your ERP Create one ERP sales order per paid Order via deliverOrder and report warehouse shipments back via @orbcart/admin. This recipe delivers every paid Order to your ERP exactly once (retrying automatically across outages) and reports warehouse shipments back so the buyer's Order page shows parcel tracking. **Prerequisites:** a commerce Worker, an ERP client, and your environment's secret key (`ORBCART_SECRET_KEY`). ## 1. Map the Order in `deliverOrder` Deduplicate by `order.id` and store each Line's `line.id` in your ERP so shipments and refunds reference the exact Line: ```ts title="src/erp.ts" import type { DeliverOrderContract } from "@orbcart/runtime"; export const deliverOrder: DeliverOrderContract = async (order, { signal }) => { const { shipTo, shipping, lines, totals } = order.quote; const salesOrder = await erp.createSalesOrder( { externalId: order.id, number: order.number, // e.g. CC-2026-004711 email: order.contact.email, shipTo, shippingMethod: shipping?.id, lines: lines.map((line) => ({ line: line.id, sku: line.reference, quantity: line.quantity, total: line.totals.total, })), total: totals.total, }, { idempotencyKey: order.id, signal }, ); return { reference: salesOrder.number }; }; ``` Attach it in `src/worker.ts`: ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { deliverOrder, inventory, offers } from "./erp"; export * from "@orbcart/runtime/objects"; export default defineCommerce({ channels, offers, inventory, deliverOrder }); ``` ## 2. Report shipments back from your warehouse Verify incoming ERP requests according to your ERP's auth scheme, then record each shipment with `admin.orders.fulfill()` (idempotent by `reference`): ```ts title="backend/erp-shipments.ts" import { createAdmin } from "@orbcart/admin"; import { z } from "zod"; const admin = createAdmin({ url: env.ORBCART_URL, key: env.ORBCART_SECRET_KEY }); const Delivery = z.object({ externalId: z.string(), deliveryNumber: z.string(), trackingNumber: z.string(), items: z.array(z.object({ line: z.string(), quantity: z.int().positive() })), }); export async function handle(request: Request): Promise { const delivery = Delivery.parse(await request.json()); await admin.orders.fulfill(delivery.externalId, { reference: delivery.deliveryNumber, carrier: "DHL", tracking: delivery.trackingNumber, lines: delivery.items, }); return new Response(null, { status: 204 }); } ``` ## Result - Buyers see confirmation immediately after payment while `deliverOrder` runs asynchronously (raising `handoff_failed` after 30 minutes of ERP downtime and clearing it on recovery). - Calling `fulfill()` updates the buyer's Order page with carrier and tracking and emits `order.fulfilled`. ## Next steps | You want to | Read | | ------------------------------------------------------ | -------------------------------------------------------------------- | | Let your ERP poll Orders instead (`fetchOrders: true`) | [Stock & ERP hand-off](/docs/cart/inventory#or-let-your-erp-fetch-orders) | | Host `deliverOrder` over signed HTTP | [Contracts in another system](/docs/cart/remote-contracts) | | Issue partial refunds and record returns | [Orders & refunds](/docs/cart/orders-and-refunds) | | Subscribe to `order.*` and `payment.*` events | [Order events](/docs/cart/order-events) | # Prices and stock from your ERP Implement OrbCart's offers and inventory contracts against an HTTP ERP API with Zod validation and stock holds. This recipe connects your commerce Worker to an ERP HTTP API for live prices, availability and checkout stock holds, without any catalog import or sync. **Prerequisites:** a commerce Worker ([Configuration](/docs/cart/configuration)) with `ERP_URL` and `ERP_TOKEN` configured as Worker bindings/secrets. ## 1. Write the ERP adapter Batch all references into one request per call, parse every ERP response with Zod, and throw on HTTP errors so nothing is ever sold at a guessed price: ```ts title="src/erp.ts" import { env } from "cloudflare:workers"; import type { InventoryContract, OffersContract } from "@orbcart/runtime"; import { z } from "zod"; const Article = z.object({ sku: z.string(), name: z.string(), priceInCents: z.int().nonnegative(), vatClass: z.enum(["standard", "reduced"]), weightInGrams: z.int().nonnegative(), discontinued: z.boolean(), }); const Quantity = z.object({ sku: z.string(), quantity: z.int().nonnegative() }); async function ask(path: string, body: unknown, answer: z.ZodType, signal: AbortSignal) { const response = await fetch(new URL(path, env.ERP_URL), { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${env.ERP_TOKEN}` }, body: JSON.stringify(body), signal, }); if (!response.ok) throw new Error(`ERP ${path} answered ${response.status}`); return answer.parse(await response.json()); } const items = (references: readonly { reference: string; quantity: number }[]) => references.map(({ reference, quantity }) => ({ sku: reference, quantity })); export const offers: OffersContract = async (lines, { currency, signal }) => { const skus = [...new Set(lines.map((line) => line.reference))]; const articles = await ask("/articles", { skus, currency }, z.array(Article), signal); return articles.map((article) => article.discontinued ? { reference: article.sku, unavailable: "discontinued" } : { reference: article.sku, title: article.name, price: { amount: article.priceInCents, currency }, taxCategory: article.vatClass, shipping: { weightInGrams: article.weightInGrams }, }, ); }; export const inventory: InventoryContract = { check: async (references, { signal }) => { const skus = references.map(({ reference }) => reference); const stock = await ask("/stock", { skus }, z.array(Quantity), signal); return stock.map(({ sku, quantity }) => ({ reference: sku, available: quantity })); }, reserve: async (hold, { signal }) => { const body = { id: hold.id, items: items(hold.references), until: hold.expiresAt }; const held = await ask("/reservations", body, z.array(Quantity), signal); return held.map(({ sku, quantity }) => ({ reference: sku, reserved: quantity })); }, release: async (holdId, { signal }) => { await ask(`/reservations/${holdId}/release`, {}, z.unknown(), signal); }, commit: async (holdId, orderId, { signal }) => { const booked = await ask( `/reservations/${holdId}/commit`, { orderId }, z.array(Quantity), signal, ); return booked.map(({ sku, quantity }) => ({ reference: sku, committed: quantity })); }, restock: async (restock, { signal }) => { const body = { id: restock.id, orderId: restock.orderId, items: items(restock.references) }; await ask("/restocks", body, z.unknown(), signal); }, }; ``` ## 2. Attach both contracts in your Worker ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { inventory, offers } from "./erp"; export * from "@orbcart/runtime/objects"; export default defineCommerce({ channels, offers, inventory }); ``` If your ERP needs more than 3 seconds, pass `offers: { run: offers, timeoutMs: 5_000 }` ([Time budgets](/docs/cart/configuration#time-budgets-and-worker-bindings)). ## Result - Discontinued SKUs show as unavailable; low stock clamps the Quote quantity with `quantity_changed`; zero stock or another buyer's active hold prevents overselling; ERP outages return a calm retry message rather than guessing prices. ## Next steps | You want to | Read | | ------------------------------------------------- | ------------------------------------------------------- | | Hand paid Orders back to your ERP | [Send paid Orders to your ERP](/docs/cart/erp-order-handoff) | | Call an existing middleware directly via `http()` | [Contracts in another system](/docs/cart/remote-contracts) | | Return images, deposits, tags and limits | [Offers](/docs/cart/offers) | | Understand every inventory hook | [Stock & ERP hand-off](/docs/cart/inventory) | # Errors How OrbCart reports errors as RFC 9457 Problem Details, every error code, what caused it and what to do next. Every failed request returns a Problem object. The TypeScript SDKs throw it as `CommerceError`: ```ts try { await cart.add("DAYBREAK-250G-BEANS"); } catch (error) { if (error instanceof CommerceError) { error.problem.code; // machine-readable error code error.problem.kind; // broad error category error.problem.retryable; // whether retrying may succeed error.problem.cart; // current Cart, when the buyer can fix it } } ``` Over HTTP, a Problem uses RFC 9457 Problem Details (`application/problem+json`), consistent across every OrbCommerce product: ```json { "title": "Bad Request", "status": 400, "code": "body_invalid", "kind": "invalid", "retryable": false, "requestId": "req_01J8Z3W6Q4XB7N2M5K9RTV0HCE", "detail": "The request body violates the schema of this operation; errors names each field.", "errors": [{ "pointer": "#/body/email", "code": "invalid_format", "detail": "Invalid email." }] } ``` Each entry in `errors` points to the failing field (`#/body/...` or `#/query/...`). Ignore any extra fields you do not recognize. Every `401` includes `WWW-Authenticate`. A declined card, `quote_changed` and `pending` are normal return values of `pay()` and `accept()`, not thrown errors. See [Place the order](/docs/cart/quotes#4-place-the-order). ## Decide by `kind` When your code encounters an unfamiliar `code`, use `kind` to choose the right fallback: | `kind` | What to do | | -------------- | ----------------------------------------------------------- | | `invalid` | Fix the input and show the buyer what to correct. | | `unauthorized` | Credential is missing or invalid. Fix your setup. | | `forbidden` | Credential is valid but lacks permission for this action. | | `not_found` | Resource does not exist for this credential. | | `conflict` | State moved on. Re-read the Cart and continue from there. | | `rate_limited` | Wait for `Retry-After` and retry with the same key. | | `unavailable` | Downstream system is temporarily away. Retry with same key. | | `internal` | Unexpected server error. Report the `requestId`. | ## Buyer-fixable errors Display a localized message using `describe(locale).problem(code)` rather than `detail`. | Code | Cause | What to do | | ----------------------------- | ----------------------------------------------- | -------------------------------------------------- | | `cart_incomplete` | Required details missing for a Quote. | Prompt for `problem.missing`. | | `ship_to_invalid` | Shipping address fails country validation. | Highlight `problem.invalid` (e.g. `postalCode`). | | `bill_to_invalid` | Billing address fails country validation. | Highlight `problem.invalid`. | | `ship_to_incomplete` | Partial address where a full one is required. | Ask for the full address. | | `ship_to_unsupported` | You do not ship to this country. | Let the buyer choose another country. | | `shipping_method_unavailable` | Selected shipping method is not offered here. | Show `cart.shippingMethods` again. | | `not_shippable` | Some Lines cannot ship to this address. | Offer to remove `problem.lines`. | | `lines_unavailable` | Some Lines can no longer be purchased. | Offer to remove `problem.lines`. | | `code_invalid` | Discount code does not apply to this Cart. | Show inline at the code input. | | `quantity_invalid` | Quantity is not a positive whole number. | Correct the quantity field. | | `configuration_invalid` | Line extension value failed validation. | Map `problem.errors[].pointer` to your fields. | | `extension_invalid` | Cart extension value failed validation. | Map `errors` or fix names in `invalid`. | | `payment_method_unavailable` | Payment method is unavailable for this buyer. | Offer `quote.paymentMethods`. | | `tax_undeterminable` | No tax rule for `problem.country` and category. | Check tax setup or let buyer pick another address. | ## State conflicts | Code | Cause | What to do | | ------------------------------------------------ | --------------------------------------------------- | ----------------------------------------------------------------------- | | `cart_locked` | A Payment for this Cart is in progress. | Reopen with `openQuote()` or `resume()`. Do not start a second Payment. | | `cart_ordered` | This Cart already became an Order. | Call `commerce.continueShopping(token)`. | | `cart_not_ordered` | `continueShopping` called before the Order existed. | Keep using the current Cart. | | `cart_merged` | Buyer signed in and this Cart merged into theirs. | Continue with the Cart returned by `identify()`. | | `quote_not_current` | Cart changed after this Quote was created. | Request a new Quote. | | `preparation_unavailable`, `preparation_unknown` | Express payment approval expired or does not match. | Restart the express step. | | `payment_instrument_required` | Agent or server called `accept()` without a token. | Pass `instrument` to `accept()`. | ## Not found Resource-not-found codes follow `_not_found`: `cart_not_found`, `line_not_found`, `quote_not_found`, `order_not_found`, `payment_not_found`, `component_not_found`, `event_not_found`, `receiver_not_found`, `withdrawal_not_found` and `route_not_found`. A `cart_not_found` on a saved cookie usually means the Cart expired after 180 days of inactivity, or belongs to a signed-in buyer whose token is missing. Start a fresh Cart silently. ## Setup and credentials These indicate integration or configuration issues and should never be shown raw to shoppers. | Code | Cause | | ------------------------ | ----------------------------------------------------------------------------------------------- | | `unauthorized` | Missing `Authorization` header, or unknown key/token (`detail` says which). | | `environment_mismatch` | A `test` key sent to `live`, or a `live` key sent to `test`. | | `not_permitted` | Credential lacks access (e.g. publishable key on Admin route, or staff missing `area`/`level`). | | `not_a_member` | Staff token belongs to someone removed from staff. | | `origin_not_allowed` | Browser `Origin` is not listed in the Channel's `origins`. | | `buyer_token_invalid` | `OrbCart-Buyer` JWT is expired or from an unknown issuer. | | `buyer_token_missing` | `identify()` or a buyer's order list called without a signed-in buyer token. | | `buyer_token_unexpected` | Buyer token sent alongside a secret key. | ## Request format | Code | Cause | | -------------------------- | ------------------------------------------------------------------------------ | | `body_invalid` | Body is not JSON, exceeds 1 MB, or fails schema validation (`problem.errors`). | | `parameter_invalid` | Query parameter fails schema validation (`problem.errors`). | | `idempotency_key_required` | Operation requires an `Idempotency-Key` header. | | `idempotency_key_invalid` | `Idempotency-Key` header is malformed. | | `idempotency_key_reused` | Same key reused with a different request body. Generate a fresh key. | | `request_in_progress` | First request with this key is still running. Retry shortly. | ## Rate limits and availability Retry with the **same `Idempotency-Key`** after the `Retry-After` interval when `problem.retryable` is `true`. | Code | Cause | | ------------------------------------- | --------------------------------------------------------------------------------- | | `rate_limited` | Too many withdrawals (5/email or 20/IP per min) or gift card lookups (10/IP/min). | | `code_rate_limited` | Too many discount code attempts (10/Cart per 10 min or 30/IP per min). | | `gift_card_rate_limited` | Too many gift card attempts in checkout (10/IP per min). | | `unavailable`, `provider_unavailable` | Downstream contract or payment provider is temporarily unreachable. | | `identity_unavailable` | Identity provider JWKS or verification endpoint is temporarily unreachable. | | `invalidation_pending`, `internal` | Temporary server condition. Retry with the same key. | | `projection_unavailable` | No Postgres order list is configured (`retryable: false`). Open Orders by ID. | ## Refunds, fulfillment and webhooks | Code | Cause | | ------------------------------------ | ---------------------------------------------------------------- | | `refund_exceeds_order` | Requested more units than remain on the Order. | | `refund_exceeds_captured` | Requested more money than was captured. | | `nothing_to_refund` | Refund selection totals zero. | | `refund_changed` | Calculated amount differs from `expectedAmount`. Preview again. | | `fulfillment_exceeds_order` | More units marked shipped than ordered. | | `withdrawal_settled` | Withdrawal is already attached to an Order or resolved. | | `provider_webhook_invalid` | Malformed payload sent by payment provider. | | `provider_webhook_signature_invalid` | Webhook secret mismatch (or two Adyen webhooks sharing one URL). | | `provider_webhook_unavailable` | Temporary failure while processing a provider webhook. | ## Support and debugging Every Problem includes a `requestId`. Log the `requestId` (never the request body) to locate the exact request in the admin's **Orders** area without exposing personal data. ## Next steps | You want to | Read | | ------------------------------- | ------------------------------------------------ | | Handle errors in the client SDK | [Carts](/docs/cart/carts#handle-errors) | | Localize buyer-facing messages | [SDKs & tools](/docs/cart/sdks#buyer-facing-messages) | | Check HTTP status and OpenAPI | [HTTP API](/docs/cart/http-api) | # Express checkout Mount Apple Pay, Google Pay, PayPal and Amazon Pay express buttons in your bag or product pages. Express buttons skip the checkout form: the wallet supplies address and contact details, OrbCart quotes each change, and the buyer confirms in the sheet or on your review page. `` renders express buttons automatically for every enabled method. Use this guide to place express buttons in your bag or on product pages. ## In React Mount `` anywhere you have a `CommerceCart` and its current snapshot: ```tsx title="BagExpress.tsx" import { useNavigate } from "react-router"; import type { Cart, CommerceCart } from "@orbcart/client"; import { ExpressCheckout } from "@orbcart/react"; export function BagExpress({ cart, current }: { cart: CommerceCart; current: Cart }) { const navigate = useNavigate(); return ( navigate(`/en/checkout?preparation=${preparation}`)} onOrdered={(order) => navigate(`/orders/${order.token}`)} /> ); } ``` - **`onOrdered`:** called once when a wallet sheet completes an Order. - **`onReviewed` & `returnTo`:** required for review-mode methods (PayPal, Amazon Pay). Navigating to `/checkout?preparation=…` lets `` display the review automatically; omitting `onReviewed` hides review methods and shows only wallet sheets. - **`pending`:** pass `true` while bag mutations are in flight so wallet sheets never quote a stale total. - **`paymentOptions={{ appearance: "inherit" }}`:** inherits your checkout theme tokens. For custom markup, use `useExpressCheckout` and `ExpressButton`. ## Two express modes | Mode | Methods | Flow | | -------- | --------------------- | ---------------------------------------------------------------------------------- | | `sheet` | Apple Pay, Google Pay | Buyer selects address, shipping and card inside the wallet sheet and pays there. | | `review` | PayPal, Amazon Pay | Buyer approves at the provider, then confirms the final Quote on your review page. | `cart.paymentMethods` marks express methods with `express: "sheet" | "review"`. Methods with `expressOnly: true` (such as Amazon Pay by default) appear only as express buttons unless moved via `offer` in [Payments](/docs/cart/payments#amazon-pay). ### Required billing addresses and 3-D Secure - Channels with [`billingAddress: "required"`](/docs/cart/configuration#contactfields-and-billingaddress) enforce complete billing details on express flows too. Missing billing details return `cart_incomplete` with `bill_to` requirements so the buyer finishes on the regular checkout. - If a bank requests 3-D Secure after Apple Pay or Google Pay, OrbCart opens the challenge dialog automatically. ## Without React Mount any express button directly with `cart.mountExpress()`: ```ts const button = await cart.mountExpress("apple_pay", element, { accepted: (result) => { if (result.status === "ordered") showConfirmation(result.order.number); }, reviewed: (review) => goToReviewPage(review.preparation), failed: (error) => console.error(error), }); if (!button.available) hideWalletSection(); ``` `accepted` receives the same outcome union as [`quote.pay()`](/docs/cart/quotes#4-place-the-order). In a custom checkout built on `cart.checkout()`: - Show the review whenever `state.prepared` is present, place the order with `placeOrder({ payment: state.prepared })`, and return to the form with `leaveReview()`. - For Amazon Pay reviews, render `state.prepared.review.paymentDescriptor` verbatim and bind Amazon's hosted `mountChangeShippingAddress(el)` and `mountChangePaymentMethod(el)` controls rather than editing Amazon's address locally. - On a custom return route, call `cart.reviewPayment({ preparation, returned })` forwarding the provider query parameters (excluding `preparation`). ## Setup checklist - **HTTPS:** wallets require a secure origin (`localhost` counts as secure). - **Apple Pay:** register your domain in Stripe or PAYONE, or serve Adyen's `/.well-known/apple-developer-merchantid-domain-association` file as `text/plain`. - **Google Pay:** works out of the box in `test`; in `live`, register in Google Pay & Wallet Console (and set `PAYONE_GOOGLE_PAY_MERCHANT_ID` for PAYONE). - **Amazon Pay:** configure credentials, region/currency and HTTPS review return URLs ([Amazon Pay setup](/docs/cart/payments#amazon-pay)). - **CSP:** allow `pay.google.com`, Apple's Pay SDK, and Amazon's regional `checkout.js`. Stripe test card numbers cannot be added to Apple Pay. Use a real card in Apple Wallet against Stripe test keys: Stripe creates a test token and charges nothing. ## Customize | You want to | Do this | Default | | --------------------------------- | ----------------------------------------------------- | ------------------------- | | Match buttons to your theme | Pass `paymentOptions={{ appearance: "inherit" }}` | Provider default style | | Hide review methods in a mini bag | Omit `onReviewed` on `` | Shows all express methods | | Build custom express wrappers | Use `useExpressCheckout` and `ExpressButton` | `` | | Use express without React | Call `cart.mountExpress()` and `cart.reviewPayment()` | React kit | ## Next steps | You want to | Read | | ------------------------------------------------------ | -------------------------------------------------------- | | Configure Stripe, Adyen, PAYONE, PayPal and Amazon Pay | [Payment providers](/docs/cart/payments) | | Find sandbox test cards and accounts | [Test payments](/docs/cart/test-payments) | | Build a framework-free checkout | [A checkout without React](/docs/cart/checkout-without-react) | | Drop in the full React checkout | [React checkout](/docs/cart/react-checkout) | # Extend OrbCart Map every OrbCart extension point from configuration and contracts to events, extensions, UI slots and plugins. OrbCart has no generic lifecycle hooks like `beforeQuote`. Every extension point has a clear name and responsibility so it is always obvious which system decides a price, tax or stock count ([How it works](/docs/cart/how-it-works)). | Depth | Seam | Best for | | ----- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | 1 | [Configure](#configure) | Markets, shipping, discounts, legal texts and contact fields. | | 2 | [Contracts in your Worker](#answer-contracts-in-your-worker) | Prices, stock, tax, shipping rates, actions and ERP hand-off. | | 3 | [Contracts in another system](#answer-them-from-another-system) | Calling external services via `http()` or `service()`, or mixing Catalog + merchant offers. | | 4 | [Events](#react-to-events) | Emails, accounting and analytics via signed CloudEvents. | | 5 | [Extensions](#add-fields-of-your-own) | Typed custom fields on Lines or Carts. | | 6 | [Storefront UI](#shape-the-storefront) | CSS tokens, labels, slots, region composition or the plain TS store. | | 7 | [Packages](#package-it-for-other-shops) | Reusable plugins across shops (such as `@orbcart/plugin-dhl`). | ### Configure Most commerce rules are declarative inside `defineCommerce`: ```ts title="src/worker.ts" members="ChannelConfig" shipping: { DE: [ { id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] }, { id: "freight", title: "Freight", price: 4900, requires: ["phone"], only: ["bulky"] }, ], }, discounts: [ { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] }, ], ``` Read: [Configuration](/docs/cart/configuration) · [Shipping](/docs/cart/shipping) · [Discounts](/docs/cart/discounts) ### Answer contracts in your Worker | Contract | Purpose | When omitted | | ------------------------------ | ------------------------------------------------------------------------------- | --------------------------- | | `offers` | Prices and product facts for Cart Lines | Required | | `inventory` | Stock checks and checkout holds | Unlimited stock | | `appointments` | Bookable visits and rentals | No appointment booking | | `pickupLocations` | Authoritative Catalog pickup Locations | Required for `pickup` rules | | `tax` (Channel) | Non-EU, B2B or custom tax calculation | Built-in EU VAT | | `shippingRates` (Channel) | [Live carrier or ERP rates](/docs/cart/shipping#live-rates-from-your-carrier-or-erp) | Fixed / weight-tier rules | | `deliverOrder` / `fetchOrders` | Push or poll paid Orders to your ERP | No automatic ERP hand-off | | `identity` | Trust your shop's buyer ID tokens | Guests only | | `orderActions` | [Custom staff actions on Orders](/docs/cart/order-actions) | Built-in Order actions only | | `paymentProviders` | [Custom payment providers](/docs/cart/payment-provider) (preview) | Built-in providers | ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; export default defineCommerce({ channels, offers: (lines, { currency }) => pricing.offers(lines, { currency }), deliverOrder: async (order, { signal }) => { const salesOrder = await erp.createSalesOrder(order, { idempotencyKey: order.id, signal }); return { reference: salesOrder.number }; }, }); ``` ### Answer them from another system Point any contract at an external service with `http()` (signed RFC 9421, verified via `verifyRequest()`) or another Worker with `service()`: ```ts title="src/worker.ts" import { defineCommerce, http, service } from "@orbcart/runtime"; export default defineCommerce({ channels, offers: service("PRICES"), deliverOrder: http("https://middleware.clayandcrema.de/orders"), }); ``` Combine [OrbCatalog](/docs/catalog) offers with merchant-priced services (such as an in-store grinder calibration) using `offers: { catalog, merchant: { references, offers } }`: ```ts title="src/worker.ts" members="CommerceConfig" import { http } from "@orbcart/runtime"; offers: { catalog: http("https://catalog.clayandcrema.de/orbcart/offers"), merchant: { references: ["GRINDER-SERVICE"], offers: (lines) => lines.map((line) => ({ reference: line.reference, title: "Grinder calibration at the roastery", price: { amount: 2500, currency: "EUR" }, taxCategory: "standard", supply: { type: "b2c_work_on_movable_goods", location: { id: "loc_roastery0001", name: "Clay & Crema Roastery Munich", address: { line1: "Sendlinger Straße 12", postalCode: "80331", city: "München", country: "DE", }, }, }, })), }, }, ``` OrbCatalog remains authoritative for every SKU it knows; your merchant function applies only when OrbCatalog explicitly answers `unknown` for a configured reference, and merchant offers in this composition expire after at most 15 minutes. Read: [Remote contracts](/docs/cart/remote-contracts) · [Tax](/docs/cart/tax#work-performed-at-your-location) ### React to events Subscribe inline functions, `http()` endpoints or `service()` bindings to signed CloudEvents ([Order events](/docs/cart/order-events), [Buyer emails](/docs/cart/buyer-emails)): ```ts title="src/worker.ts" members="CommerceConfig" import { http } from "@orbcart/runtime"; events: { mails: http("https://mail.clayandcrema.de/orbcart", { types: ["order.created", "cart.abandoned"] }), ledger: { run: (event, { signal }) => accounting.book(event, { signal }), types: ["payment.*"] }, }, ``` ### Add fields of your own Declare Zod schemas on Lines or Carts ([Extensions](/docs/cart/extensions), [Gift message recipe](/docs/cart/gift-message)): ```ts title="src/commerce.ts" members="CommerceConfig" import { z } from "zod"; extensions: { engraving: { on: "line", schema: z.object({ text: z.string().trim().min(1).max(20) }) }, giftMessage: { on: "cart", schema: z.string().max(200) }, }, ``` ### Shape the storefront Customise `@orbcart/react` in layers: CSS `--orbcart-*` tokens, `labels`/`words`, component slots (`lineImage`, `paymentHelp`, `deliveryAddress`, `fields`), composed regions, `useCheckout()`, or the framework-free `cart.checkout()` store: ```tsx title="app/delivery-address.tsx" browser import { AddressFields } from "@orbcart/react"; import type { DeliveryAddressProps } from "@orbcart/react"; const store = { company: "Clay & Crema Roastery", line1: "Sendlinger Straße 12", line2: "", postalCode: "80331", city: "München", region: "", country: "DE", }; export function DeliveryAddress({ heading, onReplace, ...fields }: DeliveryAddressProps) { return ( <> {heading} ); } ``` ### Package it for other shops Plugins are ordinary npm packages filling the seams above (following `@orbcart/plugin-dhl`'s pattern: shared schemas at root, UI at `/react`, secret-holding calls at `/server`, tokens at `/styles.css`). Plugins depend only on public packages, keep secrets server-side, never override OrbCart pricing/tax decisions, and degrade cleanly when removed. ## What cannot be extended today | Requirement | Current status | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | Custom express wallets on your own payment provider | Built-in providers only ([Payment provider](/docs/cart/payment-provider)) | | Carrier-invented shipping method IDs | Declare methods on the Channel; [price them dynamically](/docs/cart/shipping#live-rates-from-your-carrier-or-erp) | | Generic `beforeQuote` / B2B approval hooks | Not supported by design | | AI agent extension values | Not over UCP; agent hands off to your storefront | | Free-shipping progress amount ("€20.10 to free shipping") | Not exposed on Cart yet | | Built-in email sending | By design external ([Buyer emails](/docs/cart/buyer-emails)) | ## Next steps | You want to | Read | | -------------------------------------- | ------------------------------- | | Copy complete working builds | [Recipes](/docs/cart/recipes) | | Check what is shipped and what is next | [Status](/docs/cart/status) | | Browse every SDK and CLI tool | [SDKs and packages](/docs/cart/sdks) | # Extensions Add typed custom fields to Carts and Lines using Zod schemas, render them in checkout, and price them in Offers. Declare typed custom fields on a Line (such as an engraving or configurator) or on the Cart (such as a gift message or delivery note). OrbCart validates values against your schema, persists them on the Quote and Order, and delivers them to your ERP. | Target | Examples | Flows into | | ------------------- | ------------------------------------- | ------------------------- | | Line (`on: "line"`) | Engraving, grind option, configurator | `offers`, Quote and Order | | Cart (`on: "cart"`) | Gift message, carrier note, VAT ID | Quote and Order | ## Declare extensions Any [Standard Schema](https://standardschema.dev) library with JSON Schema support works (such as Zod 4.2+). Names must start with a letter and contain only letters, digits and `_`: ```ts title="src/commerce.ts" import { z } from "zod"; import type { CommerceConfig } from "@orbcart/runtime"; export const commerce = { channels, offers, extensions: { engraving: { on: "line", schema: z.object({ text: z.string().trim().min(1).max(20) }) }, giftMessage: { on: "cart", schema: z.string().max(200) }, }, } satisfies CommerceConfig; ``` ```ts title="src/worker.ts" export default defineCommerce(commerce); ``` ## Set values from the storefront Pass `typeof config` to `createCommerce()` for end-to-end type safety: ```ts browser import type { commerce as config } from "../commerce/src/commerce"; const commerce = createCommerce({ url, key }); const cart = await commerce.cart(); await cart.add("HAND-GRINDER", { configuration: { engraving: { text: "Anna 2026" } } }); await cart.setExtension("giftMessage", "Happy birthday!"); await cart.removeExtension("giftMessage"); ``` Two items with the same SKU and different `configuration` values become separate Lines. ## Ask for a value at checkout Add `ask: "optional"` or `ask: "required"` to a Cart extension (with a schema `.meta({ title: "…" })` for its label) to render it automatically in ``: | Schema | Rendered control | | --------------------------- | ------------------------------------------------------------------------------- | | `z.string().max(40)` | Text input (textarea when max exceeds 100 chars) | | `z.literal(true)` / boolean | Checkbox (`required` requires ticked) | | `z.enum(["A", "B"])` | Select dropdown | | Object or complex shape | Pass a custom component via [`fields`](/docs/cart/react-checkout#fields-of-your-own) | - **`ask: "required"`** adds `extensions.` to `cart.missing` and blocks quoting (`cart_incomplete`) until answered. Apple Pay and Google Pay wait until required extensions are filled; PayPal Express collects them on the review page; UCP AI agents hand off to your storefront. - Custom checkouts inspect `cart.askedExtensions` (name + JSON Schema) and `cart.fields["extensions."]`. ## Price a Line configuration and read it on Orders Line configurations arrive in `offers` as `line.configuration`. Echo `configuration` back when pricing varies by configuration: ```ts export const offers: OffersContract = async (lines, { currency }) => lines.map((line) => { const engraved = line.configuration.engraving !== undefined; return { reference: line.reference, configuration: line.configuration, title: engraved ? "Hand Grinder · engraved" : "Hand Grinder", price: { amount: engraved ? 9400 : 8900, currency }, taxCategory: "standard", ...(engraved && { withdrawal: { excluded: "personalized" } }), }; }); ``` Cart extensions never change totals on their own. Read both on placed Orders (and in `deliverOrder`): ```ts order.quote.lines[0].configuration; // { engraving: { text: "Anna 2026" } } order.quote.extensions; // { giftMessage: "Happy birthday!" } ``` ### Labels in the admin and OpenAPI Add `.meta({ title: "…" })` to Zod schemas so staff see friendly labels in the admin: ```ts import { z } from "zod"; const Car = z .object({ firstRegistration: z.string().meta({ title: "Erstzulassung" }) }) .meta({ title: "Fahrzeug" }); ``` `GET /v1/openapi.json` publishes your `LineConfiguration` and `CartExtensions` schemas publicly (keep internal codes out of descriptions). ## Validation errors and limits | Error code | When | Problem details | | ----------------------- | ---------------------------------------- | --------------------------------------------------------------------------- | | `configuration_invalid` | `cart.add()` fails schema validation | `errors[]` with JSON `pointer` (e.g. `#/body/configuration/engraving/text`) | | `extension_invalid` | `setExtension()` fails validation | `errors[]` with `pointer: "#/body/value"` | | `extension_invalid` | `quote()` after a breaking schema deploy | `invalid` lists extensions to fix or remove | - Each JSON value is limited to **16 KiB**. - Values are treated as personal data: excluded from logs and redacted for staff without buyer-data access. ## Customize | You want to | Do this | Default | | ------------------------------------------ | ------------------------------------------------------- | --------------------------------- | | Render a field in `` | Add `ask: "optional" \| "required"` on a Cart extension | API-only via `setExtension()` | | Use a custom React input | Pass `fields={{ myField: MyField }}` to `` | Generated from JSON Schema | | Price personalised items differently | Read `line.configuration` and echo it in `offers` | Same price for all Lines of a SKU | | Exclude personalised goods from withdrawal | Return `withdrawal: { excluded: "personalized" }` | Standard withdrawal applies | ## Next steps | You want to | Read | | ---------------------------------- | --------------------------------------------------------- | | Build a complete gift-message flow | [A gift message, end to end](/docs/cart/gift-message) | | Build custom checkout controls | [React checkout](/docs/cart/react-checkout#fields-of-your-own) | | Connect prices and product rules | [Offers](/docs/cart/offers) | | Choose payment providers | [Payments](/docs/cart/payments) | # Free shipping and a welcome code Configure automatic free shipping from €50 and a WELCOME10 code, mount the code field, and prove both in Vitest. This recipe adds automatic free standard shipping from €50 and a 10% `WELCOME10` code, wires the code field into the bag, and tests both against your Worker. **Prerequisites:** a Channel with a `standard` shipping rule ([Shipping](/docs/cart/shipping)). ## 1. Declare both discounts on the Channel ```ts title="src/worker.ts" members="ChannelConfig" discounts: [ // Automatic from €50 of shipped goods; express stays paid. { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] }, { id: "welcome", code: "WELCOME10", percentage: 10 }, ], ``` `minimumSubtotal` counts only eligible shipped goods before discounts in minor units (services and downloads never count). ## 2. Let the buyer enter a code `` includes a discount code field automatically. In a custom bag, mount `` below `` (or call `cart.enterCode()` directly without React): ```tsx title="app/mini-cart.tsx" browser elements import { DiscountCode } from "@orbcart/react"; ; ``` ```ts browser await cart.enterCode("welcome10"); ``` ## 3. Prove it in a test Using `vitest.config.ts` from [Testing](/docs/cart/testing#configure-vitest-for-your-worker): ```ts title="test/discounts.test.ts" import { env, exports } from "cloudflare:workers"; import { createCommerce } from "@orbcart/client"; import { issueKey, publishDailyRates } from "@orbcart/runtime/testing"; import { beforeEach, expect, it } from "vitest"; const worker = (request: Request) => exports.default.fetch(request); const shipTo = { name: "Anna Berg", line1: "Bergstraße 12", postalCode: "10115", city: "Berlin", country: "DE", }; beforeEach(async () => { const today = new Date().toISOString().slice(0, 10); await publishDailyRates(env, { on: today, rates: { DE: { standard: "19", reduced: ["7"] } } }); }); it("ships a hand grinder for free and takes 10% off with WELCOME10", async () => { const key = await issueKey(env, { kind: "publishable", channel: "de" }); const cart = await createCommerce({ url: "https://commerce.test", key, fetch: worker }).cart(); await cart.add("HAND-GRINDER"); // €89.00, above the €50 threshold await cart.enterCode("welcome10"); const quote = await cart.quote({ shipTo, contact: { email: "anna@example.com" } }); expect(quote.discounts).toEqual( expect.arrayContaining([ expect.objectContaining({ discount: "welcome", scope: "order" }), expect.objectContaining({ discount: "free-shipping", scope: "shipping" }), ]), ); }); ``` ## Next steps | You want to | Read | | ------------------------------------------------ | ------------------------------------------------ | | Explore single-use batches, limits and ERP codes | [Discounts](/docs/cart/discounts) | | Build the header bag this field sits in | [Add to cart and a mini cart](/docs/cart/add-to-cart) | | Test a complete card purchase | [Test a purchase](/docs/cart/test-a-purchase) | # Gift cards Sell gift cards as products, issue cards manually, redeem them at checkout or a desk, and configure card terms. A gift card is a code with a balance managed by OrbCart. Cards are created either when an Order sells a gift card product or when staff issue one via the Admin API. ## Sell and redeem a gift card Mark a gift card Offer with `giftCard: true` in your `offers` contract (its price becomes the card's face value). One card is issued per unit only after the Order is paid in full, and the buyer receives one email per card with its code and printable link ([Buyer emails](/docs/cart/buyer-emails)). Buyers apply one or more gift cards at checkout and pay any remainder (`quote.toPay`) with another method: ```ts browser await cart.enterGiftCard("ABCD-EFGH-JKMP-QRST"); const quote = await cart.quote(); // quote.giftCards lists each card's share; quote.toPay is the remainder for the payment provider. await quote.pay({ payment: "gift_card" }); // when gift cards cover the full total ``` In React, `` renders the gift-card field automatically; for a custom bag, mount `` with `onEnter={bag.enterGiftCard}` and `onRemove={bag.removeGiftCard}`. Remove a card with `cart.removeGiftCard(card.id)`. ### Redemption rules and VAT - **Order and reservation:** cards apply in entry order and cannot buy other gift cards. Balances are reserved on Quote acceptance, redeemed on Order creation, and released if payment fails or is cancelled. - **No pre-approved wallets beside gift cards:** express approvals made before checkout (such as PayPal Express) are not offered alongside a gift card. - **Multi-purpose vs single-purpose VAT:** by default, a gift card is multi-purpose (no VAT on sale; VAT applies on the goods later bought). Add `singlePurpose: true` when the card only buys goods of one tax scope: VAT falls on the sale, issuance freezes `taxScope` and `taxPaid` ([Directive 2016/1065, Art. 30a(2)](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016L1065)), and the card can only pay items matching that country, category and rate. - **Refunds:** refunding an Order restores the payment provider's captured share first and credits the remainder back to the original cards. Refunding a gift card's original sale requires its full face value to be unspent (`gift_card_refund_unavailable` if used, reserved or expired). ## Redeem at a desk and issue by hand ### Desk redemption Staff with `orders:edit` (or a secret key) can redeem a multi-purpose card in person via `POST /v1/gift-cards/{id}/redemptions`, passing the amount, Location and `Idempotency-Key`. Location-scoped staff can redeem only at their assigned Locations; merchant-wide staff can redeem at any configured desk Location. Active checkout reservations stay protected. Single-purpose cards return `gift_card_desk_unavailable` and must be redeemed through checkout. ### Issue a card via the Admin API ```sh curl https://commerce.clayandcrema.de/v1/gift-cards \ -H "Authorization: Bearer sk_live_…" \ -H "Idempotency-Key: goodwill-order-4711" \ -d '{ "amount": 2500, "currency": "EUR", "reason": "Late parcel", "channel": "de" }' ``` `GET /v1/gift-cards/{id}` returns original value, remaining balance, active reservations and redemptions, showing only the last four characters of the code. Set `PUBLIC_URL` on the Worker to enable 30-day signed print links via `POST /v1/gift-cards/{id}/print` (requires merchant-wide `orders:edit` or a secret key; otherwise printing returns `gift_card_print_unavailable`). ## Configure card terms ```ts title="src/worker.ts" members="CommerceConfig" giftCards: { codeFormat: { length: 16, alphabet: "readable" }, validityYears: 3, minimum: 500, maximum: 50000, channels: ["de"], }, ``` | Option | Default | Effect | | -------------------- | -------------- | --------------------------------------------------------------------------------------- | | `codeFormat` | 16, `readable` | Length up to 24 (min 16 for `readable`, 20 for `digits`). `readable` omits `0 O 1 I L`. | | `validityYears` | `3` | Valid through the end of the issue year plus this many years. | | `minimum`, `maximum` | None | Allowed face value in minor units for both Offers and manual issuance. | | `channels` | All | Channels where buyers may redeem gift cards. | Buyers can type codes with or without hyphens, spaces or case. Code lookups are rate-limited per network ([Security](/docs/cart/security#rate-limits)). ## Events | Event | When | `data` fields | | -------------------- | ----------------------------------- | ---------------------------------------------------- | | `gift_card.issued` | Sold in an Order or issued by staff | `giftCard`, `lastFour`, `amount`, `order?` | | `gift_card.redeemed` | Applied to an Order | `giftCard`, `lastFour`, `amount`, `balance`, `order` | | `gift_card.credited` | Restored by a refund | `giftCard`, `lastFour`, `amount`, `balance`, `order` | | `gift_card.voided` | Retired by refunding its sale | `giftCard`, `lastFour`, `amount`, `balance` | Codes are never included in events. ## Customize | You want to | Do this | Default | | --------------------------------------- | ------------------------------------------------- | ----------------------------------- | | Change code length or alphabet | Set `giftCards.codeFormat` | 16-char `readable` | | Set minimum or maximum value | Set `giftCards.minimum` and `giftCards.maximum` | No bounds | | Restrict redemption to specific markets | Set `giftCards.channels` | All Channels | | Tax a gift card at sale | Set `singlePurpose: true` beside `giftCard: true` | Multi-purpose (taxed at redemption) | ## Next steps | You want to | Read | | ---------------------------------- | ---------------------------------------------- | | Send gift card emails to buyers | [Buyer emails](/docs/cart/buyer-emails) | | Subscribe to `gift_card.*` events | [Order events](/docs/cart/order-events) | | Issue Order refunds | [Orders and refunds](/docs/cart/orders-and-refunds) | | Configure Offers and product flags | [Offers](/docs/cart/offers) | # A gift message, end to end Declare a Cart giftMessage extension, collect it in checkout, and pass it to your ERP packing slip. This recipe adds an optional gift message to checkout, validates it on the server, freezes it on the Quote and Order, and forwards it to your ERP's packing slip. **Prerequisites:** a commerce Worker and a React storefront ([Add to cart and a mini cart](/docs/cart/add-to-cart)). ## 1. Declare the Cart extension ```ts title="src/commerce.ts" import type { CommerceConfig } from "@orbcart/runtime"; import { z } from "zod"; export const commerce = { channels, offers, extensions: { giftMessage: { on: "cart", ask: "optional", schema: z.string().trim().min(1).max(200).meta({ title: "Gift message" }), }, }, } satisfies CommerceConfig; ``` Pass `commerce` to `defineCommerce(commerce)` in `src/worker.ts`. Because `ask: "optional"` is set, `` renders the **Gift message** textarea automatically with no React props needed. ## 2. Forward it on `deliverOrder` Read the validated message from `order.quote.extensions` and pass it to your ERP: ```ts title="src/erp.ts" import type { DeliverOrderContract } from "@orbcart/runtime"; export const deliverOrder: DeliverOrderContract = async (order, { signal }) => { const { giftMessage } = order.quote.extensions; const salesOrder = await erp.createSalesOrder( { externalId: order.id, lines: order.quote.lines.map(({ reference, quantity }) => ({ sku: reference, quantity })), packingSlipNote: typeof giftMessage === "string" ? giftMessage : undefined, }, { idempotencyKey: order.id, signal }, ); return { reference: salesOrder.number }; }; ``` Gift messages are treated as personal data (excluded from logs and events, visible only to staff with buyer-data access). AI agents cannot set extensions and hand off to your storefront when one is required. ## Next steps | You want to | Read | | -------------------------------------------- | --------------------------------------------------------- | | Charge for Line extensions such as engraving | [Extensions](/docs/cart/extensions) | | Build a custom React input for an extension | [React checkout](/docs/cart/react-checkout#fields-of-your-own) | | Map the full Order to your ERP | [Send paid Orders to your ERP](/docs/cart/erp-order-handoff) | # How it works Trace a single purchase from cart.add to the Order in your ERP, and see how OrbCart recovers when something goes wrong. This page follows one purchase through every part of OrbCart. If a term such as Offer, Quote or Order is unfamiliar, start with [Concepts](/docs/cart/concepts). ## The moving parts | Part | Where it runs | What it owns | | ------------------- | --------------------------------------------- | ------------------------------------------------------------- | | Client SDK | Browser, app or AI agent | Nothing binding. Sends buyer intent and holds the Cart token. | | Worker | Your Cloudflare account (one per Environment) | Request validation and routing to the right Cart. | | Cart object | One Durable Object per Cart | The Cart, Quotes, Payment and Order. Single source of truth. | | Environment object | One Durable Object per Environment | API keys, Order numbers and the Quote signing key. | | Your contracts | Your code, Worker or HTTP endpoint | Prices, stock, tax and ERP hand-off ([Offers](/docs/cart/offers)). | | Payment provider | Stripe, Adyen, Mollie, PAYONE, PayPal, Amazon | Moving the money and reporting status via webhooks. | | Postgres (optional) | Your database via Hyperdrive | Read-only Order lists for the Admin API and admin UI. | ## One purchase, step by step ### The buyer adds an item `cart.add("DAYBREAK-250G-BEANS")` runs in the browser. The first call creates the Cart using the Channel's publishable key and returns a Cart token. Every later call carries that token and a fresh `Idempotency-Key`. ### The Worker validates and routes The Worker reads the `Authorization` header, checks the browser's `Origin` against the Channel's `origins`, and validates the request body. Because the Cart ID is embedded in the token, the Worker routes straight to that Cart's Durable Object. ### The Cart asks your systems The Cart calls your `offers` function for the new Line and returns the updated Cart with titles, prices, a non-binding `estimate` and a list of `missing` fields. ### The buyer requests a Quote `cart.quote()` sends the buyer's address and email. The Cart fetches binding prices from `offers`, reserves stock via `inventory` (if configured) and calculates tax using EU VAT rates or your `tax` function. The runtime signs the Quote with the Environment's key and stores it for up to 30 minutes. ### The buyer pays `quote.pay({ payment })` runs when the buyer clicks the order button. Card details travel straight from the provider's mounted field to the provider. The Cart verifies the Quote is still valid, records consent and the Payment in a single atomic write, locks the Cart, and starts the Payment with a deterministic idempotency key. ### The provider decides The outcome arrives synchronously, via a signed webhook, or when the Cart polls the provider. Whichever arrives first records the decision. If 3-D Secure is needed, the provider returns `requires_action` and the SDK handles the challenge. ### The Order is created Inside the same Cart object, OrbCart obtains the next Order number from the Environment object and writes the Order with the exact signed Quote. `pay()` resolves with `status: "ordered"`. ### Follow-up work runs reliably The same write that creates the Order enqueues follow-up jobs in the Cart's outbox: - Capture the payment and commit reserved stock - Deliver the Order to your ERP via `deliverOrder` - Update the Order list in Postgres - Send `order.created` to your [event receivers](/docs/cart/order-events) A Durable Object alarm retries each job until it succeeds. If your ERP prefers polling over push delivery, leave out `deliverOrder` and [fetch Orders directly](/docs/cart/inventory#or-let-your-erp-fetch-orders). ## When something goes wrong | Situation | What OrbCart does | What the buyer sees | | ------------------------------------- | ------------------------------------------------------------------ | --------------------------------------- | | Price, stock or shipping changed | Returns `quote_changed` with a fresh Quote. Nothing is charged. | The updated total and the order button. | | Double click, reload or second tab | Replays the existing Payment or first idempotent response. | One Payment and one Order. | | Your `offers` or `tax` contract fails | Refuses the Quote with `provider_unavailable`. Never guesses. | A prompt to try again. | | Payment provider times out | Marks Payment `unknown` and polls while waiting for webhooks. | A calm waiting screen until decided. | | Your ERP is down | Retries `deliverOrder` up to once an hour; flags `handoff_failed`. | Nothing. Their Order is already placed. | | Worker restarts mid-purchase | State is persisted before side effects; the next alarm resumes. | Nothing. | ### How unclear payments resolve When a provider times out, the Payment enters `unknown`, never `failed`. The Cart polls after 30 seconds, then 1, 2, 4, 8 and 16 minutes while also listening for the webhook. The payment window (30 minutes by default) limits how long OrbCart may start a payment. It does not prove that a bank payment expired. A method switch, cart edit or local timeout leaves the original Payment pending while OrbCart checks with the provider. If that Payment settles, the buyer gets the original Order; if it can no longer collect, the buyer may pay another way. Any gift-card share stays reserved until the Payment is captured or released. ## Where data lives - **The Cart object is the source of truth.** It holds the Cart, its Quotes, the Payment and the Order with the buyer's details. - **Postgres lists are a read copy.** The Order list behind `admin.orders.list()` and the admin UI may lag by a few seconds, and no purchase decision reads from it. `admin.orders.get()` reads directly from the Cart object. - **No cold archive yet.** A locked R2 archive of completed Orders is planned, not built yet. Today each Order lives in its Cart object. For details on personal data storage and retention, see [Security](/docs/cart/security#personal-data). ## Next steps | You want to | Read | | ----------------------------------- | ------------------------------------------------------------------ | | Review keys, tokens and trust rules | [Security](/docs/cart/security) | | Handle every outcome of `pay()` | [Quotes and orders](/docs/cart/quotes#4-place-the-order) | | Hand Orders over to your ERP | [Hand Orders to your ERP](/docs/cart/inventory#hand-orders-to-your-erp) | # HTTP API Call OrbCart directly from any language: authentication, endpoints, OpenAPI spec, idempotency and error format. The OrbCart SDKs wrap this HTTP API. Call it directly from PHP, Python, Go, Ruby or any HTTP client. All paths are relative to your environment's URL, such as `https://commerce.example.com`. ## Authentication Pass credentials as a Bearer token in the `Authorization` header. Never put keys or tokens in query strings. ```http Authorization: Bearer pk_test_... ``` | Credential | Format | Opens | | --------------- | ----------------- | ---------------------------------------------------- | | Publishable key | `pk_test_…` | Creating Carts in its Channel. Safe in browsers. | | Cart token | `cart_…_secret_…` | One Cart: read, update, quote and pay. Keep private. | | Secret key | `sk_test_…` | Full Admin API. Server only. | For signed-in buyers, send their identity JWT in a separate header beside the publishable key or Cart token: `OrbCart-Buyer: `. ## A first request Create a Cart with your publishable key: ```sh curl -X POST http://localhost:8797/v1/carts \ -H "Authorization: Bearer $ORBCART_PUBLISHABLE_KEY" \ -H "Idempotency-Key: $(openssl rand -hex 16)" ``` The response returns the Cart with its `id` and `token`. Use that token for all subsequent calls on the Cart: ```sh curl -X POST "http://localhost:8797/v1/carts/$CART_ID/lines" \ -H "Authorization: Bearer $CART_TOKEN" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $(openssl rand -hex 16)" \ -d '{"reference":"DAYBREAK-250G-BEANS","quantity":1}' ``` Every Cart mutation returns the complete, updated Cart. ## Endpoints The endpoint tables below are generated directly from OrbCart's route definitions. Download the full OpenAPI 3.2 spec at `/openapi/v1.json` to generate typed clients in any language. Your own deployed Worker also serves `/v1/openapi.json` with your declared [extensions](/docs/cart/extensions) and [Order events](/docs/cart/order-events#the-catalog) under `webhooks`. ### Storefront Authenticated with a publishable key or Cart token. | Method | Path | What it does | With | | --- | --- | --- | --- | | `POST` | `/v1/carts` | Create a Cart. `{ lines? }` | Publishable key, Publishable key | | `POST` | `/v1/carts/handoffs` | Open an agent's checkout in the buyer's browser. `{ handoff }` | Publishable key, Publishable key | | `POST` | `/v1/carts/{cart}/buyer` | Claim the Cart for the signed-in buyer. | Cart token | | `POST` | `/v1/carts/{cart}/successor` | Start the next Cart after a purchase. | Cart token, Cart token | | `GET` | `/v1/carts/{cart}` | Read a Cart. | Cart token, Cart token | | `GET` | `/v1/carts/{cart}/payment-methods/{method}/setup` | A payment method's public setup before there is a Quote. | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/payment-methods/apple_pay/session` | Apple Pay's merchant session for the page that shows its button. `{ page }` | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/lines` | Add a Line. `{ reference, quantity?, configuration? }` | Cart token, Cart token | | `PATCH` | `/v1/carts/{cart}/lines/{line}` | Set a Line's quantity. `{ quantity }` | Cart token, Cart token | | `DELETE` | `/v1/carts/{cart}/lines/{line}` | Remove a Line. | Cart token, Cart token | | `PUT` | `/v1/carts/{cart}/ship-to` | Set the delivery address. | Cart token, Cart token | | `PUT` | `/v1/carts/{cart}/bill-to` | Set a separate billing address. | Cart token, Cart token | | `DELETE` | `/v1/carts/{cart}/bill-to` | Bill to the delivery address again. | Cart token, Cart token | | `PUT` | `/v1/carts/{cart}/contact` | Set the buyer's email and phone. `{ email, phone? }` | Cart token, Cart token | | `PUT` | `/v1/carts/{cart}/shipping` | Choose a shipping method. `{ id }` | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/codes` | Enter a discount code. `{ code }` | Cart token, Cart token | | `DELETE` | `/v1/carts/{cart}/codes/{code}` | Remove a discount code. | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/gift-cards` | Apply a gift card to the cart. `{ code }` | Cart token, Cart token | | `DELETE` | `/v1/carts/{cart}/gift-cards/{card}` | Take a gift card off the cart. | Cart token, Cart token | | `PUT` | `/v1/carts/{cart}/extensions/{name}` | Set a Cart extension. `{ value }` | Cart token, Cart token | | `DELETE` | `/v1/carts/{cart}/extensions/{name}` | Remove a Cart extension. | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/quote` | Get a signed Quote. | Cart token, Cart token | | `GET` | `/v1/quotes/{quote}` | Reopen a Quote with its last payment state. | Cart token, Cart token | | `GET` | `/v1/quotes/{quote}/payment-methods/{method}/setup` | A payment method's public setup for the Quote's amount. | Cart token, Cart token | | `POST` | `/v1/quotes/{quote}/accept` | Accept the Quote and pay. `{ payment, instrument?, preparation?, returnTo? }` | Cart token, Cart token | | `POST` | `/v1/payments/{payment}/resume` | Resume a Payment after a provider redirect. `{ returned? }` | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/prepare-payment` | Prepare a payment the buyer approves at the provider first, such as PayPal. `{ payment, returnTo? }` | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/preparations/{preparation}/update` | Pass on an address or shipping method the buyer chose at the provider. `{ shipTo } or { shipping }` | Cart token, Cart token | | `POST` | `/v1/carts/{cart}/preparations/{preparation}/review` | Quote what the buyer approved at the provider. `{ returned? }` | Cart token, Cart token | | `GET` | `/v1/orders/{order}` | Read an Order by ID or number, or a buyer's own by its token. | | | `POST` | `/v1/withdrawals` | Withdraw from an Order. | Publishable key, Publishable key | | `GET` | `/v1/orders` | List Orders: a signed-in buyer's own, or all of them with filters. | Publishable key | | `GET` | `/v1/address-formats/{country}` | Postal code and region rules of a country. | Publishable key, Publishable key, Cart token, Cart token | ### Admin Authenticated with a secret key on your server. | Method | Path | What it does | | --- | --- | --- | | `GET` | `/v1/carts` | List Carts that need a person. | | `GET` | `/v1/carts/{cart}` | Read a Cart. | | `GET` | `/v1/orders/{order}` | Read an Order by ID or number, or a buyer's own by its token. | | `POST` | `/v1/orders/{order}/fulfillments` | Report shipped units. | | `POST` | `/v1/orders/{order}/cancellations` | Cancel units that have not shipped, or the whole Order. `{ lines?, reason }` | | `POST` | `/v1/orders/{order}/returns` | Record shipped units that came back. `{ lines, reason, restock }` | | `POST` | `/v1/orders/{order}/payments` | Record a payment received for an Order paid offline. `{ amount, receivedAt?, reference? }` | | `POST` | `/v1/orders/{order}/acknowledge` | Confirm your ERP took the Order. `{ reference? }` | | `GET` | `/v1/orders/{order}/appointments/{appointment}/free-times` | Read free starts for the appointment's whole visit at its Location. | | `POST` | `/v1/orders/{order}/appointments/{appointment}/move` | Move every active appointment of the visit together, once per key. `{ start, notifyBuyer }` | | `POST` | `/v1/orders/{order}/appointment-changes` | Record an immutable appointment change from the capacity authority. | | `GET` | `/v1/orders/{order}/refunds` | Refunds and what is still refundable. | | `POST` | `/v1/orders/{order}/refunds` | Refund. `{ lines?, shipping?, expectedAmount?, reason? }` | | `POST` | `/v1/orders/{order}/refunds/preview` | Calculate a refund without making it. `{ lines?, shipping?, expectedAmount?, reason? }` | | `GET` | `/v1/withdrawals` | List the withdrawals that need attention. | | `GET` | `/v1/withdrawals/{withdrawal}` | Read a withdrawal as it was received. | | `POST` | `/v1/withdrawals/{withdrawal}/attach` | Record a withdrawal on the Order it meant. `{ order }` | | `POST` | `/v1/withdrawals/{withdrawal}/handle` | Mark a withdrawal that named no Order as handled. | | `POST` | `/v1/orders/search` | Find a buyer's Orders by email, by identity, or both. | | `GET` | `/v1/orders` | List Orders: a signed-in buyer's own, or all of them with filters. | | `GET` | `/v1/events` | List the Events of Orders and of the Carts before them, newest first, with how far each receiver's delivery came. | | `POST` | `/v1/events/{event}/resend` | Send an Event again, with the same ID, to one Receiver or to all that want its type. `{ receiver? }` | | `POST` | `/v1/events/replay` | Send the Events from an instant on again, oldest first, a batch per call. `{ since, receiver?, after? }` | | `GET` | `/v1/insights/checkout` | Count where buyers get stuck: the funnel, the time a checkout takes, the friction and the payment methods of the last days. | | `GET` | `/v1/receivers` | List the Receivers of Events that the code defines, with how each stands. | | `POST` | `/v1/receivers/{receiver}/pause` | Stop deliveries to a Receiver until it is resumed. | | `POST` | `/v1/receivers/{receiver}/resume` | Resume a Receiver and deliver its backlog at once. | | `POST` | `/v1/offers/invalidate` | Void Offers by reference or tag. `{ references?, tags?, reason? }` | | `GET` | `/v1/environment` | Mode, jurisdiction and Channels. | | `PUT` | `/v1/channels/identities` | Take the identities of the channels the catalog keeps. `{ channels }` | | `GET` | `/v1/discounts` | List the discounts staff made, with their state and how often each was redeemed. | | `POST` | `/v1/discounts` | Make a discount; it applies from the next quote. | | `GET` | `/v1/discounts/{discount}` | One discount. | | `PUT` | `/v1/discounts/{discount}` | Replace a discount's rules; the next quote applies them. | | `POST` | `/v1/discounts/{discount}/pause` | Stop a discount until it is resumed. | | `POST` | `/v1/discounts/{discount}/resume` | Resume a paused discount. | | `POST` | `/v1/discounts/{discount}/end` | End a discount for good. | | `POST` | `/v1/discounts/{discount}/batches` | Generate a batch of single-use codes; the same prefix and count again answers the same batch. `{ prefix, count }` | | `GET` | `/v1/discounts/{discount}/batches/{prefix}` | A batch's codes, each with whether it was redeemed: what the CSV export lists. | | `GET` | `/v1/discounts/{discount}/redemptions` | The orders that redeemed a discount, the latest first. | | `GET` | `/v1/gift-cards/access` | Where the caller may redeem gift cards, and whether they work merchant-wide. | | `POST` | `/v1/gift-cards` | Make a gift card with a value, such as a goodwill gesture; the same Idempotency-Key again answers the same card. `{ amount, currency, reason, channel? }` | | `GET` | `/v1/gift-cards` | List the gift cards made in the last 30 days, newest first. | | `POST` | `/v1/gift-cards/lookup` | Find a gift card by the code a customer holds out, at the desk of any Location; a few tries a minute per address. `{ code }` | | `GET` | `/v1/gift-cards/{card}` | A gift card's standing, without its code. | | `GET` | `/v1/gift-cards/{card}/history` | What moved on a gift card, oldest first: its value, each payout with its order or Location, refunds and what was retired. | | `POST` | `/v1/gift-cards/{card}/redemptions` | Pay out value of a gift card at the desk of a Location; the same Idempotency-Key again answers the same payout. `{ code, amount, location, note? }` | | `GET` | `/v1/gift-cards/{card}/delivery` | What a mail about a gift card needs: its code and the link to print it from. | | `POST` | `/v1/gift-cards/{card}/print` | Make a fresh link to the gift card's printable page. | | `GET` | `/v1/address-formats/{country}` | Postal code and region rules of a country. | ## Public endpoints | Method | Path | Purpose | | ------ | ------------------------ | ------------------------------------------------------------ | | `GET` | `/.well-known/jwks.json` | Public keys to [verify Quotes](/docs/cart/quotes#verify-a-quote). | | `GET` | `/.well-known/ucp` | Your UCP profile for [AI agents](/docs/cart/agents). | | `POST` | `/webhooks/{provider}` | Webhooks from `stripe`, `adyen`, `mollie` and `paypal`. | ## Express payment preparations Express methods such as PayPal and Amazon Pay collect the buyer's address and payment approval before you accept a Quote. All preparation routes require the Cart token and an `Idempotency-Key`. 1. **Prepare:** Call `POST /v1/carts/{cart}/prepare-payment` with `{ "payment": "amazon_pay", "returnTo": "https://shop.example/checkout" }`. For Amazon Pay, pass the returned signed `sdk` payload (`payloadJSON`, `signature`, `algorithm`) directly to `button.initCheckout()` without reserializing it. PayPal returns `providerReference`. 2. **Review:** When the provider redirects back (for Amazon Pay, with `?preparation=…&amazonCheckoutSessionId=…`), call `POST /v1/carts/{cart}/preparations/{preparation}/review` with `{ "returned": { "amazonCheckoutSessionId": "…" } }` (or `{}` if no return fields exist). OrbCart verifies the session and returns the review Quote plus `preparation.sdk`. Keep the shipping address read-only and offer the provider's hosted change actions. 3. **Accept and resume:** Once the buyer confirms, accept the Quote with `{ "payment": "amazon_pay", "preparation": "…" }`, follow the redirect, and call `POST /v1/payments/{payment}/resume` with `{ "returned": { "amazonCheckoutSessionId": "…" } }`. Amazon Pay sets `preparationRequired: true` (never submit it without a reviewed preparation) and uses durable server polling rather than SNS/IPN webhooks. See [Amazon Pay setup](/docs/cart/payments#amazon-pay) for full sandbox details. ## Retries and idempotency Send an `Idempotency-Key` header on every mutating request. After a network timeout, repeat the **exact same request with the same key**: OrbCart replays the original response instead of running the operation twice. Use a new key for each new operation. Accepting a Quote, issuing refunds and preparing express payments **require** an `Idempotency-Key`. Keys remain valid for 24 hours. For 24 hours, replaying the `Idempotency-Key` from `POST /v1/carts` returns that Cart's token. Treat it as privately as the token itself. ## Errors Failed requests return [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457) (`application/problem+json`): ```json { "status": 422, "code": "cart_incomplete", "kind": "invalid", "retryable": false, "requestId": "req_01J...", "detail": "The cart still lacks ship_to, email.", "missing": ["ship_to", "email"] } ``` Branch on `code`, never on `detail` (`detail` is English developer context). See [Errors](/docs/cart/errors) for every code. ## Versioning `/v1` is strictly additive: new fields and enum values may be added at any time, while existing ones keep their meaning. Ignore unknown response fields and handle unknown values gracefully in open lists such as `changes`, `missing` and `code`. ## Next steps | You want to | Read | | --------------------------- | -------------------------- | | Look up an error code | [Errors](/docs/cart/errors) | | Use the TypeScript SDKs | [SDKs & tools](/docs/cart/sdks) | | Review keys and trust rules | [Security](/docs/cart/security) | # Signed-in buyers Connect Better Auth, Auth0, Clerk, Keycloak or @orbcommerce/auth/shopper so buyers share one Cart across devices. OrbCart keeps no user accounts or passwords. It verifies ID tokens from your identity provider and records only the buyer's `issuer` and `subject`, giving signed-in buyers one Cart across devices, customer-group pricing and a unified Order history (including earlier guest Orders with the same verified email). ## 1. Trust your identity issuer Configure `identity.issuers` in your commerce Worker. OrbCart discovers keys via OpenID Discovery, or you can specify `jwks` explicitly: ```ts title="src/worker.ts" worker export default defineCommerce({ channels, offers, identity: { issuers: [{ issuer: "https://auth.clayandcrema.de", audience: "shop" }], }, }); ``` ```ts worker value="Issuer" { issuer: "https://clayandcrema.de", audience: "shop", jwks: "https://clayandcrema.de/api/auth/jwks" } ``` ## 2. Pass the buyer token and claim the Cart Supply a `buyer` callback to `createCommerce()`. If OrbCart rejects an expired token, it calls `buyer({ refused })` once to retry with a refreshed token: ```ts const commerce = createCommerce({ url, key, buyer: (asked) => auth.getIdToken({ forceRefresh: asked?.refused !== undefined }), }); ``` Immediately after sign-in, call `cart.identify()` to attach or merge the guest Cart into the buyer's Cart, and persist the returned token: ```ts const { access, merged } = await cart.identify(); saveCartToken(access.token); if (merged) showToast("We added the items from your other device."); ``` Signing out ends access to the buyer's Cart on that device; the next `add()` starts a fresh guest Cart. ## Buyer Orders and customer-group pricing ### List the signed-in buyer's Orders ```ts const page = await commerce.orders(); const older = page.next ? await commerce.orders({ after: page.next }) : undefined; ``` ### Price by customer group ```ts worker export const offers: OffersContract = async (lines, { buyer, currency }) => { const group = buyer ? await crm.groupOf(buyer.subject) : "retail"; return pricing.offers(lines, { group, currency }); }; ``` ## Sign-in inside `` Use `betterAuthIdentity()` from `@orbcart/client/better-auth` (requires Better Auth's `emailOTP`, `jwt` and optionally `emailAndPassword` plugins) to offer inline sign-in when checkout recognises an email: ```tsx import { betterAuthIdentity } from "@orbcart/client/better-auth"; const identity = betterAuthIdentity({ client: authClient, knows: (email) => fetch("/api/has-account", { method: "POST", body: email }).then((r) => r.json()), }); const commerce = createCommerce({ url, key, buyer: identity.buyer }); setCart(access)} />; ``` Rate-limit your `knows` endpoint and protect it with a bot check such as Turnstile. ### Built-in shopper auth (`@orbcommerce/auth/shopper`) `shopperAuth` from `@orbcommerce/auth/shopper` bundles password sign-in (min 8 chars), email OTP sign-in and password reset (`sendCode` receives `purpose`: `"sign-in"`, `"confirm-address"` or `"reset-password"`): - Requires a Cloudflare rate-limit binding (`attempts`) per route and IPv6 `/64` (never storing raw addresses); reuse `withinAttempts(request, env.SIGN_IN_LIMITER)` on your `knows` route. - Sign-up responses are indistinguishable for new vs existing addresses (no account enumeration). - OrbCart links earlier guest Orders only for verified emails (via OTP code or `confirmAddress: true`). ## Customize | You want to | Do this | Default | | -------------------------------------------- | ----------------------------------------------------- | ---------------------------------- | | Trust multiple identity providers | Add entries to `identity.issuers` | Single issuer | | Use a custom JWKS URL without OIDC discovery | Pass `jwks` on the issuer entry | `.well-known/openid-configuration` | | Force token refresh after expiry | Check `asked?.refused` in `createCommerce({ buyer })` | Single attempt | ## Next steps | You want to | Read | | ------------------------------------- | -------------------------------------------- | | Persist Cart tokens across reloads | [Carts](/docs/cart/carts) | | Price Offers per customer group | [Offers](/docs/cart/offers) | | Search buyer Orders from your backend | [Orders & refunds](/docs/cart/orders-and-refunds) | | Configure per-buyer discount limits | [Discounts](/docs/cart/discounts) | # OrbCart OrbCart runs the purchase, from Cart to Order, and asks your systems for prices and stock. What it does, what it leaves to you and where to start. OrbCart is the transaction layer of a shop: Cart, checkout, tax, shipping, payment and Order. It has no catalog. Your products, prices and stock stay in the systems that own them, and OrbCart asks those systems whenever a buyer needs a binding answer. A complete purchase is four calls. `shipTo` is the buyer's address and `payment` is the card field mounted on your page: ```ts import { createCommerce } from "@orbcart/client"; const commerce = createCommerce({ url: "http://localhost:8797", key: "pk_test_..." }); const cart = await commerce.cart(); await cart.add("DAYBREAK-250G-BEANS"); const quote = await cart.quote({ shipTo, contact: { email: "anna@example.com" } }); const result = await quote.pay({ payment }); ``` When payment succeeds, `result.status` is `"ordered"`. The [quickstart](/docs/get-started/orbcart) runs these lines against the local demo shop in minutes. ## What OrbCart does - **Signs the price.** The buyer pays the exact [Quote](/docs/cart/concepts#quote) they agreed to, or sees the updated price first. Quotes expire after at most 30 minutes. - **Takes the payment.** Stripe, Adyen, Mollie, PAYONE, PayPal and Amazon Pay sit behind one configuration, with [express checkout](/docs/cart/express-checkout). A provider timeout becomes `unknown` and is resolved by polling, never a double charge. - **Calculates shipping, tax and discounts.** Per-country [shipping](/docs/cart/shipping) rules, EU VAT for all 27 member states, [discounts](/docs/cart/discounts) and gift cards. - **Hands over the Order.** Your ERP receives every paid Order [exactly once](/docs/cart/erp-order-handoff), and your systems receive signed [Order events](/docs/cart/order-events). - **Serves AI agents through the same door.** An [agent](/docs/cart/agents) buys for a shopper over UCP, under the exact rules of your storefront. ## What OrbCart leaves to you | OrbCart does not | Who handles it | | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | Hold products, prices or stock | Your systems via the [offers contract](/docs/cart/offers), or OrbCatalog. | | Render your storefront | Your frontend, in any framework. Includes a [React checkout](/docs/cart/react-checkout) and [order page](/docs/cart/order-page). | | Send buyer emails | Your mail system. OrbCart tells you [which email is due](/docs/cart/buyer-emails). | | Host the runtime for you | You run it as a Worker in your own Cloudflare account. See [Deployment](/docs/run/deployment). | Read [What makes OrbCart different](/docs/cart/why-orbcart) to see how this compares with shop platforms, headless suites and custom builds. ## Change what you need Everything in OrbCart adapts at one of three levels, from shallow to deep. [Extend OrbCart](/docs/cart/extend) maps every extension point. | Depth | You | Example | | --------- | ---------------------------------------------------------- | ------------------------------------------------------------- | | Configure | Set values per market in a [Channel](/docs/cart/configuration). | Shipping rules, discounts, legal texts, payment methods. | | Compose | Arrange and style the checkout components. | [A multi-step checkout](/docs/cart/checkout-steps). | | Replace | Answer a contract with your own code. | [Prices and stock from your ERP](/docs/cart/erp-prices-and-stock). | ## With OrbCatalog OrbCart works completely on its own. If you also run OrbCatalog, the catalog answers the offers and inventory contracts for you with zero custom code in your Worker. See [Connect the products](/docs/run/connect-the-products). ## Next steps | You want to | Read | | ----------------------------------- | ------------------------------------------------------------------- | | Run a test purchase locally | [OrbCart quickstart](/docs/get-started/orbcart) | | Understand the core model | [Concepts](/docs/cart/concepts), then [How it works](/docs/cart/how-it-works) | | Build the storefront side | [Carts](/docs/cart/carts) | | Connect your ERP or pricing service | [Offers](/docs/cart/offers) | | Copy a complete example | [Recipes](/docs/cart/recipes) | | Check what works today | [Project status](/docs/cart/status) | # Stock & ERP hand-off Check availability, reserve stock during checkout, and deliver or let your ERP fetch paid Orders. Both `inventory` and `deliverOrder` are optional. Without `inventory`, stock never limits a purchase; without `deliverOrder`, enable `fetchOrders: true` so your ERP polls Orders on its own schedule. ## Check stock Implement `inventory.check` to return available units per reference during quoting (omitted references are treated as unlimited, such as digital goods): ```ts title="src/worker.ts" export default defineCommerce({ channels, offers, inventory: { check: async (references, { signal }) => { const stock = await erp.stock( references.map((r) => r.reference), { signal }, ); return stock.map((item) => ({ reference: item.sku, available: item.quantity })); }, }, }); ``` | Available | Buyer experience | | ---------- | ----------------------------------------------------------------------- | | Enough | Quote takes full quantity. | | Partial | `cart.changes` reports `quantity_changed`; Quote takes available units. | | None (`0`) | `cart.changes` reports `unavailable` (`sold_out`); Line is excluded. | ## Reserve stock during checkout To prevent overselling the last unit when two buyers pay at once, implement all four hold hooks together (`reserve`, `release`, `commit`, `restock`): ```ts members="CommerceConfig" inventory: { check: (references) => erp.stock(references), reserve: (hold) => erp.reserve(hold), release: (holdId) => erp.release(holdId), commit: (holdId, orderId) => erp.commit(holdId, orderId), restock: (restock) => erp.restock(restock), }, ``` | Hook | Trigger | Contract | | --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `reserve` | Quote created | Hold `hold.references` until `hold.expiresAt` (idempotent per `hold.id`; later `expiresAt` extends the hold). | | `release` | Hold expires or Order cancelled before commit | Free `holdId` (idempotent). | | `commit` | Order placed | Convert `holdId` into a permanent booking for `orderId`. | | `restock` | Booked units cancelled or returned | Return `restock.references` to stock once per `restock.id`. | While stock is held, `quote.hold.expiresAt` is set on the Quote. ## Hand Orders to your ERP Attach `deliverOrder` to push every paid Order to your ERP (30-second timeout per attempt, retried with exponential backoff up to hourly): ```ts members="CommerceConfig" deliverOrder: async (order, { signal }) => { const salesOrder = await erp.createSalesOrder(order, { signal }); return { reference: salesOrder.number }; }, ``` - **Deduplicate by `order.id`:** delivery is at-least-once; your ERP must return the existing sales order on retries. - **Non-blocking for buyers:** buyers see their confirmation immediately after payment without waiting for ERP hand-off. ### Order snapshot fields ```ts order.number; // "CC-2026-004711" order.contact.email; order.quote.lines; // reference, quantity, configuration, offer, totals, taxes order.quote.shipTo; order.quote.shipping; order.quote.totals; order.quote.extensions; order.payment; // method, provider, reference ``` ## Or let your ERP fetch Orders When your ERP polls instead of accepting pushes, omit `deliverOrder` and set `fetchOrders: true`: ```ts export default defineCommerce({ channels, offers, fetchOrders: true, }); ``` Poll `handoff: ["pending"]` with the [Admin SDK](/docs/cart/orders-and-refunds), verify current state via `get()`, create the sales order keyed by `order.id`, and acknowledge it: ```ts let page = await admin.orders.list({ handoff: ["pending"] }); while (true) { for (const summary of page.data) { const order = await admin.orders.get(summary.id); if (order.handoff === "delivered") continue; const salesOrder = await erp.createSalesOrder(order); await admin.orders.acknowledge(order.id, { reference: salesOrder.number }); } if (!page.next) break; page = await admin.orders.list({ handoff: ["pending"], after: page.next }); } ``` Because `list()` reads a fast eventually consistent index, always check `order.handoff` on `get()`. Acknowledging twice is a no-op and keeps the first `reference`. Unlike `deliverOrder` (which flags `handoff_failed` after 30 minutes), pending orders under `fetchOrders: true` never time out. Report shipments back with [`admin.orders.fulfill()`](/docs/cart/orders-and-refunds#report-shipments). ## Customize | You want to | Do this | Default | | -------------------------------- | --------------------------------------------------------------- | ----------------------- | | Call an external ERP over HTTP | Wrap `inventory` or `deliverOrder` with `http()` or `service()` | Inline function | | Poll instead of receiving pushes | Set `fetchOrders: true` and omit `deliverOrder` | Push via `deliverOrder` | | Adjust `deliverOrder` timeout | Pass `{ run, timeoutMs }` in `defineCommerce` | `30000` ms | ## Next steps | You want to | Read | | ----------------------------------------------- | ------------------------------------------------------------ | | Build `offers` and `inventory` over signed HTTP | [Prices and stock from your ERP](/docs/cart/erp-prices-and-stock) | | Copy a complete ERP order hand-off recipe | [Send paid Orders to your ERP](/docs/cart/erp-order-handoff) | | Verify signed HTTP contract calls | [Remote contracts](/docs/cart/remote-contracts) | | Configure EU VAT and tax rules | [Tax](/docs/cart/tax) | # Offers Supply product prices, tax categories, weights, deposits and sale tags to OrbCart from your ERP or catalog. OrbCart stores no product database. Whenever it needs current prices or product facts, it calls your `offers` contract with the Cart's Lines and context. ## The smallest `offers` function ```ts title="src/offers.ts" import type { OffersContract } from "@orbcart/runtime"; export const offers: OffersContract = async (lines, { currency }) => lines.map((line) => ({ reference: line.reference, title: "Daybreak · 250 g · Whole bean", price: { amount: 1290, currency }, taxCategory: "standard", shipping: { weightInGrams: 270 }, })); ``` In production, batch all requested references into one call to your ERP or pricing service rather than fetching one Line at a time: ```ts title="src/offers.ts" export const offers: OffersContract = async (lines, { currency, signal }) => { const references = [...new Set(lines.map((line) => line.reference))]; const products = await erp.products(references, { currency, signal }); return products.map((product) => ({ reference: product.sku, title: product.name, price: { amount: product.priceInCents, currency }, taxCategory: product.vatClass, shipping: { weightInGrams: product.weight }, })); }; ``` Any omitted reference is treated as unavailable; you can also return an explicit reason: ```ts value="UnavailableReference" { reference: "GUJI-250G-BEANS", unavailable: "discontinued" } ``` ### Rules that keep buyers safe - Return the **unit price** in integer minor units (`1290` EUR = €12.90); OrbCart handles quantity, discounts and tax. - Let errors throw when your ERP is unreachable (returning `[]` would falsely mark every item sold out). - Never invent a fallback price for unknown references. ## Context passed in | Field | Example | Use it for | | ---------- | ----------------------- | ---------------------------------------------------------------- | | `currency` | `"EUR"` | Price list currency. | | `channel` | `"de"` | Market-specific assortments. | | `country` | `"AT"` | Country-specific pricing once known. | | `buyer` | `{ issuer, subject }` | Customer-group pricing for [signed-in buyers](/docs/cart/identity). | | `codes` | `["VIP20"]` | Promo codes redeemed by your ERP ([Discounts](/docs/cart/discounts)). | | `purpose` | `"display"` / `"quote"` | `"quote"` is the binding calculation before payment. | | `cartId` | `"cart_01J..."` | Cart-scoped pricing or tracing. | | `signal` | `AbortSignal` | Forward to `fetch` (aborts after 3 seconds by default). | `offers` runs when Lines change (`purpose: "display"`) and when quoting (`purpose: "quote"`). Quoted Offers are reused while still valid (15 minutes by default). ## Offer fields | Field | Required | Purpose | | ---------------------------- | -------- | ----------------------------------------------------------------------------------- | | `reference` | Yes | SKU or product identifier. | | `title` | Yes | Variant title shown in Cart, Quote and Order. | | `price` | Yes | Unit price `{ amount, currency }` (gross or net per Channel). | | `taxCategory` | Yes | `"standard"`, `"reduced"`, etc. ([Tax categories](/docs/cart/tax#tax-categories)). | | `shipping` | No | `{ weightInGrams, restrictions? }`; omit for digital goods or services. | | `image` | No | Absolute `http(s)` thumbnail URL (max 400 px, ~5–15 KB WebP). | | `url` | No | Absolute `http(s)` link back to the product page. | | `deliveryTime` | No | Standalone text for slower items (e.g. `"Ships in 3 weeks"`). | | `compareAt` / `promotion` | No | Pre-sale strike-through price and promo label for display. | | `unitPrice` | No | `{ price, per }` (`kg`, `100g`, `l`, `100ml`, `m`, `m2`) for goods sold by measure. | | `deposit` | No | Refundable per-unit deposit `{ price, taxCategory }` (see below). | | `tags` | No | Tags for discounts and early [invalidation](#end-a-sale-early). | | `limits` | No | `{ min, max }` units allowed per Line. | | `expiresAt` | No | RFC 3339 validity timestamp (default: 15 minutes). | | `components` | No | Bundle parts so individual components can be refunded. | | `withdrawal` | No | `{ excluded: "personalized" }` for items excluded from statutory withdrawal. | | `supply` | No | `{ type: "b2c_work_on_movable_goods", location }` for on-site workshop services. | | `giftCard` / `singlePurpose` | No | Marks a gift card Offer ([Gift cards](/docs/cart/gift-cards)). | | `attributes` | No | Flat key-value display text under the Line title (e.g. `{ Grind: "Whole bean" }`). | | `appliedCodes` | No | Promo codes redeemed by your ERP for this Line. | ### Say when goods take longer ```ts value="Partial" { reference: "HAND-GRINDER", /* … */ deliveryTime: "Ships in 3 weeks" } ``` ```ts value="Partial" { reference: "DAYBREAK-250G-BEANS", /* … */ image: "https://cdn.clayandcrema.de/daybreak-400.webp" } ``` If `deliveryTime` changes before order placement, the Quote reports `line_delivery_time_changed` and asks the buyer again. ### Charge a refundable deposit separately For bottle or crate deposits (such as `COLD-BREW-6X330` with a €0.90 deposit), send `deposit: { price: { amount: 90, currency: "EUR" }, taxCategory: "zero" }` (choose the tax category required by your jurisdiction). - `price`, `compareAt` and `unitPrice` must **exclude** the deposit ([PAngV §7](https://www.gesetze-im-internet.de/pangv_2022/__7.html)). - OrbCart multiplies the deposit by quantity, excludes it from discounts and shipping-tax allocation, taxes it separately, and includes it once in `totals.total` (while exposing `line.deposit` and `totals.deposit` separately). - Return only the deposit via the [deposit refund target](/docs/cart/orders-and-refunds#refund-a-deposit). ### Name what sets a Line apart Put buyer-facing variant labels in `attributes` (`{ Roast: "Medium", Grind: "Whole bean" }`) and structured custom inputs in Line `configuration` ([Extensions](/docs/cart/extensions)). Storefronts show `attributes` under the Line title; the admin displays both `attributes` and formatted `configuration`. ## Combine OrbCatalog with merchant-priced services When using [OrbCatalog](/docs/catalog), OrbCatalog's signed offers answer for catalog SKUs directly. To also price non-catalog services (such as a workshop fitting) in the same Cart, compose both: `offers: { catalog, merchant: { references, offers } }` - Your merchant function receives only its configured `references` and applies only when OrbCatalog explicitly answers `unknown` for that reference. - If both claim the same reference, the Line fails with `answer_invalid` until the conflict is resolved. - Merchant offers in this composition expire after at most 15 minutes. ## End a sale early Tag sale Offers and invalidate them from your backend when the promotion ends. Open Carts re-fetch `offers`, active checkouts see `quote_changed`, and placed Orders keep their frozen price: ```ts await admin.offers.invalidate({ tags: ["summer-sale"] }); ``` ## Customize | You want to | Do this | Default | | ----------------------------------------- | ------------------------------------------------------------------------------ | ---------------------- | | Adjust Offer cache lifetime | Return `expiresAt` per Offer | 15 minutes | | Host `offers` in another service | Wrap with `http()` or `service()` ([Remote contracts](/docs/cart/remote-contracts)) | Inline function | | Increase the 3-second budget | Pass `{ run, timeoutMs }` in `defineCommerce` | `3000` ms | | Mix OrbCatalog goods with custom services | Use `offers: { catalog, merchant: { references, offers } }` | Single `offers` source | ## Next steps | You want to | Read | | -------------------------------------------------- | ------------------------------------------------------------ | | Check stock, hold reservations and hand off Orders | [Stock & ERP hand-off](/docs/cart/inventory) | | Build `offers` and `inventory` over HTTP | [Prices and stock from your ERP](/docs/cart/erp-prices-and-stock) | | Configure EU VAT and custom tax contracts | [Tax](/docs/cart/tax) | | Price Line extensions such as engraving | [Extensions](/docs/cart/extensions) | # Run your own actions on an Order Add custom staff actions such as parcel labels to the Order menu with typed dialogs, idempotent execution and timeline entries. Order actions add merchant-specific operations (such as generating a carrier parcel label) to an Order's menu in the admin. OrbCart manages eligibility, input dialogs, idempotency keys, locking and the Order timeline; your code performs the work. ## 1. Declare the action and its `run` handler ```ts title="src/parcel-label.ts" import type { OrderAction } from "@orbcart/runtime"; import { makeLabel } from "./make-label"; export const parcelLabel: OrderAction = { label: "Parcel label", offered: (order) => order.units.some((unit) => unit.open > 0), run: makeLabel, }; ``` ```ts title="src/make-label.ts" import type { OrderActionContract } from "@orbcart/runtime"; export const makeLabel: OrderActionContract = async (order, { key, signal }) => { const label = await carrier.createLabel( { reference: order.number, shipTo: order.quote.shipTo }, { idempotencyKey: key, signal }, ); if (label.status === "address_rejected") { return { outcome: "refused", reason: "The carrier rejected this address. Correct it with the customer, then try again.", }; } return { outcome: "done", open: label.pdf, reference: label.parcelNumber }; }; ``` Attach it in `defineCommerce` (menu items appear in the order declared): ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { parcelLabel } from "./parcel-label"; export * from "@orbcart/runtime/objects"; export default defineCommerce({ channels, offers, orderActions: { parcelLabel } }); ``` ### Outcomes and idempotency - **`done`:** recorded in the Order timeline with `reference` and an **Open** button for `open` (URL). - **`refused`:** changes nothing and shows `reason` to staff. - **Throw or timeout (default 10s):** recorded as **unknown** with a **Try again** button that resends the exact same `key` (and `input`). Store `key → result` in your own system if your carrier's idempotency window is short. - While a run is in flight, OrbCart blocks concurrent runs of the same action on that Order. Only staff with `orders:edit` can trigger actions (`orders:view` reads history only). ## 2. Prompt staff for typed `input` Declare up to 20 `input` fields to open a localised dialog before running the action: ```ts title="src/parcel-label.ts" import type { OrderAction } from "@orbcart/runtime"; import { makeLabel } from "./make-label"; export const parcelLabel: OrderAction = { label: "Parcel label", input: { product: { kind: "choice", label: { en: "Product", de: "Produkt" }, required: true, choices: [ { value: "paket", label: { en: "Parcel", de: "Paket" } }, { value: "kleinpaket", label: { en: "Small parcel", de: "Kleinpaket" } }, ], }, weight: { kind: "number", label: { en: "Weight", de: "Gewicht" }, unit: "kg", required: true, default: (order) => order.units.reduce((sum, unit) => sum + unit.open, 0) * 1.5, }, bulky: { kind: "yesNo", label: { en: "Bulky goods", de: "Sperrgut" } }, }, offered: (order) => order.units.some((unit) => unit.open > 0), run: makeLabel, }; ``` | `kind` | Admin control | Value passed to `run` | | ---------- | ----------------------------------------------- | -------------------------- | | `text` | Single-line input (`maxLength`) | `string` | | `number` | Number input with optional `unit`, `min`, `max` | `number` | | `date` | Date picker | `"2026-11-14"` | | `dateTime` | Date and time picker | `"2026-11-14T14:30"` | | `choice` | Dropdown from `choices` | Selected `value` | | `yesNo` | Toggle switch | `boolean` (always present) | Read validated values from `context.input` (or `POST /v1/orders/:order/actions/:action` over HTTP): ```ts title="src/make-label.ts" import type { OrderActionContract } from "@orbcart/runtime"; export const makeLabel: OrderActionContract = async (order, { key, input, signal }) => { const label = await carrier.createLabel( { reference: order.number, shipTo: order.quote.shipTo, product: input["product"], weightKg: input["weight"], bulky: input["bulky"], }, { idempotencyKey: key, signal }, ); if (label.status === "address_rejected") { return { outcome: "refused", reason: "The carrier does not know this address." }; } return { outcome: "done", open: label.pdf, reference: label.parcelNumber }; }; ``` ## 3. Run the action in a remote service Keep `offered` synchronous in the Worker and point `run` to an HTTP endpoint (verified via `verifyRequest()`): ```ts title="src/order-actions.ts" import { http } from "@orbcart/runtime"; import { parcelLabel } from "./parcel-label"; export const orderActions = { parcelLabel: { label: "Parcel label", offered: parcelLabel.offered, run: http("https://middleware.clayandcrema.de/labels", { timeoutMs: 20_000 }), }, }; ``` ## Customize | You want to | Do this | Default | | ------------------------------------- | ---------------------------------------------------- | ---------------------- | | Pre-fill dialog fields from the Order | Add a `default: (order) => …` function on each field | Empty field | | Localise dialog labels | Pass `{ en: "…", de: "…" }` on `label` and `choices` | English fallback | | Delegate execution to your ERP | Use `http()` or `service()` for `run` | Inline Worker function | ## Next steps | You want to | Read | | ------------------------------------------- | ----------------------------------------------------- | | Read Orders, report shipments and refund | [Orders & refunds](/docs/cart/orders-and-refunds) | | Verify signed HTTP contract calls | [Contracts in another system](/docs/cart/remote-contracts) | | Understand Order events (actions emit none) | [Order events](/docs/cart/order-events) | | Explore all extension points | [Extend OrbCart](/docs/cart/extend) | # Order events Subscribe to signed CloudEvents for Orders, Payments, Carts, Withdrawals and Gift cards, or poll them via the Admin SDK. OrbCart emits CloudEvents 1.0 messages for every lifecycle transition. Attach inline functions, HTTP receivers (`http()`) or Service Bindings (`service()`) under `events`, or poll events through `@orbcart/admin`. ## Receive events ```ts title="src/worker.ts" export default defineCommerce({ channels, offers, events: { mails: async (event) => { await mailQueue.add(event.id, event); }, ledger: { run: (event, { signal }) => accounting.book(event, { signal }), types: ["payment.captured", "payment.refunded"], timeoutMs: 5_000, // default and maximum: 10 seconds }, }, }); ``` Keep receiver names stable across deployments. `types` filters by exact type or prefix (`order.*`); omit `types` to receive all events. ### Receive events over HTTP ```ts title="src/worker.ts" import { defineCommerce, http, service } from "@orbcart/runtime"; export default defineCommerce({ channels, offers, events: { erp: http((vars) => vars.get("MIDDLEWARE_URL"), { types: ["order.*", "payment.*"] }), audit: http("https://audit.clayandcrema.de/events", { previews: true, timeoutMs: 5_000 }), mails: service("MAILER", { types: ["order.created"] }), }, }); ``` - HTTP targets must use `https` on port `443` with a public hostname (under `wrangler dev`, `http` and `localhost` work too). Preview environments skip HTTP receivers unless `previews: true`. - Acknowledge with any `2xx` within **10 seconds** (redirects are never followed). Return `429` or `503` with `Retry-After` (up to 1 hour) to slow delivery, or `410 Gone` to pause the receiver. - Service Bindings receive unsigned `POST /events` requests directly inside your Cloudflare account. ### Verify a delivery Every HTTP delivery is signed with RFC 9421 (`ecdsa-p256-sha256`, `tag="orbcommerce-event"`) using keys at `/.well-known/jwks.json`: ```ts title="middleware/events.ts" import { verifyEvent } from "@orbcart/admin"; export async function handle(request: Request): Promise { const event = await verifyEvent(request, { url: "https://commerce.clayandcrema.de" }); if (event.type === "order.created") { await erp.register(event.subject, { idempotencyKey: event.id }); } return new Response(null, { status: 204 }); } ``` Invalid deliveries throw `EventVerificationError` (`signature_missing`, `wrong_purpose`, `unsupported_algorithm`, `missing_component`, `outside_window`, `digest_mismatch`, `body_too_large`, `unknown_key`, `keys_unavailable`, `signature_invalid`, `event_invalid`). Respond with `4xx` (or `503` for `keys_unavailable`). ## Event envelope and privacy ```json { "specversion": "1.0", "id": "evt_01J8Z3W6Q4XB7N2M5K9RTV0HCE_3", "type": "order.created", "source": "https://commerce.clayandcrema.de", "subject": "ord_01J8Z3W6Q4XB7N2M5K9RTV0HCE", "time": "2026-10-02T10:15:02.000Z", "environment": "live", "channel": "de", "dataschema": "https://commerce.clayandcrema.de/v1/openapi.json#/webhooks/order.created", "data": { "order": { "id": "ord_01J8Z3W6Q4XB7N2M5K9RTV0HCE", "number": "CC-2026-004711", "version": 3 }, "total": { "amount": 1785, "currency": "EUR" }, "lines": [{ "line": "l_1", "reference": "DAYBREAK-250G-BEANS", "quantity": 1 }] } } ``` Events carry **no personal data** (no names, emails, addresses or gift card codes). Fetch current details with your secret key: ```ts const order = await admin.orders.get(event.subject); ``` ### The catalog | Type | When | Key `data` fields | | ---------------------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------- | | `quote.created` | Quote issued | `cart`, `quote`, `total` | | `quote.accepted` | Buyer agreed to Quote; Payment begins | `cart`, `quote`, `payment`, `total` | | `payment.authorized` | Amount reserved | `cart`, `payment`, `quote`, `amount`, `method`, `provider` | | `payment.pending_funds` | Slow or offline method awaiting funds | Same as `payment.authorized` | | `payment.failed` | Payment or capture refused | Same + `reason`, `order?` | | `payment.canceled` | Payment cancelled by buyer, provider or OrbCart | Same + `reason?`, `order?` | | `payment.captured` | Funds captured (full or partial) | `order`, `payment`, `amount`, `provider` | | `payment.refunded` | Refund settled | `order`, `payment`, `refund`, `amount`, `lines` | | `payment.refund_failed` | Refund failed | `order`, `payment`, `refund`, `amount` | | `order.created` | Order created | `order`, `total`, `lines`, `journey` | | `order.fulfilled` | Units shipped, picked up or delivered | `order`, `lines`, `carrier`, `reference` | | `order.canceled` | Unshipped units cancelled | `order`, `lines` | | `order.returned` | Shipped units returned | `order`, `lines`, `restock` | | `order.withdrawn` | Withdrawal recorded on Order | `order`, `goods`, `lines`, `timing` | | `order.handed_off` | ERP accepted Order | `order`, `reference` | | `order.issue_opened` / `order.issue_resolved` | Order attention issue opened or closed | `order`, `issue`, `resolvedBy?` | | `cart.abandoned` | Non-empty Cart idle for `abandonedAfterHours` (default 24h) | `cart`, `lines`, `journey` | | `cart.canceled` | Unordered Cart expired (`expiresAfterDays`) or discarded | `cart`, `reason` | | `withdrawal.received` | Withdrawal declaration submitted | `withdrawal`, `order?` | | `gift_card.issued` | Gift card sold or issued manually | `giftCard`, `lastFour`, `amount`, `order?` | | `gift_card.redeemed` / `gift_card.credited` / `gift_card.voided` | Gift card balance changed | `giftCard`, `lastFour`, `amount`, `balance`, `order?` | Ignore unknown event types. Always deduplicate by `event.id`, and use `data.order.version` if ordering matters. ## Delivery guarantees, polling and repair - **At-least-once for 72 hours:** retries at 5s, 1m, 5m, 30m, then hourly. After 1 hour of failures, OrbCart probes hourly instead of hammering your endpoint. - **30-day event retention:** use `deliverOrder` for mandatory ERP hand-offs; events are notifications. ### Fetch instead of receive ```ts const page = await admin.events.list({ type: ["order.*"], limit: 50 }); const more = page.next && (await admin.events.list({ type: ["order.*"], after: page.next })); page.data[0].deliveries; // [{ receiver: "mails", status: "delivered", attempts: 1 }] ``` Filter by `type`, `subject`, `channel` and `since`. ### Repair a receiver Requires secret key or staff `connections:edit`: ```ts const { data } = await admin.receivers.list(); await admin.events.resend("evt_01J8Z3W6Q4XB7N2M5K9RTV0HCE_3", { receiver: "erp" }); await admin.events.replay({ since: "2026-10-01T00:00:00Z", receiver: "erp" }); await admin.receivers.pause("erp"); await admin.receivers.resume("erp"); ``` `replay()` handles up to 500 events per call (follow `next` via `after`). ## Customize | You want to | Do this | Default | | ------------------------------------- | ------------------------------------------------------------- | ----------------------- | | Filter events per receiver | Pass `types: ["order.*", "payment.*"]` | Receives all events | | Allow HTTP calls from preview Workers | Pass `previews: true` on `http()` | Blocked in `preview-*` | | Verify behind a rewriting proxy | Pass `target` to `verifyEvent()` | Uses `request.url` | | Tune abandonment or expiry timing | Set `abandonedAfterHours` / `expiresAfterDays` on the Channel | `24` hours / `180` days | ## Next steps | You want to | Read | | --------------------------------------- | ----------------------------------------------------- | | Send confirmation and withdrawal emails | [Sending the buyer's emails](/docs/cart/buyer-emails) | | Read Orders, shipments and refunds | [Orders & refunds](/docs/cart/orders-and-refunds) | | Verify signed HTTP contract calls | [Contracts in another system](/docs/cart/remote-contracts) | | Rotate OrbCart signing keys | [Rotate credentials](/docs/run/credential-rotation) | # The order page Give every buyer a secret, read-only Order link that works on any device without an account. Every Order gets a stable secret link that lets guests and signed-in buyers check their purchase, shipments and refunds from any device. You host the route; OrbCart generates the link and serves the Order payload. ## 1. Configure `orderPage` on the Channel ```ts title="src/worker.ts" members="Channels" de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", orderPage: "https://clayandcrema.de/orders", }, ``` Every Order now exposes `order.url` (`https://clayandcrema.de/orders/ord_…_secret_…`) and `order.token`. Use `order.url` after checkout and in your confirmation emails: ```ts order.url; // https://clayandcrema.de/orders/ord_…_secret_… order.token; // ord_…_secret_… ``` ```ts const order = await admin.orders.get(event.subject); await mail.send({ to: order.contact.email, data: { number: order.number, orderUrl: order.url } }); ``` ## 2. Render the Order route Read the Order with `commerce.order(params.token)` (no API key is required; the token grants read-only access to that single Order) and render ``: ```tsx title="app/routes/orders.$token.tsx" browser import { CommerceError } from "@orbcart/client"; import { OrderPage } from "@orbcart/react"; import type { Route } from "./+types/orders.$token"; export async function loader({ params }: Route.LoaderArgs) { try { return { order: await commerce.order(params.token) }; } catch (error) { if (error instanceof CommerceError) throw new Response(null, { status: 404 }); throw error; } } export default function Order({ loaderData: { order } }: Route.ComponentProps) { return ; } ``` `` displays items, totals, delivery address, payment method (including bank-transfer instructions when unpaid), shipments with tracking and refunds in the Order's language. It never exposes internal provider references, staff notes or issues. Anyone with the link can view the Order and delivery address (read-only). Keep it out of logs and analytics, and serve the route with `Referrer-Policy: strict-origin-when-cross-origin` or stricter. An invalid or truncated token throws `CommerceError` (`order_not_found` or `unauthorized`); direct the buyer to your support contact instead of a raw error page. ## Customize | You want to | Do this | Default | | -------------------------------------------- | --------------------------------------------------------- | ------------------------- | | Add support links below the Order | Pass children to `…` | Order details only | | Render custom product thumbnails | Pass `lineImage` and `lineTitle` to `` | Text-only lines | | Show bank-transfer instructions in custom UI | Mount `` | Included in `` | | Build a completely custom Order page | Render the object returned by `commerce.order(token)` | Prebuilt `` | ## Next steps | You want to | Read | | ------------------------------------------------ | ---------------------------------------------- | | Send Order links in confirmation emails | [Buyer emails](/docs/cart/buyer-emails) | | Add the EU statutory withdrawal flow | [The withdrawal function](/docs/cart/withdrawal) | | Record shipments and refunds on Orders | [Orders and refunds](/docs/cart/orders-and-refunds) | | Enable AI agent checkouts (requires `orderPage`) | [AI agents](/docs/cart/agents) | # Orders & refunds Read Orders, search by buyer, report shipments, cancel units, record offline payments and issue refunds with @orbcart/admin. `@orbcart/admin` runs on your server using your environment's **secret key** (`sk_test_…` or `sk_live_…`). Never import it into browser code. ## Connect and read an Order ```ts title="lib/admin.ts" import { createAdmin } from "@orbcart/admin"; export const admin = createAdmin({ url: env.ORBCART_URL, key: env.ORBCART_SECRET_KEY, }); ``` Look up an Order by number, ID or digits. `get()` always returns authoritative current state including per-line `units` (`ordered`, `fulfilled`, `canceled`, `returned`, `open`, `returnable`): ```ts const order = await admin.orders.get("CC-2026-004711"); ``` ### Search and list Orders Search by email and/or buyer `sub` (sends email in POST body, never in URLs), or list Orders with filters: ```ts const { data } = await admin.orders.search({ email: "anna@example.com" }); const theirs = await admin.orders.search({ buyer: "user_8f2c", email: "anna@example.com" }); const signedIn = await admin.orders.list({ buyer: "user_8f2c", payment: ["captured"] }); ``` ```ts const page = await admin.orders.list({ attention: true, sort: "newest", limit: 50 }); const next = page.next ? await admin.orders.list({ attention: true, after: page.next }) : undefined; ``` | Filter | Example | Matches | | ------------- | -------------------------- | -------------------------------------------- | | `attention` | `true` | Orders with open issues needing staff action | | `payment` | `["authorized", "failed"]` | Payment state | | `fulfillment` | `["unfulfilled"]` | Fulfilment state | | `refunds` | `["partial", "full"]` | Refund state | | `handoff` | `["pending"]` | Orders awaiting ERP acknowledgement | | `channel` | `["de"]` | Channel keys | Pass `count: true` for a total count (capped at 1,000). For monthly exports, pass `since`, `until`, `sort: "oldest"` and `expand: "order"` (up to 50 full Orders per page): ```ts const page = await admin.orders.list({ since: "2026-10-01T00:00:00+02:00", until: "2026-11-01T00:00:00+01:00", sort: "oldest", expand: "order", limit: 50, }); ``` ## Refund Specify **what** to refund (Lines, bundle components, deposits or shipping), never a raw amount. OrbCart calculates exact amounts from the Order's frozen prices, discounts and tax: ```ts const refund = await admin.orders.refund( order.id, { lines: [{ line: "l_1", quantity: 1 }], reason: "return" }, { idempotencyKey: "return-4711-daybreak" }, ); refund.status; // "succeeded" | "pending" | "failed" refund.amount; // { amount: 1290, currency: "EUR" } ``` ```ts alternatives value="RefundInput" { lines: [{ line: "l_2", component: "FILTER-CONE" }] } // one part of a bundle { lines: [], shipping: true } // shipping only { lines: [{ line: "l_1" }], shipping: true } // a Line plus shipping ``` Preview before confirming in a UI, and guard against changes with `expectedAmount`: ```ts const preview = await admin.orders.previewRefund(order.id, { lines: [{ line: "l_1" }] }); await admin.orders.refund(order.id, { lines: [{ line: "l_1" }], expectedAmount: preview.amount }); ``` Keep the same `idempotencyKey` when retrying the same refund after a crash. Use a fresh key for every new refund. `pending` means OrbCart is still awaiting provider confirmation. ### Refund a deposit Return a refundable deposit (such as bottles on `COLD-BREW-6X330`) without refunding the merchandise: ```ts await admin.orders.refund( order.id, { lines: [{ line: "l_1", target: "deposit", quantity: 1 }] }, { idempotencyKey: "returned-deposit-4711" }, ); ``` Check remaining refundable quantities and `depositQuantity` via `admin.orders.refunds(order.id)`. Whole-unit refunds without `target` credit merchandise plus any unrefunded deposits; component refunds never refund deposits. ## Report shipments, cancellations, returns and offline payments ### Report shipments ```ts await admin.orders.fulfill(order.id, { lines: [{ line: "l_1", quantity: 1 }], reference: "DELIVERY-80012", carrier: "DHL", tracking: "00340434161094042557", }); ``` Repeating the same `reference` is a no-op. ### Cancel before shipping ```ts await admin.orders.cancel(order.id, { reason: "Ordered twice" }); ``` Omitting `lines` cancels every unshipped unit. Cancelling a whole Order before capture voids the authorisation; partial cancellation requires captured funds and refunds the difference. Committed stock returns via `inventory.restock`. ### Record a return ```ts await admin.orders.recordReturn(order.id, { lines: [{ line: "l_1", quantity: 1 }], reason: "Damaged cup", restock: true, }); await admin.orders.refund(order.id, { lines: [{ line: "l_1", quantity: 1 }], reason: "Damaged cup", }); ``` ### Record an offline payment received For `bank_transfer` or `pay_on_site` Orders (`payment.status === "pending_funds"`), record incoming funds using the bank transaction ID as `reference` (idempotent): ```ts await admin.orders.recordPayment(order.id, { amount: { amount: 1785, currency: "EUR" }, receivedAt: "2026-11-06T09:30:00Z", reference: "TX-2026-110601", }); ``` Once `payment.owed` reaches `0`, status becomes `captured` and `payment.captured` is emitted. ### Acknowledge ERP fetch When using `fetchOrders: true`: ```ts await admin.orders.acknowledge(order.id, { reference: "SO-2026-1234" }); ``` ## Events, receivers, carts, offers and insights `@orbcart/admin` also provides: ```ts const page = await admin.events.list({ type: ["order.*"], limit: 50 }); await admin.receivers.list(); await admin.events.resend(eventId, { receiver: "erp" }); await admin.events.replay({ since: "2026-10-01T00:00:00Z", receiver: "erp" }); await admin.receivers.pause("erp"); await admin.receivers.resume("erp"); ``` ```ts const page = await admin.carts.needingAttention(); const { issues, history } = await admin.carts.get(page.data[0].id); await admin.offers.invalidate({ tags: ["summer-sale"] }); await admin.offers.invalidate({ references: ["DAYBREAK-250G-BEANS"] }); const { funnel, checkout, friction, payments } = await admin.insights.checkout({ days: 14, channel: ["de"], origin: "storefront", }); const { mode, channels } = await admin.environment.get(); ``` `verifyRequest()` and `verifyEvent()` are also exported from `@orbcart/admin` (both throw subclasses of `VerificationError`): ```ts import { verifyRequest } from "@orbcart/admin"; const { body, requestId, idempotencyKey } = await verifyRequest(request, { url: "https://commerce.clayandcrema.de", contract: "deliverOrder", }); ``` ## Customize | You want to | Do this | Default | | ---------------------------------------- | ---------------------------------------------------------------- | ------------------------------ | | Add custom staff actions to Orders | Declare `orderActions` ([Order actions](/docs/cart/order-actions)) | Fulfil, return, cancel, refund | | Export full Orders for accounting | Use `list({ since, until, sort: "oldest", expand: "order" })` | Summary rows only | | Keep checkout funnel data beyond 30 days | Store `journey` from `order.created` and `cart.abandoned` events | 30-day insights window | ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------------------------- | | Add custom actions to the Order menu | [Run your own actions on an Order](/docs/cart/order-actions) | | Subscribe to Order and Payment events | [Order events](/docs/cart/order-events) | | Verify signed HTTP contract requests | [Contracts in another system](/docs/cart/remote-contracts) | | Browse every Admin HTTP endpoint | [Cart HTTP API](/docs/cart/http-api) | # A payment provider of your own Integrate a payment provider OrbCart does not ship using paymentProviders in defineCommerce. Mollie is the [reference payment plugin](/docs/cart/payments#mollie). Its server entry implements `PaymentProviderFactory`; its browser entry supplies a hosted card field. It uses the same registration as a provider you write yourself. A bank redirect needs no browser component. This extension seam is a preview and its TypeScript shape may still change before the first stable release. ## 1. Register the provider in your Worker Pick a lowercase name not used by a built-in provider. That name also becomes its webhook path (`/webhooks/`): ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { acme } from "./payments/acme"; export default defineCommerce({ paymentProviders: { acme }, channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", payments: { card: "stripe", pay_by_bank: "acme" }, returnUrl: "https://clayandcrema.de/checkout/return", origins: ["https://clayandcrema.de"], }, }, offers: (lines, { currency }) => pricing.offers(lines, { currency }), }); ``` Keep a provider registered in `paymentProviders` while any of its Payments remain unresolved or refundable, even after removing it from Channel `payments`. ## 2. Implement the `PaymentProviderFactory` Declare the Worker bindings in `requires`, open the provider with those credentials, and report observed states and verified webhook events. The second argument to `open` supplies OrbCart's deployment `mode` (`test` or `live`). `cancel` releases unwanted money, for example after an order cancellation. It is not a way to escape an undecided checkout: an authorization could arrive just as the buyer changes methods. Report the original payment's state through `status` or a verified webhook. A local timeout, an unreadable reply, or a cancellation request the bank has merely accepted is not a final failure. ```ts title="src/payments/acme.ts" import { z } from "zod"; import { Duration, Instant, PaymentId, unknownMovement, unknownObservation, } from "@orbcart/runtime/payment"; import type { ObservedPaymentState, PaymentMethodCapabilities, PaymentProviderFactory, ProviderMovement, } from "@orbcart/runtime/payment"; type AcmeEnv = { readonly ACME_API_KEY: string; readonly ACME_WEBHOOK_SECRET: string }; const bankRedirect: PaymentMethodCapabilities = { flow: "redirect", outcome: "async", capture: "separate", partialCapture: false, refund: "partial", requires: [], needs: [], }; const AcmePayment = z.object({ id: z.string(), status: z.enum(["open", "declined", "authorized", "captured", "failed", "canceled", "refunded"]), reference: z.string(), checkoutUrl: z.string().optional(), }); const AcmeMessage = z.object({ id: z.string(), created: z.number(), payment: AcmePayment }); export const acme: PaymentProviderFactory = { requires: ["ACME_API_KEY", "ACME_WEBHOOK_SECRET"], open(env) { async function call(path: string, body: object, idempotencyKey: string) { try { const response = await fetch(`https://api.acme.example${path}`, { method: "POST", headers: { authorization: `Bearer ${env.ACME_API_KEY}`, "content-type": "application/json", "idempotency-key": idempotencyKey, }, body: JSON.stringify(body), signal: AbortSignal.timeout(10_000), }); return AcmePayment.safeParse(await response.json()).data; } catch { return undefined; } } return { methods: new Map([["pay_by_bank", bankRedirect]]), keyRetention: Duration.minutes(24 * 60), browserSetup: () => ({}), async start({ payment, idempotencyKey, returnUrl }) { const created = await call( "/payments", { amount: payment.amount, reference: payment.id, returnUrl }, idempotencyKey, ); if (!created) return unknownObservation("start_unanswered"); const state = stateOf(created.status); if (state) { return { outcome: "known", providerReference: created.id, state, providerFacts: { status: created.status }, }; } if (created.status !== "open" || !created.checkoutUrl) return unknownObservation("unexpected_start", created.id); return { outcome: "known", providerReference: created.id, state: { status: "requires_action", action: { type: "redirect", url: created.checkoutUrl }, }, providerFacts: { status: created.status }, }; }, capture: async ({ payment, amount, idempotencyKey }) => movementOf( await call(`/payments/${payment.providerReference}/capture`, { amount }, idempotencyKey), "captured", ), refund: async ({ payment, refund, amount, idempotencyKey }) => movementOf( await call( `/payments/${payment.providerReference}/refunds`, { amount, reference: refund }, idempotencyKey, ), "refunded", ), cancel: async ({ payment, idempotencyKey }) => movementOf( await call(`/payments/${payment.providerReference}/cancel`, {}, idempotencyKey), "canceled", ), async webhook({ headers, body }) { const signature = headers.get("acme-signature") ?? ""; if (!(await signedByAcme(signature, body, env.ACME_WEBHOOK_SECRET))) { return { status: "signature_invalid" }; } const message = messageIn(body); const state = message && stateOf(message.payment.status); if (!message || !state) return { status: "payload_invalid" }; const payment = PaymentId.parse(message.payment.reference); return { status: "verified", events: [ { id: message.id, type: `payment.${message.payment.status}`, ...(payment && { payment }), createdAt: Instant.from(message.created * 1000), observation: { outcome: "known", providerReference: message.payment.id, state, providerFacts: { status: message.payment.status }, }, document: { id: message.id, payment: message.payment.id, status: message.payment.status, }, }, ], }; }, }; }, }; function messageIn(body: string) { try { return AcmeMessage.safeParse(JSON.parse(body)).data; } catch { return undefined; } } function movementOf( moved: z.output | undefined, confirmed: "captured" | "refunded" | "canceled", ): ProviderMovement { if (!moved) return unknownMovement("unanswered"); const providerFacts = { status: moved.status }; return moved.status === "failed" || moved.status === "declined" ? { outcome: "failed", providerFacts } : { outcome: moved.status === confirmed ? "succeeded" : "pending", providerReference: moved.id, providerFacts, }; } function stateOf(status: z.output["status"]): ObservedPaymentState | undefined { switch (status) { case "authorized": case "captured": case "canceled": return { status }; case "failed": case "declined": return { status: "failed", reason: "declined" }; case "open": case "refunded": return undefined; } } async function signedByAcme(signature: string, body: string, secret: string): Promise { const encoder = new TextEncoder(); const key = await crypto.subtle.importKey( "raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"], ); try { return await crypto.subtle.verify( "HMAC", key, Uint8Array.fromBase64(signature), encoder.encode(body), ); } catch { return false; } } ``` ## Responsibilities and browser fields Your provider reports observations; OrbCart enforces the payment state machine: | Duty | Why | | --------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | Forward `idempotencyKey` | Prevents double charges on retries; declare `keyRetention` to match your provider. | | Return `unknownObservation()` / `unknownMovement()` on timeouts | Never guess failed or paid when a network call is unanswered. | | Verify webhook signatures before parsing | Unverified or unparseable payloads are rejected before storage. | - **Redirect flows (`flow: "redirect"`):** require no frontend code; `accept()` redirects and `cart.resume()` completes on return. - **Inline fields (`flow: "inline"`):** register your browser field once before mounting checkout using `registerPaymentComponent` from `@orbcart/client/payment`. - **Not possible today:** inventing new method names outside OrbCart's list, or custom express wallets. ## Customize | You want to | Do this | Default | | ----------------------------------- | -------------------------------------------------------------------------- | ----------------------------------- | | Mount a custom inline payment field | Call `registerPaymentComponent()` from `@orbcart/client/payment` | Redirect flow needs no browser code | | Test your provider end to end | Stub `fetch` at the provider boundary in Vitest ([Testing](/docs/cart/testing)) | Real provider HTTP calls | ## Next steps | You want to | Read | | ---------------------------------------------- | ----------------------------------- | | Configure built-in payment providers | [Payment providers](/docs/cart/payments) | | Test Worker purchases with faked `fetch` | [Testing](/docs/cart/testing) | | Explore every OrbCart extension point | [Extend OrbCart](/docs/cart/extend) | | Trace how OrbCart handles retries and webhooks | [How it works](/docs/cart/how-it-works) | # Payment providers Map payment methods to Stripe, Adyen, Mollie, PAYONE, PayPal, Amazon Pay or offline transfers in your Channel config. Map each payment method to an installed provider on the Channel. Once the storefront has the provider's browser component, it can render the methods the Channel offers without changing checkout. ## Map methods to providers ```ts title="src/worker.ts" members="ChannelConfig" payments: { card: "adyen", apple_pay: "stripe", google_pay: "adyen", paypal: "paypal", klarna: "adyen", }, ``` ### Methods and providers | Method | Stripe | Adyen | Mollie | PAYONE | PayPal | Available for | | ------------- | :----: | :---: | :----: | :----: | :----: | ----------------------------------------------------------- | | `card` | ✓ | ✓ | ✓ | ✓ | | All countries | | `apple_pay` | ✓ | ✓ | | ✓³ | | Apple devices, all countries | | `google_pay` | ✓ | ✓ | | ✓² | | All countries | | `paypal` | | | | | ✓ | EUR, GBP, USD (not CHF yet) | | `klarna` | ✓ | ✓ | ✓¹ | | | Klarna-supported countries | | `ideal` | ✓ | ✓ | ✓ | ✓² | | NL, EUR ("iDEAL \| Wero") | | `bancontact` | ✓ | ✓ | ✓ | | | BE, EUR | | `eps` | ✓ | | ✓¹ | ✓² | | AT, EUR | | `przelewy24` | ✓ | | ✓¹ | | | PL, EUR | | `twint` | ✓ | ✓ | ✓ | | | CH, CHF | | `pay_by_bank` | | ✓ | ✓ | ✓² | | Adyen: DE/FR/FI; Mollie: 9 EU; PAYONE: AT/BE/DE/FR/NL (EUR) | ¹ Built, awaiting Mollie sandbox verification. ² Built, awaiting PAYONE sandbox verification. ³ Built, awaiting PAYONE sandbox and Apple device verification. OrbCart filters `quote.paymentMethods` automatically by billing country (or delivery country when no separate billing address is set) and Channel currency. PayPal, Amazon Pay, Klarna, iDEAL, EPS, Przelewy24, TWINT, Pay by Bank (plus Mollie and PAYONE card 3-D Secure) redirect the buyer away. Set `returnUrl` on the Channel to a page on your `origins`. ## Stripe ### Set secrets ```sh wrangler secret put STRIPE_SECRET_KEY # sk_test_… or sk_live_… wrangler secret put STRIPE_PUBLISHABLE_KEY # pk_test_… or pk_live_… wrangler secret put STRIPE_WEBHOOK_SECRET # whsec_… ``` ### Configure the webhook Create a webhook pointing to `https:///webhooks/stripe` using API version `2026-08-26.dahlia`. Locally, forward events to port `8797`: ```sh stripe listen --latest --all-snapshot --forward-to localhost:8797/webhooks/stripe ``` Register your storefront domain as a payment method domain in Stripe to enable Apple Pay and Google Pay. If Stripe declines an inline card for insufficient funds, the buyer can enter another card for the same PaymentIntent. OrbCart does not open a second payment. An ambiguous processing error stays pending. ## Adyen ### Set secrets and allowed origins ```sh wrangler secret put ADYEN_API_KEY # API credential with Checkout role wrangler secret put ADYEN_CLIENT_KEY # test_… or live_… wrangler secret put ADYEN_MERCHANT_ACCOUNT wrangler secret put ADYEN_HMAC_KEY # hex from webhook ``` In `live`, also set `ADYEN_LIVE_URL_PREFIX`. Add your storefront origins (and `http://localhost:5173` locally) to the client key's allowed origins in Adyen Customer Area. ### Create one standard webhook Point one JSON standard webhook with HMAC signing at `https:///webhooks/adyen`. Keep only one webhook per URL. For Apple Pay, serve Adyen's domain file at `/.well-known/apple-developer-merchantid-domain-association` as `text/plain` without redirects. ## Mollie Install `@orbcart/plugin-mollie` and register its **server** entry in your Worker. The name `mollie` identifies both the webhook route and the provider of a stored payment. ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { mollie } from "@orbcart/plugin-mollie/server"; export default defineCommerce({ paymentProviders: { mollie }, channels: { nl: { currency: "EUR", pricesIncludeTax: true, locale: "nl-NL", payments: { card: "mollie", ideal: "mollie" }, origins: ["https://shop.example"], returnUrl: "https://shop.example/checkout/return", }, }, offers: (lines, { currency }) => pricing.offers(lines, { currency }), }); ``` Register the **browser** entry before mounting checkout to use Mollie's hosted card fields. A shop offering only bank redirects can omit it. ```ts browser import { registerPaymentComponent } from "@orbcart/client/payment"; import { mollieComponent } from "@orbcart/plugin-mollie/browser"; registerPaymentComponent("mollie", mollieComponent); ``` To stop selling through Mollie, remove its mappings from Channel `payments`. Keep the server entry, its credentials and webhook active while earlier payments can still settle or need refunds. ```sh wrangler secret put MOLLIE_API_KEY # test_… in test, live_… in live wrangler secret put MOLLIE_WEBHOOK_URL # https:///webhooks/mollie (required in live) ``` Activate each mapped method in your Mollie website profile (test and live separately). Leave `MOLLIE_WEBHOOK_URL` unset locally because Mollie rejects unreachable URLs. Allow `js.mollie.com` in your storefront's `script-src` and `frame-src`. ## PAYONE Sign up for preprod at [signup.preprod.payone.com](https://signup.preprod.payone.com/), register `https:///webhooks/payone`, activate your methods and set: ```sh wrangler secret put PAYONE_MERCHANT_ID # your PSPID wrangler secret put PAYONE_API_KEY_ID wrangler secret put PAYONE_API_SECRET wrangler secret put PAYONE_WEBHOOK_KEY_ID wrangler secret put PAYONE_WEBHOOK_SECRET ``` Allow `payment.payone.com` (and `payment.preprod.payone.com` in test) in `script-src` and `frame-src`. PAYONE refunds initially return `REFUND_REQUESTED` (`81`) before settling to `REFUNDED` (`8`); confirm capture (`CAPTURED`, `9`) before refunding and poll the refund via the Admin SDK with a stable idempotency key. ### Google Pay and Apple Pay Map `google_pay: "payone"` and `apple_pay: "payone"`, allow `pay.google.com` in your CSP, and set these Worker vars: ```ts title="src/worker.ts" members="ChannelConfig" payments: { card: "payone", google_pay: "payone", apple_pay: "payone" }, ``` ```jsonc "vars": { "PAYONE_WALLET_NAME": "Clay & Crema", // max 64 chars "PAYONE_WALLET_COUNTRY": "DE" // settlement country } ``` - **Google Pay:** in `live`, also set `PAYONE_GOOGLE_PAY_MERCHANT_ID` from the Google Pay & Wallet Console. - **Apple Pay:** register your HTTPS domain in PAYONE's portal (no Apple developer certificate needed) and serve `/.well-known/apple-developer-merchantid-domain-association`. PAYONE web Apple Pay settles immediately as a sale. ### The card field's look PAYONE's card field ignores checkout CSS tokens. Build a static template in PAYONE's [Template Builder](https://developer.payone.com/en/design-and-test-tools/tools/template-builder), ask PAYONE to upload it, and set its filename in `vars`: ```jsonc "vars": { "PAYONE_CARD_TEMPLATE": "your-card-template.html" } ``` ## PayPal ```sh wrangler secret put PAYPAL_CLIENT_ID wrangler secret put PAYPAL_CLIENT_SECRET wrangler secret put PAYPAL_WEBHOOK_ID ``` Point your PayPal app webhook at `https:///webhooks/paypal`. ## Amazon Pay Add `@orbcart/plugin-amazon-pay` and register its **server** entry in your Worker. Use the provider name `amazon_pay` to keep earlier payments reachable. ```ts title="src/worker.ts" import { defineCommerce } from "@orbcart/runtime"; import { amazonPay } from "@orbcart/plugin-amazon-pay/server"; export default defineCommerce({ paymentProviders: { amazon_pay: amazonPay }, channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", payments: { amazon_pay: "amazon_pay" }, origins: ["https://shop.example"], returnUrl: "https://shop.example/checkout/return", }, }, offers: (lines, { currency }) => pricing.offers(lines, { currency }), }); ``` Register the **browser** entry before mounting checkout: ```ts browser import { registerExpressComponents } from "@orbcart/client/payment"; import { amazonPayComponents } from "@orbcart/plugin-amazon-pay/browser"; registerExpressComponents("amazon_pay", amazonPayComponents); ``` Amazon Pay appears as an express button by default. Set `amazon_pay: { provider: "amazon_pay", offer: "method" }` to show it among payment methods instead, or use `offer: "both"`. Set the six bindings (`AMAZON_PAY_PRIVATE_KEY` is a PKCS#8 PEM kept secret on the Worker; the other five may be plain vars): ```sh wrangler secret put AMAZON_PAY_MERCHANT_ID wrangler secret put AMAZON_PAY_STORE_ID wrangler secret put AMAZON_PAY_PUBLIC_KEY_ID wrangler secret put AMAZON_PAY_PRIVATE_KEY wrangler secret put AMAZON_PAY_REGION # us | eu | jp wrangler secret put AMAZON_PAY_LEDGER_CURRENCY # USD | EUR | GBP | JPY ``` Set the Channel currency to the account's ledger currency. Register your HTTPS origins and review return URLs in Amazon Pay settings. Allow the regional script in your CSP: `static-eu.payments-amazon.com`, `static-na.payments-amazon.com` or `static-fe.payments-amazon.com`. OrbCart uses Amazon's review flow, not `ProcessOrder`. **PayAndShip** covers physical deliveries; **PayOnly** covers pickup and digital carts. Server polling resolves payments and refunds without SNS or IPN. Issue refunds through OrbCart rather than Seller Central. The integration has not yet been verified against Amazon's sandbox. To stop offering Amazon Pay, remove the Channel's `amazon_pay` mapping. Leave the server registration and credentials in place while earlier payments can still settle or need refunds. ## Bank transfer and pay on site Map `bank_transfer` and `pay_on_site` to the built-in `"offline"` provider: ```ts title="src/commerce.ts" import type { BankTransferConfig, ChannelConfig } from "@orbcart/runtime"; const transfer = { provider: "offline", account: { holder: "Clay & Crema GmbH", iban: "DE89 3704 0044 0532 0130 00", bic: "COBADEFFXXX", bank: "Commerzbank", }, daysToPay: 7, } satisfies BankTransferConfig; export const payments = { card: "stripe", bank_transfer: { ...transfer, carts: "that_ship" }, pay_on_site: { provider: "offline", instructions: "Pay by card or cash at our Munich roastery.", carts: "that_ship_nothing", }, } satisfies ChannelConfig["payments"]; ``` - `carts: "that_ship"` or `"that_ship_nothing"` restricts any payment method to shipping or non-shipping Carts. - Offline Orders start **awaiting payment** (holding stock immediately) and display payment instructions using the **order number** as bank reference. Record incoming funds in the admin or via `admin.orders.recordPayment()` to emit `payment.captured`. ## Customize | You want to | Do this | Default | | ---------------------------------------------- | ------------------------------------------------------ | ----------------------- | | Mix multiple providers per market | Map each method key to its own provider | One provider per method | | Restrict a method to physical or digital carts | Set `carts: "that_ship" \| "that_ship_nothing"` | Offered on all Carts | | Show Amazon Pay among methods or as express | Set `offer: "express" \| "method" \| "both"` | Provider default | | Add a provider OrbCart does not ship | Implement [`paymentProviders`](/docs/cart/payment-provider) | Built-in providers | ## Next steps | You want to | Read | | -------------------------------------------------------- | -------------------------------------------------------- | | Add Apple Pay, Google Pay, PayPal and Amazon Pay buttons | [Express checkout](/docs/cart/express-checkout) | | Test cards, wallets and bank simulators in sandbox | [Test payments](/docs/cart/test-payments) | | Build a custom payment provider module | [A payment provider of your own](/docs/cart/payment-provider) | | Capture, record payments and issue refunds | [Orders and refunds](/docs/cart/orders-and-refunds) | # Quotes & payments Lock in a binding signed Quote, mount inline payment fields, handle redirect returns and place an Order. If you use React, [``](/docs/cart/react-checkout) handles every step on this page. Outside React, use the checkout store in [A checkout without React](/docs/cart/checkout-without-react), or call the primitives below directly. ## 1. Request a binding Quote Call `cart.quote()` with the buyer's contact and address details. The returned Quote is signed, locks in exact prices and tax, and expires after at most 30 minutes: ```ts const quote = await cart.quote({ contact: { email: "anna@example.com" }, shipTo: { name: "Anna Berg", line1: "Bergstraße 12", postalCode: "10115", city: "Berlin", country: "DE", }, }); ``` Format `quote.totals.total` with `formatMoney()` rather than dividing minor units yourself: ```ts import { formatMoney } from "@orbcart/client"; formatMoney(quote.totals.total, "en-GB"); // "€94.85" ``` - **Missing fields:** throws `CommerceError` with `code: "cart_incomplete"` and `error.problem.missing` listing what is required (such as `["ship_to_postal_code"]`). - **Refundable deposits:** Offers with a deposit (such as `COLD-BREW-6X330`) expose `line.deposit.totals` and aggregate `quote.totals.deposit` so you can display deposits on a separate row. `quote.totals.total` already includes them. Orders preserve the exact signed `quote/2` (or historical `quote/1`) bytes. ## 2. Choose a payment method `quote.paymentMethods` lists every method available for this Channel, currency and billing country: ```ts quote.paymentMethods; // [{ id: "card", provider: "adyen", flow: "inline" }, // { id: "paypal", provider: "paypal", flow: "redirect" }, // { id: "klarna", provider: "adyen", flow: "redirect" }] ``` | `flow` | Behaviour | | ---------- | --------------------------------------------------------------------------------------------------- | | `inline` | Mount a provider-hosted card or payment field on your page (card, Bancontact). | | `redirect` | Redirect the buyer to the provider and resume at `returnUrl` (PayPal, Klarna, iDEAL, TWINT). | | `wallet` | Open a native wallet sheet (Apple Pay, Google Pay; see [Express checkout](/docs/cart/express-checkout)). | ## 3. Mount an inline payment field For `inline` methods, mount the provider field into an empty element. Card numbers travel directly to the provider and never touch your page or Worker. The mounted field outlives the Quote and can be reused if a Quote refreshes: ```html
``` ```ts const element = document.querySelector("#payment-field")!; const payment = await quote.mountPayment("card", element); ``` For `redirect` methods, skip mounting and pass the method ID (such as `"paypal"`) directly to `pay()`. ### Match the field to your theme Use `adyenVariables()` (accepts CSS custom properties) or `stripeAppearance()` (requires literal colour values; pass `dark: true` in dark mode): ```ts import { adyenVariables, stripeAppearance } from "@orbcart/client/payment"; const colors = { text: "#0a0f1f", surface: "#fff", action: "#31476b", radius: "6px" }; Object.assign( element.style, adyenVariables({ ...colors, muted: "#5b6275", error: "#b3261e", border: "#d9dce4", focus: colors.action, }), ); const payment = await quote.mountPayment("card", element, { appearance: stripeAppearance(colors) }); ``` PAYONE's outer frame receives a localised title before first paint and uses the template configured in your PAYONE account. ## 4. Place the Order Call `quote.pay()` only from the buyer's click on the order button: ```ts alternatives const result = await quote.pay({ payment }); // inline: mounted field const result = await quote.pay({ payment: "paypal" }); // redirect: method ID ``` `pay()` accepts the Quote, runs 3-D Secure when requested and waits up to 10 seconds for a final outcome: ```ts function switch (result.status) { case "ordered": return showConfirmation(result.order.number); case "quote_changed": return askAgain(result.quote, result.changes); case "failed": return letBuyerTryAgain(); case "pending": return showWaiting(result); case "requires_action": return result.action.run(); } ``` | `status` | What to do | | ----------------- | -------------------------------------------------------------------------------------------- | | `ordered` | Show confirmation with `result.order.number`. | | `quote_changed` | Price, stock or shipping changed; display `result.quote` and `result.changes` and ask again. | | `failed` | Payment declined; let the buyer retry or switch methods. | | `pending` | Provider has not decided after 10 seconds; wait without starting a new payment. | | `requires_action` | Buyer has an unfinished step (such as 3-D Secure); call `result.action.run()`. | A pending result is not a failure. Follow the same payment with `result.wait()` until the provider decides. The local payment window is not a bank deadline. If an attempt can still settle, a method switch, reload or expired timer does not unlock a second payment. ```ts if (result.status === "pending") { const outcome = await result.wait({ timeout: Infinity }); } ``` ## 5. Return from a redirect On your Channel's `returnUrl`, reopen the Cart from the session cookie and call `cart.resume()`. It reads the URL parameters and returns the same outcome union as `pay()`: ```ts const cart = commerce.openCart(savedToken); const result = await cart.resume(); ``` After an ordinary reload mid-checkout, reopen the existing Quote without starting a new payment: ```ts const quote = await cart.openQuote(quoteId); ``` ## Verify a Quote Every Quote is signed with the environment's ES256 key and stored on `order.quote`. Anyone can verify its signature against `/.well-known/jwks.json`: ```ts import { verifyQuote } from "@orbcart/client"; const keys = await fetch(`${ORBCART_URL}/.well-known/jwks.json`).then((r) => r.json()); const { valid } = await verifyQuote(quote, keys); ``` ## Customize | You want to | Do this | Default | | ----------------------------------- | ----------------------------------------------------- | --------------------------- | | Style Stripe or Adyen card fields | Pass `stripeAppearance()` or apply `adyenVariables()` | Provider default styles | | Wait indefinitely for slow payments | Call `result.wait({ timeout: Infinity })` | 10-second wait | | Drive steps from a server or agent | Call `quote.accept()` with a ready `instrument` | `quote.pay()` for browsers | | Skip manual plumbing in React | Mount [``](/docs/cart/react-checkout) | Low-level `@orbcart/client` | ## Next steps | You want to | Read | | ---------------------------------------------- | -------------------------------------------------------- | | Configure shipping and store pickup | [Shipping](/docs/cart/shipping) | | Add Apple Pay, Google Pay and PayPal Express | [Express checkout](/docs/cart/express-checkout) | | Build a framework-free checkout with the store | [A checkout without React](/docs/cart/checkout-without-react) | | Use the ready-made React checkout kit | [React checkout](/docs/cart/react-checkout) | # React checkout Drop in , CartProvider and composable checkout regions from @orbcart/react. `` handles contact, addresses, delivery and pickup, payment fields, 3-D Secure, changed Quotes and slow payments. You pass a `CommerceCart` handle and handle `onOrdered`. ## Render `` ```tsx title="CheckoutPage.tsx" import { useNavigate } from "react-router"; import type { CommerceCart } from "@orbcart/client"; import { Checkout } from "@orbcart/react"; import "@orbcart/react/styles.css"; export function CheckoutPage({ cart }: { cart: CommerceCart }) { const navigate = useNavigate(); return ( navigate(`/orders/${order.number}`)} /> ); } ``` Pass `cart` from [`commerce.openCart(token)`](/docs/cart/carts#keep-the-cart-across-reloads) rather than creating a new Cart on every render. Unsaved form drafts (contact, addresses and custom fields, never payment data or tokens) persist in `sessionStorage` for that Cart so opening legal pages in the same tab keeps what the buyer typed. ## A Cart for the whole storefront Wrap your app in `CartProvider` and `OrbCartProvider` so any component can add items and share one locale: ```tsx title="App.tsx" import { CartProvider, useShoppingCart } from "@orbcart/react"; saveToken(cart.token)}> ; function AddToBag({ reference }: { reference: string }) { const { add } = useShoppingCart(); return ; } ``` ```tsx title="Shop.tsx" import { Money, OrbCartProvider } from "@orbcart/react"; ; ``` - `de-DE`, `de-AT` and `de-CH` select German labels (informal by default); use `de-DE-formal` or `de-CH-formal` for formal "Sie". Every other locale uses English labels with local money formatting. - `Money` marks fractional digits (`data-part="orbcart-money-cents"`) and currency (`data-part="orbcart-money-currency"`) for typographic styling. ## Props reference | Prop | Example | Purpose | | ------------------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------- | | `cart` | `commerce.openCart(token)` | Cart handle to check out (required). | | `locale` | `"de-DE"` | Language, money format and provider field locale. | | `homeCountry` | `"DE"` | Omit this country from review addresses (foreign countries always show). | | `onOrdered` | `(order) => navigate(...)` | Redirect or render your confirmation view. | | `start` | `{ from: "quote", quote }` | Reopen an existing Quote directly. | | `labels` | `{ contact: { heading: "…" } }` | Override built-in wording (the legal order button text is fixed). | | `discountCode` | `false` | Hide the discount code input (shown by default). | | `showEstimate` | `false` | Hide the estimate before a Quote (shown by default). | | `stickyAction` | `true` | Keep step button and total pinned on narrow viewports. | | `lineImage`, `lineTitle` | `(reference, line) => ` | Custom product thumbnails and titles (4rem default slot via `--orbcart-line-image-size`). | | `summaryHeader` | `({ lines }) => ` | Custom header above summary lines (such as booking time). | | `paymentHelp` | `(method) => ` | Helper content beside the payment field. | | `deliveryAddress` | `DhlDeliveryAddress` | Custom delivery address UI (such as a pickup point finder). | | `fields` | `{ vatId: VatIdField }` | Custom controls for Cart extension fields. | | `after` | `{ order: }` | Inject content after `express`, `contact`, `shipping`, `address`, `payment`, `order` or `summary`. | | `addressPriority` | `"billing"` | Lead with billing address instead of delivery address. | | `pickup` | `{ defaultLocation: "loc_…" }` | Default store pickup Location and `searchFrom` threshold (default `10`). | | `paymentOptions` | `{ appearance: "inherit" }` | Inherit your checkout CSS tokens into Stripe's card field. | | `identity`, `onSignedIn` | `betterAuthIdentity(…)` | Inline buyer sign-in ([Signed-in buyers](/docs/cart/identity)). | | `buyer`, `signOut` | `{ email }`, `` | Display an already signed-in buyer. | | `steps`, `step`, `onStepChange` | `steps` | Three-step flow or [one route per step](/docs/cart/checkout-steps). | | `className`, `children` | `"my-checkout"` | Root class for theming, or custom region composition. | ## Delivery, pickup, billing and redirects ### Delivery or pickup By default, buyers pick delivery or store pickup right after contact. - Single-country Channels preselect the cheapest delivery before an address is typed; pickup is never preselected unless it is the only option. - Methods excluded by Cart Lines stay visible and disabled with the blocking Lines listed (`labels.shipping.unavailable`). - Non-shipping Carts (services or digital goods) ask only for email and billing country unless the Channel sets [`billingAddress: "required"`](/docs/cart/configuration#contactfields-and-billingaddress). - Setting `addressPriority="billing"` places billing address first with a checked "Delivery address same as billing address" toggle for physical goods. ### Redirect returns and `start` Returning from PayPal, Amazon Pay, Klarna, iDEAL or an express review (`/checkout?preparation=…`) resumes automatically by reading the URL. Pass `start` only to reopen a specific Quote: ```tsx elements ``` ### Line attributes and `summaryHeader` Offer `attributes` render under each Line title in the bag, summary and Order page (Line `configuration` is never shown). Use `summaryHeader` for Cart-wide context such as an appointment slot: ```tsx title="CheckoutPage.tsx" import type { CommerceCart } from "@orbcart/client"; import { Checkout } from "@orbcart/react"; import type { SummaryHeaderContext } from "@orbcart/react"; function Appointment({ lines, changeable }: SummaryHeaderContext) { const time = lines.find((line) => line.offer?.attributes?.["Time"])?.offer?.attributes?.["Time"]; if (!time) return null; return (

Your appointment: {time} {changeable && Change}

); } export function CheckoutPage({ cart }: { cart: CommerceCart }) { return } />; } ``` ## Theme and labels The kit's stylesheet lives in `@layer orbcart`. With Tailwind, declare `@layer theme, base, orbcart, components, utilities;` so your utilities win. Style via CSS custom properties and `data-part` attributes: ```css .my-checkout { --orbcart-color-text: #18212f; --orbcart-color-surface: #fff; --orbcart-color-action: #31476b; --orbcart-color-action-text: #fff; --orbcart-color-action-hover: #26385a; --orbcart-color-focus: #31476b; --orbcart-font-family: "Inter", sans-serif; --orbcart-field-radius: 0.375rem; --orbcart-button-radius: 999px; --orbcart-columns: minmax(0, 1fr) minmax(0, 24rem); } .my-checkout [data-part="orbcart-checkout-summary"] { background: #f7f7f5; } ``` Pass `paymentOptions={{ appearance: "inherit" }}` so Stripe's card field reads your tokens (Adyen follows light/dark themes automatically; PAYONE uses its account template). Override labels selectively: ```tsx ``` ## Compose regions, steps and custom fields ### Content between regions Use `after` to place trust badges or shipping notes after any region (`express`, `contact`, `shipping`, `address`, `payment`, `order`, `summary`): ```tsx title="CheckoutPage.tsx" import type { CommerceCart } from "@orbcart/client"; import { Checkout } from "@orbcart/react"; export function CheckoutPage({ cart }: { cart: CommerceCart }) { return ( Secure payment. 30 days to return.

, summary: ({ quote }) => quote &&

Ships within two working days.

, }} /> ); } ``` ### Compose the page Pass region components (`CheckoutExpress`, `CheckoutDetails`, `CheckoutPayment`, `CheckoutSummary`) as children of `` to control layout and markup: ```tsx title="CheckoutPage.tsx" import type { CommerceCart } from "@orbcart/client"; import { Checkout, CheckoutDetails, CheckoutPayment, CheckoutSummary } from "@orbcart/react"; export function CheckoutPage({ cart }: { cart: CommerceCart }) { return ( window.location.assign(`/orders/${order.number}`)}>

Secure payment. 30 days to return.

); } ``` Waiting, review and confirmation panels remain managed by `` (`data-panel="waiting"` or `"review"`). ### Run in steps Pass `steps` for a built-in three-step checkout (contact, delivery, payment), or group `CheckoutContact`, `CheckoutShipping` (`part="way"` / `part="methods"`), `CheckoutAddress`, `CheckoutExtensions` and `CheckoutPayment` inside `CheckoutStep`: ```tsx title="CheckoutPage.tsx" import type { CommerceCart } from "@orbcart/client"; import { Checkout, CheckoutAddress, CheckoutContact, CheckoutExtensions, CheckoutPayment, CheckoutShipping, CheckoutStep, CheckoutSummary, } from "@orbcart/react"; export function CheckoutPage({ cart }: { cart: CommerceCart }) { return ( window.location.assign(`/orders/${order.number}`)}> ); } ``` The Cart's `missing` list determines which steps are complete; steps save only when the buyer clicks **Continue**. For one URL per step, see [A checkout with a page per step](/docs/cart/checkout-steps). ### Fields of your own Cart extensions with [`ask`](/docs/cart/extensions#ask-for-a-value-at-checkout) render automatically. Replace any field with a custom component built on `Field`: ```tsx title="CheckoutPage.tsx" import type { CommerceCart } from "@orbcart/client"; import { Checkout, Field } from "@orbcart/react"; import type { ExtensionFieldProps } from "@orbcart/react"; function VatIdField({ id, name, label, value, onChange, error, required }: ExtensionFieldProps) { return ( {(described) => ( onChange(event.currentTarget.value.toUpperCase())} /> )} ); } export function CheckoutPage({ cart }: { cart: CommerceCart }) { return ; } ``` ### Standalone building blocks `@orbcart/react` also exports `useCheckout()`, `Cart`, `Line`, `OrderSummary`, `ShippingChoice`, `DiscountCode`, `Changes`, `Money`, `Address`, `PostalAddress`, `OrderPage`, `OrderPayment`, `ExpressCheckout` and `Totals`: ```tsx import { Totals } from "@orbcart/react"; ; ``` `` links your [legal texts](/docs/cart/configuration#legal) and pairs with [``](/docs/cart/order-page), but check [Status](/docs/cart/status) for remaining pre-release items before taking live payments. ## Customize | You want to | Do this | Default | | -------------------------------- | ------------------------------------------------------- | ---------------------- | | Restyle colours, fonts and radii | Override `--orbcart-*` CSS variables on a wrapper class | Built-in neutral theme | | Switch to a three-step checkout | Pass `steps` or compose `CheckoutStep` children | Single-page checkout | | Inject trust badges or notes | Pass `after={{ order, summary }}` | No extra blocks | | Build a completely custom UI | Call `useCheckout({ cart })` or use `@orbcart/client` | Prebuilt `` | ## Next steps | You want to | Read | | ----------------------------------------------- | ------------------------------------------------------- | | Add a header bag with cookie persistence | [Add to cart and a mini cart](/docs/cart/add-to-cart) | | Give each checkout step its own URL | [A checkout with a page per step](/docs/cart/checkout-steps) | | Render the post-purchase Order page | [The order page](/docs/cart/order-page) | | Read Orders and issue refunds from your backend | [Orders and refunds](/docs/cart/orders-and-refunds) | # Recipes Complete, copyable builds for Clay & Crema, from an add-to-cart button to ERP hand-off and Vitest purchase tests. Each recipe builds one complete feature for **Clay & Crema** in the order you write it, linking out to guides rather than repeating explanations. Swap `DAYBREAK-250G-BEANS` for your own SKU to adapt any recipe to your shop. ## In the storefront | Recipe | What you build | | ----------------------------------------------------------------- | ------------------------------------------------------------------------ | | [Add to cart and a mini cart](/docs/cart/add-to-cart) | Product button and header bag in React with an `HttpOnly` token cookie. | | [A checkout without React](/docs/cart/checkout-without-react) | Plain TypeScript checkout page using `@orbcart/client`'s checkout store. | | [A checkout with a page per step](/docs/cart/checkout-steps) | Dedicated routes for contact, delivery and payment driven by Cart state. | | [Free shipping and a welcome code](/docs/cart/free-shipping-and-codes) | Declared promotions, a code input and a Vitest test proving both. | ## In your Worker and your systems | Recipe | What you build | | ------------------------------------------------------------ | ------------------------------------------------------------------------------- | | [Prices and stock from your ERP](/docs/cart/erp-prices-and-stock) | Signed HTTP `offers` and `inventory` endpoints with stock holds. | | [Send paid Orders to your ERP](/docs/cart/erp-order-handoff) | Idempotent sales-order creation on `deliverOrder` and shipment reporting. | | [A gift message, end to end](/docs/cart/gift-message) | Custom Cart extension from checkout input to ERP packing slip. | | [Test a purchase](/docs/cart/test-a-purchase) | Vitest test that quotes, pays via fake Stripe and verifies double-click safety. | ## Next steps | You want to | Read | | --------------------------------- | ------------------------------------------ | | See every OrbCart extension point | [Extend OrbCart](/docs/cart/extend) | | Run OrbCart locally in minutes | [OrbCart quickstart](/docs/get-started/orbcart) | # Contracts in another system Run offers, inventory, tax, shippingRates, orderActions and deliverOrder over signed HTTP or Cloudflare Service Bindings. Any OrbCart contract (`offers`, `inventory`, `tax`, `shippingRates`, `pickupLocations`, `appointments`, `deliverOrder` and `orderActions`) can run outside your commerce Worker via `http()` or `service()` with the same arguments, timeouts and validation. ## Attach remote contracts ```ts title="src/worker.ts" import { defineCommerce, http, service } from "@orbcart/runtime"; export default defineCommerce({ channels, offers: service("PRICES"), inventory: { check: http((vars) => vars.get("SHOP_URL") + "/commerce/stock"), reserve: http((vars) => vars.get("SHOP_URL") + "/commerce/reserve"), release: http((vars) => vars.get("SHOP_URL") + "/commerce/release"), commit: http((vars) => vars.get("SHOP_URL") + "/commerce/commit"), restock: http((vars) => vars.get("SHOP_URL") + "/commerce/restock"), }, deliverOrder: http("https://middleware.clayandcrema.de/edge/orders", { timeoutMs: 20_000 }), }); ``` HTTP URLs must use `https` on port `443` with a public hostname (no IP addresses or private names; `wrangler dev` allows `http` and `localhost`). Preview environments still call HTTP contracts, so read environment-specific URLs from `vars`. ## Request format and paths Every call is a `POST` with `Content-Type: application/json`. HTTP endpoints are called at the exact URL you pass; Service Bindings are called at the paths below: | Contract | Service Binding path | JSON body | | ------------------------ | -------------------------- | ------------------------------ | | `offers` | `/offers` | `lines`, `context` | | `tax` | `/tax` | `draft`, `context` | | `shippingRates` | `/shipping-rates` | `request`, `context` | | `deliverOrder` | `/deliver-order` | `order`, `context` | | `pickupLocations` | `/pickup-locations` | `context` | | `inventory.check` | `/inventory/check` | `references`, `context` | | `inventory.reserve` | `/inventory/reserve` | `hold`, `context` | | `inventory.release` | `/inventory/release` | `holdId`, `context` | | `inventory.commit` | `/inventory/commit` | `holdId`, `orderId`, `context` | | `inventory.restock` | `/inventory/restock` | `restock`, `context` | | `appointments.reserve` | `/appointments/reserve` | `hold`, `context` | | `appointments.release` | `/appointments/release` | `holdId`, `reason`, `context` | | `appointments.commit` | `/appointments/commit` | `hold`, `orderId`, `context` | | `appointments.freeTimes` | `/appointments/free-times` | `query`, `context` | | `appointments.move` | `/appointments/move` | `move`, `context` | | `orderActions.` | `/order-actions/` | `order`, `context` | Respond with any `2xx` and the contract's JSON return value (empty body equals `{}`). Redirects and non-`2xx` responses count as unreachable. ### Request headers - `Orbcart-Request-Id`: new with every attempt, for diagnostics. Never deduplicate by it. - `Idempotency-Key`: present on mutating calls (`deliverOrder`, `reserve`, `release`, `commit`, `restock`, `appointments.move`, `orderActions`). A retry repeats the key, a new change gets a new one. Always scope idempotency storage by **endpoint + key**, because `release` and `commit` of the same hold share the hold's ID as their key. ### Retry or extension of a hold `inventory.reserve` and `appointments.reserve` name the hold by `hold.id` in the body. OrbCart reserves the same hold more than once: for the Quote, then again to keep it through the payment. Each reserve is a change of its own, with its own `Idempotency-Key`: | Call | `hold.id` | `Idempotency-Key` | Your endpoint | | ---------------------- | --------- | ----------------- | ---------------------------------- | | Reserve for a Quote | New | New | Holds it until `expiresAt` | | Extend for the payment | Same | New | Holds it until the new `expiresAt` | | Retry of either | Same | Same | Returns its stored answer | A reserve with other `references` or `lines` under the same `hold.id` is a new change too. Keep holds by `hold.id` and stored answers by endpoint and key. The key is derived from what the reserve asks for: the hold's ID, its `references` or `lines`, and `expiresAt`. OrbCart sends an extension again while the payment runs, and every repeat carries the same key over HTTP and through a Service Binding. An extension therefore applies once. Never read the hold's ID from the key. ## Verify an HTTP call Every HTTP contract call carries an RFC 9421 ES256 signature (`tag="orbcart-contract"`) verifiable against `/.well-known/jwks.json`. Service Bindings stay inside your Cloudflare account and are not signed. ```ts title="middleware/orders.ts" import { verifyRequest } from "@orbcart/admin"; export async function handle(request: Request): Promise { const { body, idempotencyKey } = await verifyRequest(request, { url: "https://commerce.clayandcrema.de", contract: "deliverOrder", }); const { order } = body; const reference = await erp.createSalesOrder(order, { idempotencyKey }); return Response.json({ reference }); } ``` `verifyRequest()` verifies the signature before parsing `body` against the named contract (for actions, pass `orderActions.`). Invalid signatures, wrong purposes (`wrong_purpose` for event signatures) or bodies over 1 MiB (`body_too_large`) throw `RequestVerificationError`: respond with `4xx`. ### Test signed calls locally ```ts import { signedContractCall } from "@orbcart/runtime/testing"; const request = await signedContractCall( env, "deliverOrder", "https://middleware.clayandcrema.de/edge/orders", { order }, ); ``` ## Customize | You want to | Do this | Default | | --------------------------------------- | ----------------------------------------------------------------- | ------------------ | | Verify behind a rewriting reverse proxy | Pass `target` (the exact URL OrbCart called) to `verifyRequest()` | Uses `request.url` | | Change the JWKS fetch timeout | Pass `keysTimeoutSeconds` to `verifyRequest()` | `5` seconds | | Increase a remote call's timeout | Pass `{ timeoutMs }` to `http()` or `service()` | 3s / 10s / 30s | ## Next steps | You want to | Read | | --------------------------------------------- | ------------------------------------------------------------ | | Verify incoming Order and Cart events | [Order events](/docs/cart/order-events) | | Build HTTP `offers` and `inventory` endpoints | [Prices and stock from your ERP](/docs/cart/erp-prices-and-stock) | | Send paid Orders to your ERP | [Send paid Orders to your ERP](/docs/cart/erp-order-handoff) | | Review OrbCart's security model | [Security](/docs/cart/security) | # SDKs & tools Which OrbCart package fits which job, where each key belongs, and how errors and retries work. All packages are TypeScript-first. While OrbCart is pre-release, install and import them from the workspace rather than npm. | You are building | Package | Start here | | --------------------------- | --------------------- | ------------------------------------------------------------ | | A storefront, app or agent | `@orbcart/client` | [Carts](/docs/cart/carts) | | A React checkout | `@orbcart/react` | [React checkout](/docs/cart/react-checkout) | | An ERP sync or support tool | `@orbcart/admin` | [Orders & refunds](/docs/cart/orders-and-refunds) | | Your commerce Worker | `@orbcart/runtime` | [Configuration](/docs/cart/configuration) | | A DHL pickup finder | `@orbcart/plugin-dhl` | [Shipping](/docs/cart/shipping#dhl-packstation-and-pickup-points) | React is optional. `@orbcart/client` works in any framework, on the server and in Node.js. ## Imports at a glance In your storefront: ```ts import { createCommerce, formatMoney, unitsIn, isSubmitted, CommerceError } from "@orbcart/client"; import { Checkout, CartProvider, useShoppingCart } from "@orbcart/react"; import "@orbcart/react/styles.css"; import { betterAuthIdentity } from "@orbcart/client/better-auth"; ``` On your server and in your commerce Worker: ```ts worker import { createAdmin } from "@orbcart/admin"; import { defineCommerce } from "@orbcart/runtime"; export * from "@orbcart/runtime/objects"; ``` Test helpers live in `@orbcart/runtime/testing` and `@orbcart/client/testing`. See [Testing](/docs/cart/testing). ## Which key goes where Keep the publishable key in the browser, the Cart token in a session cookie, and the secret key strictly on your server. See [HTTP API authentication](/docs/cart/http-api#authentication) for the full table. `createCommerce` rejects secret keys and `createAdmin` rejects publishable keys, catching mix-ups immediately during development. ## Errors Every SDK throws `CommerceError` when a request fails. Normal business outcomes, such as a declined card or `quote_changed`, are return values rather than exceptions. When using the `cart.checkout()` store: - **Cart actions** (`add`, `setQuantity`, `remove`, `enterCode`) throw `CommerceError` so you can display the error next to the item or code field. - **Checkout actions** (`start`, `submitDetails`, `setShipping`, `placeOrder`) never throw refusals: they write them to `state.notice`. See [Handle errors](/docs/cart/carts#handle-errors) and [Error codes](/docs/cart/errors). ## Buyer-facing messages Use `describe(locale)` to turn error codes, payment methods and cart changes into localized sentences in English, German, French and Dutch. Never display raw API `detail` strings to buyers. ```ts import { describe } from "@orbcart/client"; const words = describe("de-DE"); words.problem("code_invalid"); // localized sentence for the buyer words.paymentMethod("ideal"); // "iDEAL | Wero" words.change(change); // explains one entry from cart.changes ``` ## Automatic retries The SDKs attach a fresh `Idempotency-Key` to every mutation and retry transient network failures automatically, so retries never add an item twice or double-charge ([How it works](/docs/cart/how-it-works#when-something-goes-wrong)). You only need to supply your own idempotency key for server-side refunds that must survive a backend restart. ## Next steps | You want to | Read | | -------------------------------- | -------------------------------------- | | Build a Cart in any framework | [Carts](/docs/cart/carts) | | Drop in the React checkout | [React checkout](/docs/cart/react-checkout) | | Call the HTTP API without an SDK | [HTTP API](/docs/cart/http-api) | | Look up an error code | [Errors](/docs/cart/errors) | # Security How OrbCart handles keys, tokens, webhooks, rate limits and personal data, plus what to verify before going live. In OrbCart, access comes strictly from the credential presented, never from what a caller claims. A key fixes the Environment and Channel, a token opens one Cart or one Order, and every binding number is computed on the server. ## The trust model ### Browser and API access - **Clients send intent, never prices.** Requests carry references, quantities, addresses and choices. Prices, tax, shipping, discounts and totals come only from your systems and the server. Unexpected fields are rejected. - **Keys fix the context.** A publishable key belongs to one Channel in one Environment. A `live` key against a `test` Worker is refused. - **Tokens are scoped to one record.** A Cart token opens one Cart; an Order token reads one Order. All keys and tokens have 256 random bits, are stored only as SHA-256 hashes, and are compared in constant time. - **Credentials travel in headers.** The API reads credentials from `Authorization`, never from URLs. Only two links carry a secret by design: the read-only [Order link](/docs/cart/order-page) and an agent's short-lived [continue link](/docs/cart/agents#build-the-continue-page). - **Browser calls require an allowed origin.** Browsers may call only from the Channel's `origins` (plus `localhost` in `test`). Secret keys are always refused from browser contexts. ### Payments and webhooks - **Card data never touches your Worker.** Payment fields come from the provider and transmit card numbers straight to the provider. OrbCart stores only provider references, keeping heavy PCI scope with the provider. - **Every webhook is verified first.** Stripe, Adyen and PAYONE webhooks require a valid signature. PayPal webhooks are confirmed through PayPal's API. Mollie webhooks are verified by fetching the payment back with your API key. Every webhook is stored before returning `200`, so redeliveries are no-ops. - **Retries never double-charge.** Every mutation carries an `Idempotency-Key`, and provider calls use keys derived from the Payment ID. Unclear outcomes are resolved by polling, never guessed ([How it works](/docs/cart/how-it-works#when-something-goes-wrong)). ### Outgoing calls, agents and isolation - **Outgoing calls are signed.** Quotes, [Order events](/docs/cart/order-events#verify-a-delivery) and calls to your [HTTP contracts](/docs/cart/remote-contracts#verify-an-http-call) carry an ES256 signature from the Environment. Public keys are published at `/.well-known/jwks.json`. Service Bindings stay inside your Cloudflare account and need no signature. - **Outgoing URLs must be public HTTPS.** HTTP contracts and event receivers must use `https` on port `443` with a public hostname (no IP addresses or private names). - **AI agents sign every request.** UCP checkout calls require an HTTP message signature verified against the agent platform's published keys. Agents follow the exact same rules as browsers. - **Environments are isolated.** `test` and `live` run as separate Workers with separate keys, provider accounts and data. ## Keys and tokens | Credential | Format | Where to keep it | What it opens | | --------------- | ------------------- | ------------------------------ | ------------------------------------------------------------------- | | Publishable key | `pk_test_…` | Browser, app or agent | Creating Carts in its Channel. | | Cart token | `cart_…_secret_…` | Buyer's session cookie | One Cart: read, update, quote and pay. | | Order token | `ord_…_secret_…` | Order link sent to buyer | One Order, read-only. | | Buyer ID token | Your identity JWT | `OrbCart-Buyer` header | That buyer's own Carts and Orders. | | Secret key | `sk_test_…` | Server secret only | Full Admin API for the Environment. | | Staff token | 15-minute EdDSA JWT | Admin memory (never persisted) | Admin API routes permitted by the staff member's areas. | | Root secret | 32 random bytes | Wrangler secret on the Worker | Seals signing keys and hand-off codes. Never rotate without a plan. | Keep the Cart token in an `HttpOnly`, `SameSite=Lax` session cookie. Never put it in URLs, analytics events or logs. ## Personal data - **Excluded from logs, IDs and events.** The Worker logs one line per request (route, status, code, duration) with no bodies, headers or addresses. Events reference only the Order ID; your receiver loads details with the secret key. - **Excluded from Postgres lists.** The Order list in Postgres holds no names, addresses or emails. - **Stored in the EU.** Durable Objects run in the EU jurisdiction unless you configure another. - **Auto-deleted when unused.** Abandoned Carts without an Order are deleted with all personal details after 180 days of inactivity (`expiresAfterDays`). - **Buyer ID tokens are not stored.** OrbCart records only the signed-in buyer's issuer and subject. ## Staff access in the admin OrbCart's admin screens live under **Orders** and **Settings** in the OrbCommerce Admin. Staff sign in once at the admin, which forwards calls to your Worker over a Service Binding using short-lived 15-minute EdDSA tokens (`audience: "orbcommerce-staff"`, verified against `${STAFF_ISSUER}/api/auth/jwks`). | Area | View | Edit | | ----------- | ---------------------------------------------------- | ---------------------------------------------------------- | | Orders | Orders and Carts with buyer details; search by email | Refunds, gift card redemptions/prints, withdrawal attaches | | Connections | Events, receivers; Orders and Carts without buyer | Resend and replay events, pause receivers | Any staff member can view the Environment's configuration. Calls outside a person's granted areas return `403 not_permitted` naming the required `area` and `level`. Staff with `orders` access can also be scoped to specific Locations (for example, desk staff may redeem gift cards only at their assigned Locations, whereas merchant-wide staff can access every Location and mint printable gift card links). Removing a staff member ends their sessions. ## Rate limits Endpoints open to anonymous callers enforce strict rate limits using HMAC-keyed counters (never storing raw emails or IP addresses): | Action | Limit | Error response | | ------------------- | ----------------------------------- | ---------------------------------------------- | | Withdrawal request | 5 per email/min, 20 per IP/min | `429 rate_limited` + `Retry-After` | | Gift card lookup | 10 per IP/min (checkout and desk) | `429 rate_limited` or `gift_card_rate_limited` | | Discount code entry | 10 per Cart / 10 min, 30 per IP/min | `429 code_rate_limited` | Two details to keep in mind: - **Forward client IPs on Service Bindings.** Limits read `CF-Connecting-IP`. When calling the Worker through a Service Binding from your server, forward the visitor's IP so shoppers do not share one counter. - **Duplicate withdrawals are deduplicated.** Repeating the same withdrawal within 10 minutes returns the original submission without sending another email. Other routes do not enforce built-in rate limits yet: put a Cloudflare zone rate-limiting rule in front of your Worker. Key management via `orbcart keys issue`, `revoke` and `status` works in `test` today, while `live` key issuance and revocation are not built yet; keep your `live` secret key on a single server. ## Go-live checklist - [ ] `live` runs in its own Worker with its own `ROOT_SECRET` and live provider keys. - [ ] All secrets are stored via [`wrangler secret put`](/docs/run/deployment#set-root_secret), never in code or `wrangler.jsonc`. - [ ] Every Channel's `origins` lists only your production storefront origins. - [ ] The secret key stays on your server; the browser receives only `ORBCART_URL` and the publishable key. - [ ] Cart tokens live in `HttpOnly` session cookies, never in URLs, analytics or logs. - [ ] Event receivers and HTTP contracts verify every call with `verifyEvent()` or `verifyRequest()`. - [ ] Provider webhooks point to the live Worker with matching secrets. - [ ] `STAFF_ISSUER` points to your admin sign-in, and staff only hold the areas they need. - [ ] Cloudflare [cart creation rate rules and checkout challenges](/docs/run/deployment#protect-cart-creation-and-checkout) are enabled. For the full launch checklist (including tax and legal texts), see [Deployment](/docs/run/deployment#checklist-before-real-money). ## Next steps | You want to | Read | | ------------------------------ | ----------------------------------------------- | | Deploy OrbCart to Cloudflare | [Deployment](/docs/run/deployment) | | Rotate credentials safely | [Credential rotation](/docs/run/credential-rotation) | | Verify incoming Order events | [Order events](/docs/cart/order-events) | | Verify incoming HTTP contracts | [Remote contracts](/docs/cart/remote-contracts) | # Shipping Configure delivery methods, weight tiers, store pickup via Catalog Locations, carrier rates and DHL Packstation. Shipping rules live on each Channel, keyed by ISO country code. Countries not listed return `ship_to_unsupported`. ## Declare delivery methods ```ts title="src/worker.ts" members="ChannelConfig" shipping: { DE: [ { id: "standard", title: "Standard (DHL)", price: 495, deliveryTime: "2-4 business days" }, { id: "express", title: "Express", price: 1290, deliveryTime: "1 business day" }, ], AT: [{ id: "standard", title: "Standard", price: 790, deliveryTime: "3-5 business days" }], }, ``` Prices are in minor units of the Channel's currency (`495` is €4.95). Until the buyer chooses a method, OrbCart selects the cheapest delivery once the country is known (single-country Channels know it immediately; pickup is never preselected): ```ts browser current.shippingMethods; // [{ id: "standard", ... }, { id: "express", ... }] current.shipping; // { id: "standard" } await cart.setShipping("express"); ``` ### Rule options | Option | Required | Example | Purpose | | -------------- | -------- | ------------------ | --------------------------------------------------------------- | | `id` | Yes | `"express"` | Unique ID per country. | | `title` | Yes | `"Express"` | Label shown to buyers (single string or per-language map). | | `price` | Yes | `1290` | Fixed minor units (`0` for free), weight tiers or `"quoted"`. | | `deliveryTime` | No | `"1 business day"` | Informational text (single string or per-language map). | | `requires` | No | `["phone"]` | Contact fields required only when this method is chosen. | | `excludes` | No | `["fragile"]` | Offer restrictions this method cannot carry. | | `only` | No | `["bulky"]` | Offered only when at least one Line carries these restrictions. | ### In several languages Pass a language map to `title` and `deliveryTime`. OrbCart matches the client's `language`, then its base language (`en-GB` → `en`), then the first entry: ```ts members="ChannelConfig" shipping: { DE: [ { id: "standard", title: { de: "Standardversand (DHL)", en: "Standard (DHL)" }, price: 495, deliveryTime: { de: "2-4 Werktage", en: "2-4 working days" }, }, ], }, ``` ## Weight tiers, restrictions and free shipping ### Price by weight Pass tiers lightest-first. Weight is summed from each Offer's `shipping.weightInGrams` (missing weights count as `0` and log `weight_missing`). Omit `upToGrams` on the final tier to cover any weight; capped methods drop out with `reason: "too_heavy"`: ```ts items="ShippingRuleConfig" { id: "standard", title: "Standard (DHL)", price: [ { upToGrams: 2000, price: 495 }, { upToGrams: 10000, price: 695 }, { price: 995 }, ], }, { id: "express", title: "Express", price: [{ upToGrams: 10000, price: 1290 }] }, ``` ### Keep restricted goods off a method Return `shipping.restrictions` from your `offers` contract, then exclude them from parcel rules or restrict freight with `only`: ```ts members="OfferedReference" shipping: { weightInGrams: 3600, restrictions: ["bulky"] }, ``` ```ts items="ShippingRuleConfig" { id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] }, { id: "freight", title: "Freight", price: 4900, requires: ["phone"], only: ["bulky"] }, ``` Excluded methods disappear from `shippingMethods` and appear in `cart.changes` as `shipping_unavailable`. If no method remains, quoting fails with `not_shippable`. ### Digital goods, zones and free shipping - **Digital goods:** omit `shipping` on the Offer. Carts with only digital goods need no delivery address or shipping method. - **Price zones:** group countries with a small helper: ```ts function zone(countries: string[], price: number, deliveryTime: string) { const standard = { id: "standard", title: "Standard (DHL)", price, deliveryTime }; return Object.fromEntries(countries.map((country) => [country, [standard]])); } ``` ```ts continues members="ChannelConfig" shipping: { DE: [standard, express], ...zone(["BE", "NL", "LU", "DK"], 890, "3-5 business days"), ...zone(["FR", "IT", "ES", "SE"], 990, "4-6 business days"), }, ``` - **Free shipping from €50:** declare a shipping [discount](/docs/cart/discounts) naming the eligible methods so express stays paid: ```ts members="ChannelConfig" discounts: [ { id: "free-shipping", scope: "shipping", percentage: 100, minimumSubtotal: 5000, methods: ["standard"] }, ], ``` ## Collect at a store (pickup) Reference an authoritative [OrbCatalog Location](/docs/catalog/storefront#locations) by ID and attach the `pickupLocations` contract: ```ts members="ChannelConfig" shipping: { DE: [ { id: "standard", title: "Delivery", price: 495 }, { type: "pickup", id: "collect-roastery", title: "Roastery pickup", location: "loc_roastery0001", price: 0 }, ], }, ``` ```ts members="CommerceConfig" import { http } from "@orbcart/runtime"; pickupLocations: http((vars) => `${vars.get("CATALOG_URL")}/orbcart/pickup-locations`), ``` Only open, pickup-enabled Locations assigned to the Channel (with matching country) are offered. Carts cache Locations for 1 minute; Quotes and payment acceptance always re-check Catalog's primary and freeze the selected Location into the signed Quote and Order. Pickup requires only a country, not a delivery street address, and does not perform per-store stock allocation. ## Live rates from your carrier or ERP Set `price: "quoted"` on a rule and attach `shippingRates` (a function, `http()` or `service()`) on the Channel: ```ts title="src/worker.ts" members="ChannelConfig" shipping: { DE: [ { id: "standard", title: "Standard (DHL)", price: 495, excludes: ["bulky"] }, { id: "freight", title: "Freight", price: "quoted", requires: ["phone"], only: ["bulky"] }, ], }, shippingRates: async ({ shipTo, lines, methods, currency }, { signal }) => { const rates = await forwarder.rates( { postalCode: shipTo.postalCode, pieces: lines.reduce((sum, line) => sum + line.quantity, 0), grams: lines.reduce((sum, line) => sum + (line.weightInGrams ?? 0) * line.quantity, 0), }, { signal }, ); return methods.flatMap((id) => { const rate = rates[id]; return rate ? [{ id, price: { amount: rate.cents, currency }, expiresAt: rate.validUntil }] : []; }); }, ``` - Called only when quoting a Cart with a matching `"quoted"` method; omitted methods are not offered. - Retries once on failure, then returns `provider_unavailable` without guessing a price. - The Quote expires no later than the earliest rate `expiresAt`. - Not supported yet: quoted pickup prices, carrier-invented method IDs, or quoted methods in AI agent options before quoting. ## DHL Packstation and pickup points `@orbcart/plugin-dhl` adds a German Packstation and post-office map picker to ``: ```tsx browser import { DhlDeliveryAddress, DhlPickupProvider } from "@orbcart/plugin-dhl/react"; import "@orbcart/plugin-dhl/styles.css"; ; ``` Proxy the search on your server with your DHL Location Finder Unified API Key (never the API Secret): ```ts title="app/routes/pickup.locations.ts" import { env } from "cloudflare:workers"; import { PickupSearch } from "@orbcart/plugin-dhl"; import { findDhlLocations } from "@orbcart/plugin-dhl/server"; export async function action({ request }: { request: Request }) { if (request.headers.get("Origin") !== new URL(request.url).origin) { return new Response(null, { status: 403 }); } const search = PickupSearch.safeParse(await request.json()); if (!search.success) return Response.json({ error: "invalid_query" }, { status: 400 }); const result = await findDhlLocations({ apiKey: env.DHL_API_KEY, search: search.data, signal: request.signal, }); const headers = { "Cache-Control": "private, no-store" }; return result.status === "success" ? Response.json({ locations: result.locations }, { headers }) : Response.json({ error: result.error }, { status: 503, headers }); } ``` ## Customize | You want to | Do this | Default | | ------------------------------------- | ------------------------------------------------------------- | -------------------------- | | Show a delivery estimate | Set `deliveryTime` on the rule (and on Offers for slow goods) | None shown | | Offer free shipping above a threshold | Add a [discount](/docs/cart/discounts) with `scope: "shipping"` | Shipping is charged | | Price from your carrier or ERP | Set `price: "quoted"` and attach `shippingRates` | Fixed or weight-tier price | | Add a pickup-point map picker | Pass `deliveryAddress={DhlDeliveryAddress}` to `` | Standard address fields | ## Next steps | You want to | Read | | ------------------------------------------------ | ------------------------------------------ | | Configure discounts and free shipping | [Discounts](/docs/cart/discounts) | | Return weights and restrictions from Offers | [Offers](/docs/cart/offers) | | Connect remote HTTP or Service Binding contracts | [Remote contracts](/docs/cart/remote-contracts) | | Build your own checkout plugin | [Extend OrbCart](/docs/cart/extend) | # Project status What works in OrbCart today, what is actively being built, and what comes next. Status as of 14 November 2026. OrbCart is pre-release: packages are not published to npm yet and the repository is private. ## Works today ### Buying and checkout - Carts, signed Quotes and Orders through one API for storefronts and AI agents. - Framework-free client SDK (`@orbcart/client`), React checkout kit (`@orbcart/react`) and server-side Admin SDK (`@orbcart/admin`). - Generated [OpenAPI 3.2 description](/docs/cart/http-api#endpoints) for building clients in any language. - Express checkout with Apple Pay, Google Pay and PayPal, including 3-D Secure dialogs. - Waiting state for slow or asynchronous payments that transitions to the Order once confirmed. - Signed-in buyers through your own identity provider, with one Cart across devices and buyer Order history. - Typed custom fields on Lines and Carts ([Extensions](/docs/cart/extensions)). - Per-Channel [legal texts](/docs/cart/configuration#legal) linked at checkout and recorded in every Quote. ### Markets, pricing and systems - Live Offers from your systems, stock checks and reservations, and reliable Order hand-off with retries. - Multiple markets with separate currencies (such as EUR and CHF). - Built-in EU VAT for all 27 member states from daily EU rates, plus a custom `tax` contract for other regions. - Per-country shipping rules with exclusions, weight tiers, freight handling, store pickup and a DHL Packstation finder. - Per-Offer delivery times when specific items ship slower than standard parcels. - Discount codes, automatic promotions, free shipping per method, redemption limits and gift cards. ### Payment providers | Provider | Ready today | Waiting on sandbox proof | | ---------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- | | Stripe | Card, Apple Pay, Google Pay, Klarna, iDEAL, Bancontact, EPS, P24, TWINT | None | | Adyen | Card, Apple Pay, Google Pay, Klarna, iDEAL, Bancontact, TWINT, Pay by Bank | iDEAL return/webhook, Google Pay test card | | Mollie | Card, iDEAL, Bancontact, TWINT, Pay by Bank | Klarna, EPS, P24, Apple Pay, Google Pay, public webhook | | PAYONE | Card | Card refund confirmation, iDEAL, EPS, Pay by Bank, wallets | | PayPal | Standard and express review | None | | Amazon Pay | Express button, hosted changes, storefront review, capture and refunds | Real Amazon sandbox acceptance (uses durable polling, no IPN) | Swapping a payment method's provider is a single string change in your Channel configuration. ### After the purchase and admin - Shareable [order page](/docs/cart/order-page) for every buyer, including guests, via a secret Order link. - Order reads, search, fulfillment tracking, acknowledgment and partial refunds (including bundle parts). - AI agent checkout over UCP, with AP2 mandates and signed UCP order updates. - Automatic deletion of abandoned Carts and their personal data after 180 days of inactivity. - Signed Order events and remote HTTP/Service Binding contracts with `verifyEvent()` and `verifyRequest()`. - OrbCommerce Admin **Orders** area: overview, order actions, refunds, withdrawals, discounts, gift cards, checkout funnel metrics and read-only environment settings. ## In progress - **Mollie wallets and webhooks:** Apple Pay, Google Pay and public webhook verification. - **Adyen final sandbox proofs:** iDEAL return/webhook and Google Pay test-card verification. - **Admin Orders expansion:** Editable settings in the admin, attention queues for payments and integration backlogs. ## Planned next - **Legally complete checkout:** Withdrawal button on the order page and structured receipt data for confirmation emails. - **More payment providers:** German invoice payments, followed by Unzer. - **One-command setup:** `orbcart deploy` for environment provisioning and `npm create orbcart` for scaffolding. - **More framework examples:** SvelteKit, and Laravel with Inertia and Vue. Licensed under Apache 2.0. A managed cloud offering is a future direction with no pricing or launch commitments today. # Track storefront events Send cart and checkout events to Google Tag Manager or your own analytics endpoint without slowing down the storefront. Pass an `events` stream when creating your OrbCart client. The cart and checkout emit structured events in the background without blocking user interactions. ```ts import { createEvents } from "@orbcommerce/storefront-events"; import { createCommerce } from "@orbcart/client"; import { toDataLayer } from "@orbcart/client/ga4"; export const events = createEvents({ ga: toDataLayer() }); export const commerce = createCommerce({ url, key, events }); ``` Create **one event stream per page**, not one per component or cart. The GA4 adapter pushes events to `window.dataLayer`; your storefront still loads Google Tag Manager and handles consent. ## How events are emitted - **React checkout kit:** Checkout steps, forms and validation refusals report automatically. `` inside `` reports `cart.viewed` when it enters the viewport. - **Standalone components:** Outside ``, pass `viewCart={bag.viewCart}` to `` and `tellInteraction={bag.tellInteraction}` to standalone forms. - **Custom storefronts:** Call `checkout.viewCart?.(cart)` once your custom cart view is visible. ## Built-in events | Event | When it fires | GA4 event | | ------------------------------------------------------ | ------------------------------------------------------- | ------------------- | | `cart.viewed` | The storefront shows the cart | `view_cart` | | `cart.line_added` | An item addition is confirmed | `add_to_cart` | | `cart.line_removed` | An item removal is confirmed | `remove_from_cart` | | `cart.line_changed` | A quantity change is confirmed | | | `cart.code_entered`, `cart.gift_card_entered` | A discount or gift card code is tried (result only) | | | `checkout.started` | Checkout opens with an active cart | `begin_checkout` | | `checkout.step_entered`, `checkout.step_completed` | A checkout step is shown or saved | | | `checkout.shipping_chosen` | The runtime confirms the chosen shipping method | `add_shipping_info` | | `checkout.payment_chosen` | The buyer picks a payment method or submits the default | `add_payment_info` | | `checkout.refused` | The runtime refuses a checkout action | | | `checkout.order_requested` | The buyer submits a Quote for payment | | | `checkout.payment_failed` | A payment fails or is cancelled | | | `checkout.ordered` | The purchase produces an Order | `purchase` | | `product.viewed` | Your storefront shows a product | `view_item` | | `product_list.viewed` | Your storefront shows a product list | `view_item_list` | | `product.selected` | A shopper selects a product from a list | `select_item` | | `ui.pressed`, `ui.opened`, `ui.closed`, `ui.submitted` | A named button, disclosure or form is used | | | `ui.rejected` | A form validation refusal occurs | | A closed tab drops unsent browser events. Always use [signed Order events](/docs/cart/order-events) on your server for fulfillment, accounting and reconciliation. ## Customize | You want to | Do this | Default | | ------------------------------------ | ---------------------------------------------------- | ------------------ | | Track clicks on your own UI elements | Add `data-part` and `data-scope` attributes | Only kit elements | | Report product views and lists | Call `events.tell({ type: "product.viewed", data })` | Not reported | | Filter events or gate on consent | Pass `{ run, types, when }` to `createEvents()` | All events sent | | Rename GA4 events or add custom ones | Pass `names` and `map` to `toDataLayer()` | Standard GA4 names | ### Track your own UI elements and products Use stable `data-part` names rather than translated labels. Wrap sections in `data-scope` to distinguish the same part in different places (such as a drawer vs. a full page): ```html
``` That click reports `part: "brew-guide"` and `path: ["product-page", "brew-guide"]`. For custom dialogs, emit `ui.opened` manually with `{ from: trigger }` to inherit the path. On product pages, emit `product.viewed` once the product is displayed (prices use decimal major units): ```ts continues events.tell({ type: "product.viewed", data: { reference: "DAYBREAK-250G-BEANS", title: "Daybreak · 250 g · Whole bean", price: { value: 12.9, currency: "EUR" }, }, }); ``` ### Filter events and respect consent A listener can be a function or an object with `run`, `types` (exact names or `prefix.*` globs) and `when` (a synchronous consent check): ```ts import { createEvents, toEndpoint } from "@orbcommerce/storefront-events"; const events = createEvents({ warehouse: { run: toEndpoint("https://collect.example.com/events"), types: ["cart.*", "checkout.*", "ui.rejected"], when: () => banner.allows("analytics"), }, }); // Flush held events whenever consent changes. banner.onChange(() => events.flush()); ``` How `when` and delivery behave: - **Consent values:** Return `true` to send, `false` to drop, or `undefined` to buffer in memory until the visitor decides. - **Collector payload:** Your endpoint receives a JSON array of events with `id`, `type`, `time`, `sequence`, `source` and (for cart events) `subject`. Deduplicate retries by `id` and order by `sequence`. - **Privacy and timeouts:** OrbCart never sends buyer-entered values, tokens or raw discount codes (GA4 receives the discount ID). Network listeners are aborted after 5 seconds; keep custom listeners async so they do not block the main thread. ### Rename GA4 events or add custom events Declare your custom event types once and pass them to both `createEvents` and `toDataLayer`. The prefixes `ui`, `product`, `product_list`, `cart` and `checkout` are reserved. ```ts import { createEvents } from "@orbcommerce/storefront-events"; import { toDataLayer } from "@orbcart/client/ga4"; type ShopEvents = { "wishlist.added": { reference: string } }; const events = createEvents({ ga: toDataLayer({ names: { view_cart: "shop_cart_opened" }, map: { "wishlist.added": ({ data }) => ({ event: "add_to_wishlist", ecommerce: { items: [{ item_id: data.reference }] }, }), }, }), }); events.tell({ type: "wishlist.added", data: { reference: "HAND-GRINDER" } }); ``` ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------------------- | | Add the React checkout kit | [React checkout](/docs/cart/react-checkout) | | Receive reliable backend Order events | [Receive signed order events](/docs/cart/order-events) | # Tax Configure EU daily VAT rates via eu-standard, handle on-site workshop services, or plug in your own tax function. Each Channel has exactly one tax source. OrbCart never guesses rates or falls back between sources: if tax cannot be determined for a Line or territory, quoting fails cleanly. | Channel setting | Best for | Rate source | | -------------------- | ----------------------------------------------------- | -------------------------------------------------------- | | `tax: "eu-standard"` | EU B2C shops | Daily rates imported from EU TEDB (quoted at Quote time) | | `tax: yourFunction` | Non-EU markets (e.g. CH), B2B or external tax engines | Your function or HTTP contract | | _(omitted)_ | EU B2C shops wanting cart-level estimates | Bundled EU VAT table (updates with OrbCart) | ## Set up EU standard VAT ### Enable `eu-standard` on the Channel ```ts title="src/worker.ts" members="Channels" de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE", tax: "eu-standard", shipping: { DE: [standard], AT: [standard], FR: [standard] }, }, ``` ### Add the Cron trigger ```jsonc title="wrangler.jsonc" "triggers": { "crons": ["*/15 * * * *"] } ``` Imports run once daily around 20:00 UTC; the 15-minute schedule only retries failed imports (at 15, 30, 60 and 120 minutes). ### Prime and verify after first deploy ```sh pnpm exec orbcart tax sync --env test pnpm exec orbcart tax status --env test ``` Check that `state` is `ready` or `waiting` and `availableOn` includes today. ### Tax categories Every Offer declares a `taxCategory` naming a national rate tier: | Category | Meaning | | --------------- | --------------------------------- | | `standard` | National standard rate | | `reduced` | Lower reduced rate (at least 5%) | | `intermediate` | Higher of two reduced rates | | `super_reduced` | Rate below 5% | | `zero` | 0% with right to deduct input VAT | | `exempt` | 0%, exempt from VAT | If a country lacks the requested category (or TEDB has no reduced-rate rows for it), quoting fails rather than falling back to `standard` (except Denmark, which taxes all categories at 25%). Non-EU destinations fail at startup under `eu-standard`. Special territories outside the EU VAT area (Heligoland, Büsingen, Jungholz, Mittelberg, Canary Islands, Ceuta, Melilla, French overseas departments, Livigno, Campione d'Italia, Madeira, Azores, Åland, Mount Athos, Kyrenia) are rejected by postal code. ## Work performed at your Location Stand-alone B2C work on a consumer's movable goods physically performed at your Location (Art. 54(2)(b) VAT Directive, such as a grinder service in Munich) is taxed in the **Location's country** regardless of where the buyer lives. Mark the Offer with `supply` (leaving `shipping` out) using the Location's `id`, `name` and `address` from `/v1/locations`: ```ts value="Partial" { reference: "GRINDER-SERVICE", /* … */ supply: { type: "b2c_work_on_movable_goods", location: { id: "loc_roastery0001", name: "Clay & Crema Roastery Munich", address: { line1: "Sendlinger Straße 12", postalCode: "80331", city: "München", country: "DE" }, }, }, } ``` Use a custom tax function instead of `eu-standard` for B2B reverse charge, mail-in repairs, courses/events, food & drink or other services with special place-of-supply rules. ## Write your own tax function For non-EU markets (such as Switzerland), B2B rules or third-party tax engines, pass a `TaxContract` function (or `http()` / `service()`): ```ts title="src/swiss-vat.ts" import type { TaxAmount, TaxContract, TaxDraft } from "@orbcart/runtime"; const rates = new Map([ ["standard", 81], ["reduced", 26], ["zero", 0], ]); export const swissVat: TaxContract = (draft) => ({ lines: draft.lines.flatMap(({ id, amount, taxCategory, deposit }) => { const tenths = rates.get(taxCategory); const depositRate = deposit && rates.get(deposit.taxCategory); return tenths === undefined || (deposit !== undefined && depositRate === undefined) ? [] : [ { id, taxes: [vat(amount.amount, taxCategory, tenths, draft)], ...(deposit && depositRate !== undefined && { deposit: [vat(deposit.amount.amount, deposit.taxCategory, depositRate, draft)], }), }, ]; }), ...(draft.shipping && { shipping: [vat(draft.shipping.amount.amount, "standard", 81, draft)], }), }); function vat(amount: number, taxCategory: string, tenths: number, draft: TaxDraft): TaxAmount { const { country, currency, pricesIncludeTax } = draft; const tax = pricesIncludeTax ? Math.round((amount * tenths) / (1000 + tenths)) : Math.round((amount * tenths) / 1000); return { percentage: String(tenths / 10), country, taxCategory, taxableAmount: { amount: pricesIncludeTax ? amount - tax : amount, currency }, amount: { amount: tax, currency }, rule: "ch-mwst@2024-01-01", }; } ``` ### Validation checks OrbCart enforces - Every Line in `draft.lines` must be returned by `id` (and `shipping` when charged). - Lines with a refundable `deposit` must return a separate `deposit` tax array matching `line.deposit.amount`. - All amounts must be integer minor units in `draft.currency`. - Gross prices: `taxableAmount + amount === discountedAmount`. Net prices: `taxableAmount === discountedAmount`. ## Customize | You want to | Do this | Default | | ------------------------------------- | ----------------------------------------------------- | --------------------- | | Round tax per Line for your ERP | Set `taxRounding: "line"` on the Channel | `"total"` | | Tax non-EU or B2B markets | Pass a custom `TaxContract` function or `http()` | Built-in EU VAT table | | Seed EU VAT in Vitest without network | Call `publishDailyRates()` ([Testing](/docs/cart/testing)) | Fetches TEDB | ## Next steps | You want to | Read | | ---------------------------------------------- | ----------------------------------------------------- | | Connect signed-in buyers with your login | [Signed-in buyers](/docs/cart/identity) | | Supply `taxCategory` and `deposit` from Offers | [Offers](/docs/cart/offers) | | Host your tax engine over HTTP | [Contracts in another system](/docs/cart/remote-contracts) | | Run `orbcart tax sync` and `tax status` | [CLI](/docs/cart/cli) | # Test a purchase Run a complete Vitest checkout against your Worker with fakeStripe, read the Order back, and prove double clicks buy once. This recipe runs a real checkout against your commerce Worker in Vitest, faking only Stripe, and verifies both Order creation and double-click idempotency. **Prerequisites:** a commerce Worker with `card: "stripe"` and the `vitest.config.ts` from [Testing](/docs/cart/testing#configure-vitest-for-your-worker). ## 1. Write the purchase test ```ts title="test/purchase.test.ts" import { env, exports } from "cloudflare:workers"; import { createAdmin } from "@orbcart/admin"; import { createCommerce } from "@orbcart/client"; import { fakeStripe, issueKey, publishDailyRates } from "@orbcart/runtime/testing"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; const url = "https://commerce.test"; const worker = (request: Request) => exports.default.fetch(request); const shipTo = { name: "Anna Berg", line1: "Bergstraße 12", postalCode: "10115", city: "Berlin", country: "DE", }; const byCard = { payment: "card", instrument: { confirmationToken: "ctoken_test" } }; beforeEach(async () => { vi.stubGlobal("fetch", fakeStripe({ created: { status: "requires_capture" } }).fetch); const today = new Date().toISOString().slice(0, 10); await publishDailyRates(env, { on: today, rates: { DE: { standard: "19", reduced: ["7"] } } }); }); afterEach(() => { vi.unstubAllGlobals(); }); it("buys coffee with a card once and reads the Order back", async () => { const key = await issueKey(env, { kind: "publishable", channel: "de" }); const commerce = createCommerce({ url, key, fetch: worker }); const cart = await commerce.cart(); await cart.add("DAYBREAK-250G-BEANS"); const quote = await cart.quote({ shipTo, contact: { email: "anna@example.com" } }); const result = await quote.accept(byCard); if (result.status !== "ordered") throw new Error(`Expected an Order, got ${result.status}.`); expect(result.order.quote.totals.total).toEqual(quote.totals.total); // Double-clicking returns the exact same Order. expect(await quote.accept(byCard)).toMatchObject({ status: "ordered", order: { id: result.order.id }, }); const admin = createAdmin({ url, key: await issueKey(env, { kind: "secret" }), fetch: worker }); const order = await admin.orders.get(result.order.id); expect(order.payment).toMatchObject({ method: "card", provider: "stripe" }); }); ``` Run it with: ```sh pnpm exec vitest run test/purchase.test.ts ``` ## 2. Route ERP fetches alongside `fakeStripe` When your `offers` or `deliverOrder` contracts also call `fetch`, forward Stripe requests to `fakeStripe` and everything else to your ERP fake: ```ts import { vi } from "vitest"; import { fakeStripe } from "@orbcart/runtime/testing"; const stripe = fakeStripe({ created: { status: "requires_capture" } }); vi.stubGlobal("fetch", (input: RequestInfo | URL, init?: RequestInit) => new URL(input instanceof Request ? input.url : input).host === "api.stripe.com" ? stripe.fetch(input, init) : fakeErp(input, init), ); ``` ## Next steps | You want to | Read | | ------------------------------------------ | -------------------------------------------------------------------------------------- | | Test 3-D Secure webhooks and UI components | [Testing](/docs/cart/testing) | | Test free shipping and discount codes | [Free shipping and a welcome code](/docs/cart/free-shipping-and-codes#3-prove-it-in-a-test) | | Test sandbox cards manually in a browser | [Test payments](/docs/cart/test-payments) | # Test payments Sandbox card numbers, 3-D Secure passwords, Tink bank logins and wallet accounts for testing checkout. All credentials below are public sandbox test values provided by Stripe, Adyen, PayPal and Amazon Pay. Nothing is charged. Remember that regional methods only appear when your billing address and currency match ([Payment providers](/docs/cart/payments#methods-and-providers)). ## Cards | Provider | Succeeds | Triggers 3-D Secure | Decline | Expiry & CVC | | -------- | --------------------- | --------------------- | -------------------------- | ----------------------------------------- | | Stripe | `4242 4242 4242 4242` | `4000 0027 6000 3184` | `4000 0000 0000 0002` | Any future date, any 3 digits | | Adyen | `4111 1111 4555 1142` | `4917 6100 0000 0000` | Cardholder name `DECLINED` | `03/30`, `737` (3DS password: `password`) | Check `payments.card` on your Channel or inspect `quote.paymentMethods` to see which provider is active. ## Bancontact - **Billing country / currency:** Belgium (`BE`), `EUR`. - **Card number:** `6703 4444 4444 4449`, expiry `03/30` (no security code). - **3-D Secure password:** `password`. ## Pay by Bank (Adyen / Tink) Choose **Tink Demo Bank → Open banking → Password and OTP With Templates**, enter a test user below, pick **2FA App Code**, and confirm twice with `1234`: | Country / outcome | Username | Password | | -------------------- | ----------- | -------- | | Germany (DE) | `u83188312` | `zhx571` | | France (FR) | `u77894411` | `mzw990` | | Finland (FI) | `u06516046` | `kam413` | | Login refused | `u92721594` | `nbs589` | | Temporary bank error | `u91902655` | `jtx720` | ## PayPal, Amazon Pay and TWINT - **PayPal:** sign in with a personal sandbox buyer account from your [PayPal developer dashboard](https://developer.paypal.com/dashboard/accounts), then confirm the Order back on your checkout. - **Amazon Pay:** sign in with an Amazon Pay **sandbox buyer** from Seller Central (never a real Amazon account). Verify address/payment changes via Amazon's hosted controls, single-click confirmation, separate capture and partial refund against Amazon's sandbox before enabling in `live`. - **TWINT (Adyen, CH / CHF):** the order button opens Adyen's simulator. Choose **authorised**, **cancelled**, **refused**, **error**, or **pending** (decides later via webhook). ## Next steps | You want to | Read | | --------------------------------------- | ------------------------------------------ | | Configure payment provider credentials | [Payment providers](/docs/cart/payments) | | Set up Apple Pay and Google Pay buttons | [Express checkout](/docs/cart/express-checkout) | | Write automated Vitest checkout tests | [Testing](/docs/cart/testing) | | Run the local test environment | [Test environment](/docs/run/test-environment) | # Testing Test real checkouts against your Cloudflare Worker in Vitest with @orbcart/runtime/testing and @orbcart/client/testing. The strongest OrbCart test runs a real purchase against your real Worker, `offers` contract and SDK, faking only external boundaries (the payment provider and your ERP). ## Configure Vitest for your Worker Use `@cloudflare/vitest-plugin` with `JURISDICTION: "none"` (local Miniflare has no data jurisdictions): ```ts title="vitest.config.ts" import { cloudflareTest } from "@cloudflare/vitest-plugin"; import { defineProject } from "vitest/config"; export default defineProject({ plugins: [ cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" }, miniflare: { bindings: { JURISDICTION: "none", ROOT_SECRET: "b3JiY2FydC10ZXN0LXJvb3Qtc2VjcmV0LTMyYnl0ZXM", STRIPE_SECRET_KEY: "stripe-secret-for-tests", STRIPE_PUBLISHABLE_KEY: "stripe-publishable-for-tests", STRIPE_WEBHOOK_SECRET: "stripe-webhook-for-tests", }, }, }), ], }); ``` ## Run a purchase against your Worker Use `issueKey()` from `@orbcart/runtime/testing` and route `@orbcart/client` directly into `exports.default.fetch`: ```ts title="test/purchase.test.ts" import { env, exports } from "cloudflare:workers"; import { createCommerce } from "@orbcart/client"; import { issueKey } from "@orbcart/runtime/testing"; import { expect, it } from "vitest"; const worker = (request: Request) => exports.default.fetch(request); const url = "https://commerce.test"; const shipTo = { name: "Anna Berg", line1: "Bergstraße 12", postalCode: "10115", city: "Berlin", country: "DE", }; it("quotes coffee with shipping", async () => { const key = await issueKey(env, { kind: "publishable", channel: "de" }); const commerce = createCommerce({ url, key, fetch: worker }); const cart = await commerce.cart(); await cart.add("DAYBREAK-250G-BEANS"); const quote = await cart.quote({ shipTo, contact: { email: "anna@example.com" } }); expect(quote.totals.total).toEqual({ amount: 1785, currency: "EUR" }); }); ``` Issue a secret key the same way for Admin SDK tests: ```ts const admin = createAdmin({ url, key: await issueKey(env, { kind: "secret" }), fetch: worker }); ``` ## Seed EU VAT and fake external providers ### EU VAT without the network An `eu-standard` Channel expects daily VAT rates; seed them in your test setup: ```ts import { publishDailyRates } from "@orbcart/runtime/testing"; const today = new Date().toISOString().slice(0, 10); await publishDailyRates(env, { on: today, rates: { DE: { standard: "19", reduced: ["7"] }, AT: { standard: "20", reduced: ["4.9", "10", "13"] }, }, }); ``` ### Fake payment providers Never mock OrbCart internals. Stub `fetch` at the provider boundary, or use `fakeStripe()` and `signedStripeEvent()` for full Stripe idempotency and webhook signing: ```ts import { vi } from "vitest"; import { fakeStripe } from "@orbcart/runtime/testing"; const stripe = fakeStripe({ created: { status: "requires_capture" } }); vi.stubGlobal("fetch", stripe.fetch); ``` ```ts import { vi } from "vitest"; vi.stubGlobal("fetch", async (request: Request) => { if (request.url.includes("adyen.com")) return Response.json({ resultCode: "Authorised", pspReference: "PSP123" }); throw new Error(`Unexpected request to ${request.url}`); }); ``` ## Test storefront components without a Worker Use `fakeRuntime()` from `@orbcart/client/testing` for fast UI component tests: ```ts browser import { fakeRuntime, cartPath, cart } from "@orbcart/client/testing"; const { commerce, requests } = fakeRuntime({ [`GET ${cartPath}`]: cart, }); // render your component with commerce.openCart(token) expect(requests.map((r) => r.route)).toEqual([`GET ${cartPath}`]); ``` ## High-value scenarios to cover - **A sale ends mid-checkout:** buyer receives `quote_changed` instead of the stale price. - **Double-clicking the order button:** one payment, one Order. - **ERP downtime:** Order delivery retries and arrives once the ERP recovers. - **Partial refund:** amount matches the frozen Order snapshot. - **Restricted shipping:** bulky or restricted items drop ineligible methods with a reason. ```sh pnpm exec vitest run test/purchase.test.ts ``` ## Customize | You want to | Do this | Default | | --------------------------------------- | ------------------------------------------------------------- | --------------------- | | Simulate 3-D Secure webhooks | Call `signedStripeEvent(env, stripe.authenticate(id), url)` | Immediate capture | | Test Admin API routes | Call `issueKey(env, { kind: "secret" })` with `createAdmin()` | Publishable key | | Test React components without Miniflare | Use `fakeRuntime()` from `@orbcart/client/testing` | Full Worker in Vitest | ## Next steps | You want to | Read | | ------------------------------------------- | ----------------------------------------- | | Copy a complete payment + double-click test | [Test a purchase](/docs/cart/test-a-purchase) | | Test cards and redirect flows manually | [Test payments](/docs/cart/test-payments) | | Review all OrbCart SDK packages | [SDKs and packages](/docs/cart/sdks) | | Run a local test environment | [Test environment](/docs/run/test-environment) | # What makes OrbCart different What OrbCart is, what it leaves to you, and when it fits better than a shop platform, headless suite or custom build. OrbCart handles the transaction layer of a shop: Cart, checkout, tax, shipping, payment and Order. It does not store a catalog. Your products, prices and stock stay in the systems that already own them, and OrbCart asks them through [small contracts](/docs/cart/offers) whenever a buyer needs a binding answer. One core serves both your storefront and AI agents, running as a Worker in your own Cloudflare account. See [Concepts](/docs/cart/concepts) for the mental model. ## What OrbCart is not - **Not a catalog, PIM or CMS.** Your storefront renders products, categories, images and pages; OrbCart never stores them. - **Not a storefront.** Build your shop in any framework. A [React checkout](/docs/cart/react-checkout) and an [order page](/docs/cart/order-page) are included if you want them. - **Not search, an ERP or a warehouse.** Invoices, fulfillment and stock records stay in your systems. OrbCart hands them the Order. - **Not an email sender.** OrbCart emits [which buyer email is due](/docs/cart/buyer-emails), and your system sends it in your own design. - **Not a hosted SaaS.** You deploy it in your own Cloudflare account. A managed offering is a future direction, not a product today. ## How it compares | Approach | Your catalog | You operate | You get | | ----------------- | --------------------------------- | -------------------------- | ----------------------------------------------- | | Shop platforms | Moves into the platform | Nothing (hosted) | A full shop built around their catalog. | | Headless suites | Mirrored SKUs; live pricing glued | Storefront on their API | Cart to Order around their catalog. | | Open-source shops | Inside their product model | Servers, DB, queue, cache | A complete shop you maintain. | | Payment checkouts | Passed per checkout session | Nothing | Payment collection; cart and Orders stay yours. | | Custom build | Stays where it is | Everything | Full control, plus retries, tax and edge cases. | | **OrbCart** | **Stays where it is**, asked live | One Worker per environment | Cart to Order for storefronts and AI agents. | ## What you get out of the box - **A signed price.** Buyers pay the exact [Quote](/docs/cart/concepts#quote) they agreed to, or see the updated price first. - **Honest payment states.** Provider timeouts become `unknown` and are resolved by polling, never a double charge or lost Order ([how it works](/docs/cart/how-it-works#when-something-goes-wrong)). - **AI agents through the same door.** Agents check out over UCP with AP2 mandates under the exact rules of your storefront ([AI agents](/docs/cart/agents)). - **Instant price invalidation.** Call `admin.offers.invalidate()` to end a sale immediately for every new Quote. - **Clear operational state.** Payment, shipping and ERP hand-off track their own state, and problems surface as `issues` on the Order. - **Privacy-safe events.** Webhook events carry no personal data and are signed by your Environment's key. ## Choose OrbCart when - Your products, prices and stock already live in an ERP, PIM or pricing service and you do not want a second copy. - You are building your own storefront, or want full control over it. - You want AI agents to buy under the same rules as human shoppers. - You sell in the EU and need EU VAT plus local payment methods. - You want the commerce runtime in your own cloud account under Apache 2.0. ## Choose something else when - You want an all-in-one shop with themes, catalog and admin out of the box. A hosted shop platform fits better. - You do not have developers. OrbCart is code: a Worker, your contracts and a storefront. - You only need to charge a fixed price. A payment link is simpler. - You need subscriptions, B2B approvals, payment on account or a multi-seller marketplace. None of these is built. - You cannot run on Cloudflare Workers and Durable Objects. - You need published npm packages today. OrbCart is [pre-release](/docs/cart/status). ## Next steps | You want to | Read | | -------------------------- | ------------------------------------------ | | Try it locally in minutes | [OrbCart quickstart](/docs/get-started/orbcart) | | Learn the core vocabulary | [Concepts](/docs/cart/concepts) | | Trace a full purchase flow | [How it works](/docs/cart/how-it-works) | | See what is built today | [Project status](/docs/cart/status) | # The withdrawal function Implement the EU two-step contract withdrawal flow without requiring an account, with durable receipts and admin inbox handling. EU online shops must provide a dedicated two-step withdrawal function ([Directive (EU) 2023/2673](https://eur-lex.europa.eu/eli/dir/2023/2673/oj), Art. 11a; in Germany [§ 356a BGB](https://www.gesetze-im-internet.de/bgb/__356a.html)). You host the two steps; OrbCart stores declarations, matches them to Orders, sends receipts and tracks them in the admin. ## Submit a withdrawal declaration Collect the shopper's name, order number, email address and whether they withdraw from the whole order or specific items, show their declaration back for review, and submit it only when they click the confirmation button: ```ts const receipt = await commerce.withdraw({ name: "Anna Berger", number: "CC-2026-004711", email: "anna@example.com", goods: { type: "some", description: "Espresso Cup · Moss · Pair" }, locale: "en", }); ``` Display every field of the returned receipt immediately, including its timestamp: ```ts continues receipt.receivedAt; // "2026-11-03T10:15:00.000Z" receipt.goods; // { type: "some", description: "Espresso Cup · Moss · Pair" } ``` ## Required labels and privacy rules Place a persistent link in your footer on every page using the statutory wording for each language: | Language | Step 1 link label | Step 2 confirm button | | -------- | --------------------------- | ------------------------- | | German | Vertrag widerrufen | Widerruf bestätigen | | English | Withdraw from contract here | Confirm withdrawal | | French | Se rétracter du contrat ici | Confirmer la rétractation | Verify non-German labels against your national transposition before launch. ### Anti-enumeration and rate limits - **Identical responses:** `commerce.withdraw()` returns the same receipt shape whether or not the order number and email match an Order, so callers cannot probe which orders exist. Tell the buyer confirmation will arrive by email rather than saying "withdrawal recorded". - **Forgiving input:** `CC-2026-004711`, `cc-2026-004711`, `2026-4711` and `4711` match the same Order; email case and surrounding whitespace are ignored. - **Deduplication and limits:** repeating the same declaration within 10 minutes returns the original receipt without sending a second email. Requests are limited to 5 per email/minute and 20 per IP/minute (`429 rate_limited`; see [Security](/docs/cart/security#rate-limits)). - **Email receipt:** the `withdrawal.received` event triggers the receipt email in the submitted `locale` ([Buyer emails](/docs/cart/buyer-emails)). ## How support handles withdrawals Matched withdrawals appear in the Order's history with a deadline check: the 14-day window runs from the last reported fulfilment (rolling Saturday/Sunday to Monday) and flags borderline cases as "maybe late" for staff review without refusing them. Unmatched declarations (and matched ones still awaiting durable confirmation) wait in _Orders → Withdrawals_: - Staff with `orders:edit` (or a secret key) attach a declaration to an Order via `POST /v1/withdrawals/{withdrawal}/attach` with `{ order }` (Order ID or number) and an `Idempotency-Key`. The endpoint returns `200` with `status: "recorded"` once durably saved, or `202` with `status: "recording"` while background retries finish. - Raw declarations and their personal data are deleted after **180 days**; an attached withdrawal stays on its Order for the life of the Order. An unconfirmed attachment past 180 days becomes `expired_unconfirmed` (`410 withdrawal_expired` on retry). ## Customize | You want to | Do this | Default | | ------------------------------------------ | ------------------------------------------------------------- | ------------------------------------------- | | Exclude personalised goods from withdrawal | Return `withdrawal: { excluded: "personalized" }` in `offers` | Standard 14-day withdrawal | | Send receipt emails from your own mailer | Subscribe to `withdrawal.received` in `events` | Built-in [Buyer emails](/docs/cart/buyer-emails) | | Localise the receipt email | Pass the page's `locale` to `commerce.withdraw()` | Channel locale | ## Next steps | You want to | Read | | ----------------------------------------- | ---------------------------------------------- | | Configure buyer withdrawal receipt emails | [Buyer emails](/docs/cart/buyer-emails) | | Process returns and refunds | [Orders and refunds](/docs/cart/orders-and-refunds) | | Review rate limits and privacy rules | [Security](/docs/cart/security) | | Add legal text links to checkout | [Configuration](/docs/cart/configuration#legal) | # Agents Connect AI agents to OrbCatalog over MCP to search products, inspect drafts and propose human-approved edits. OrbCatalog exposes an [MCP](https://modelcontextprotocol.io) endpoint at `https:///mcp` so AI assistants can answer real questions about your catalog (_"Which coffees are still missing an English description?"_) and propose draft changes. An agent **never mutates your catalog directly**: every creation, copy, edit or publish creates a proposal that a staff member must explicitly approve in the admin. ## Connect an MCP client Point any MCP client (supporting MCP revision `2026-07-28`, streamable HTTP `POST`) to: ```text https://catalog.example.com/mcp ``` Clients supporting standard MCP OAuth discovery (`/.well-known/oauth-protected-resource/mcp`) find your admin's sign-in automatically, prompt the user once to consent to scopes (`catalog:products.read` and `catalog:products.write`), and receive short-lived 5-minute access tokens. ## Read tools All list tools return up to **25 rows per page** (capped at 64 KB per response) with a `next` cursor passed back as `after`. | Tool | Purpose | Key inputs | | ---------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | `find_products` | Search products by text, category, status, attributes or missing fields | `text`, `category`, `status`, `where`, `missing`, `incomplete`, `after` | | `list_filters` | List filterable attributes, choices and linked Registers | _(none)_ | | `find_entries` | Search entries in a Register (such as Brands or Origins) | `register`, `text`, `after` | | `list_product_types` | List published Types with schema/settings versions and locales | `after` | | `read_product_type` | Inspect a Type's defaults, attributes, choices and variant axes | `type`, `after` | | `find_categories` | Search the category tree (including unpublished categories) | `text`, `after` | | `read_category` | Read a category's working copy, parent and Source owner | `ref` | | `read_entry` | Read a register entry's working copy and publication state | `register`, `ref` | | `read_schema_draft` | Read working Type, attribute or register declarations, by revision | `section` (`types`, `attributes`, `registers`), `after` | | `preview_schema_draft` | Check the impact and blockers before publishing a saved Schema draft | `basedOn` | | `read_draft` | Read draft/live fields, variants, media refs, `owned` fields and `publishCheck` | `ref`, `section` (`all`, `fields`, `variants`, `media`), `version`, `after` | - **Register filters:** Brand or origin fields link to Register entries rather than plain text. Use `list_filters` → `find_entries` → `find_products` with `where`. - **Snapshot consistency:** Paginated continuations carry the draft revision and schema/settings versions they started with; if any change mid-read, the cursor is invalidated so the agent restarts cleanly. - **`publishCheck`:** Runs Catalog's real publish validator on a copy and reports `ready`, `unchanged`, `blocked` or `incomplete` with exact missing fields. ## Proposal tools | Tool | What it proposes | | ------------------- | -------------------------------------------------------------------------------------------------------------------------- | | `create_product` | Create one new unpublished editorial draft (`ref`, `type`, `locale`, `name`) | | `duplicate_product` | Copy an existing draft with fresh variant IDs (clears slugs, SKUs, GTIN/MPN, offers, stock and Source ownership) | | `edit_draft` | Apply up to 200 native field edits (`set`, `clear`, `add_variant`, `remove_variant`) against a specific `basedOn` revision | | `publish_product` | Release specific `locales` of a draft (always separate from editing) | | `change_products` | Change every product the `find_products` filters find, as one job with a dry run and an undo | | `edit_schema_draft` | Create or update Type, attribute and register declarations in the working Schema | | `change_category` | Create a category, edit its draft or move its subtree | | `change_entry` | Create a register entry or edit its draft | Read the current Schema revision or the category or entry snapshot before proposing an edit. `edit_schema_draft` changes only the named declarations. After approval, use `preview_schema_draft` to check the impact of publishing in the admin. Category and register entry creation and text edits remain unpublished until you publish in the admin. Moving a category changes the hierarchy on approval; it does not publish a new version. Stock, product deletion, publishing many products and Source-owned fields are never exposed as MCP write tools. ## Change many products at once `change_products` takes the filters of `find_products` and up to 20 changes: set, clear or `adjust_percent` an attribute, add or remove a category, a new `base_price`, or a `sale` in a Channel for a window, by amount or `percent_off`. ```json { "products": { "category": "mugs" }, "changes": [ { "target": "sale", "channel": "de", "price": { "by": "percent_off", "percent": 20 }, "during": { "from": "2026-11-27T00:00:00Z", "until": "2026-11-30T00:00:00Z" } } ] } ``` The first call starts a dry run. The approval page shows how many products it finds and changes, samples with before and after, and which products cannot take the change. **Approve** runs the job, skipping any product that changed after the dry run. Prices change in their Channel at once; other fields stay in the drafts, unpublished. The retry answers the job's id, its counts and `follow`, the approval page where the person follows the job and finds **Undo** once it has finished. Only that approval runs the job; _Run_ in the panel refuses it. Each person has one such proposal waiting at a time, because each holds a dry run over every product its filters find. ## How human approval works No proposal tool writes on the first call. After validating permissions, revision freshness and field rules, Catalog stores a **proposal** (valid for 15 minutes) and returns `resultType: "input_required"` with an approval URL on your admin's origin. 1. **Review in the admin:** The staff member opens the approval URL (or sees it inline/in a dialog inside the admin's built-in [AI Chat](/docs/admin/chat)) showing exact before/after diffs and clicks **Approve** or **Reject**. 2. **Fresh session verification:** Clicking **Approve** issues a single-use 30-second grant against the user's live session cookie. Catalog re-verifies the session, Products edit permission and draft revision atomically before saving. 3. **Resume the tool call:** The MCP client retries the tool call with the returned `inputResponses` and `requestState` and receives the final outcome (e.g. `"Saved as revision 43."`). Retries never write twice. Only the person who triggered the proposal can approve it. If the draft changed in the meantime or a Source claimed the field, the save is refused cleanly. ## Access rules and audit logging - **Strict audience and scopes:** Tokens must target the exact `/mcp` URL (`aud`) and carry `catalog:products.read` or `catalog:products.write`. Scopes never widen a staff member's actual Products role. - **Privacy-safe logs:** Request logs record only the MCP tool name, outcome and duration (no product text or user prompts). Consumed proposals write an audit record with the actor, client, operation, product ref, revision and outcome. Approved edits are attributed to the approving person. ## Next steps | You want to | Read | | ------------------------------- | ----------------------------- | | Use the built-in admin AI Chat | [AI Chat](/docs/admin/chat) | | Understand Catalog's data model | [Concepts](/docs/catalog/concepts) | | Call the public storefront API | [HTTP API](/docs/catalog/http-api) | # Follow the catalog's changes Read incremental catalog updates from the change feed or receive signed CloudEvents webhooks. OrbCatalog records every product, category, register, offer and stock change in commit order. Pull increments with `@orbcatalog/client/changes` or subscribe to signed webhooks. ## Poll the change feed Create a read key (`rk_…`) under _Connections_ in the admin and store the returned `next` cursor after each page: ```ts function import { changes } from "@orbcatalog/client/changes"; const feed = changes({ url: "https://catalog.clayandcrema.de", key: env.ORBCATALOG_READ_KEY }); let after = await cursors.get("orbcatalog"); for (;;) { const page = await feed.page({ after, limit: 100 }); if (page.status === "cursor_expired") { await refreshWhatYouHold(); // read each ref you keep again through the public client after = undefined; continue; } for (const change of page.data) await apply(change); // { sequence, position, kind, ref, version, at } if (page.next === undefined) break; after = page.next; await cursors.set("orbcatalog", after); } ``` ### How the feed works - **Pointers, not payloads.** Each change names what moved (`product.published`, `product.withdrawn`, `product.scheduled`, `product.unscheduled`, `offer.changed`) and its ref or SKU; read the entity through the public client. - **Commit order and batching.** One write's changes share a `sequence` and increment `position`. Cursors are opaque and resume inside large batches without skipping slow transactions. - **New kinds and fields.** A kind of change added after your client was built arrives as `{ kind: "unrecognized", unrecognizedKind, sequence, position, at }` at its place in the page, so a reader that only handles some kinds reads on past it. Fields added to a known kind are left out. A known kind that is malformed throws `CatalogError` and is never passed on as unrecognized. - **30-day retention.** The feed keeps the changes of the last 30 days. A cursor older than that, or one from a restored database history, returns `cursor_expired`. - **Isolated readers.** Cache purges, OrbSearch, OrbCart and each webhook maintain their own cursors, so one slow destination never delays another. - **Private and retried.** `GET /v1/changes` is always `private, no-store`. The client retries `429` and `5xx` with backoff. ### Where the feed starts The feed is incremental. It says what changed, not what the catalog holds. - **Without a cursor**, a reader gets the changes still retained, oldest first. Changes older than 30 days are gone, so a new reader never sees a product that was published earlier and has not changed since. - **On `cursor_expired`**, drop the cursor and read on from the oldest retained change, as the sample does. Read every ref your copy holds again through the [public client](/docs/catalog/storefront), since some of their changes are gone. - **A complete mirror** of the catalog is not possible today. A read key reads the change feed and nothing else, so there is no full export with a matching cursor to start from. The feed OrbSearch polls is built for search and is not that snapshot. ## Receive signed webhooks Add a webhook under _Settings → Webhooks_ in the admin. Your receiver only needs the catalog's URL to verify every delivery with `verifyEvent()`: ```ts import { verifyEvent } from "@orbcatalog/client/changes"; export async function handle(request: Request): Promise { const event = await verifyEvent(request, { url: "https://catalog.clayandcrema.de" }); if (event.type !== "webhook.test" && event.data.kind === "product.published") { await shop.refresh(event.data.ref, event.id); } return new Response(null, { status: 204 }); } ``` ### CloudEvents envelope Each delivery is a CloudEvents 1.0 JSON message (`Content-Type: application/cloudevents+json`): | Field | Value | | ------------- | ----------------------------------------------------------------------------------------------- | | `id` | Position and timestamp (for example `2107.0@2026-10-01T07:00:00.000Z`); deduplicate by this ID. | | `type` | The change kind (such as `product.published`, `offer.changed` or `webhook.test`). | | `subject` | The affected product ref, category ref or SKU. | | `data` | The same change object returned by the feed. | | `environment` | `live`, `test` or `preview-`, so test events are never confused with live ones. | | `source` | Origin of `PUBLIC_URL`, or `urn:orbcatalog:{catalog}:{environment}` when unset. | A webhook delivers only the kinds it subscribes to, so a kind added later never reaches a receiver until you add it to the webhook. `verifyEvent()` leaves out fields added to a known kind, and rejects an event of a kind it does not know as `event_invalid`, so update the client before subscribing to a new kind. Because `id` is also a valid feed cursor, a receiver that wants to catch up after a bulk sync can pass it directly to `feed.page({ after: event.id })`. ### Verification and retries - **RFC 9421 HTTP signatures.** Deliveries are signed with `ecdsa-p256-sha256` (`tag: "orbcommerce-event"`) using keys published at `/.well-known/jwks.json`. Signatures cover `@method`, `@authority`, `@path`, `@query`, `content-type`, `content-digest`, `webhook-id` and `webhook-timestamp`, and remain valid for 5 minutes. - **Standard Webhooks fallback.** Every delivery also carries `webhook-signature` (`v1` HMAC-SHA256) using the webhook's own secret from _Settings → Webhooks_ (`new Webhook(secret).verify(body, headers)`). Rolling the secret keeps the previous secret signing alongside it for 24 hours. - **Delivery schedule.** Any `2xx` within 10 seconds acknowledges the event; redirects are not followed. `429` and `503` honour `Retry-After` up to 1 hour. `410 Gone` pauses the webhook until resumed in the admin. Other failures retry at 5 seconds, 1, 5 and 30 minutes, then hourly for up to 30 days. ### Test a webhook before going live Use **Send test** in _Settings → Webhooks_ (`POST /panel/webhooks/{name}/test`) to deliver a signed `webhook.test` event immediately. Point a webhook at `{PUBLIC_URL}/test-receiver` to inspect the last 20 signed deliveries, headers and verification results directly in the admin. ## Customize | You want to | Do this | Default | | --------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------ | | Verify behind a rewriting reverse proxy | Pass `{ url, target }` to `verifyEvent()` | Uses `request.url` | | Tune JWKS fetch timeout | Pass `keysTimeoutSeconds` to `verifyEvent()` | `5` seconds | | Verify in a language without RFC 9421 | Use a [Standard Webhooks](https://www.standardwebhooks.com) library with the webhook secret | RFC 9421 via `verifyEvent()` | | Rotate the event signing key | Trigger rotation in _Settings_ (`POST /panel/signing-keys`) | 31-minute prepublish, 6-minute grace | ## Troubleshooting ### `EventVerificationError` codes `verifyEvent()` throws `EventVerificationError` with one of: `signature_missing`, `wrong_purpose`, `unsupported_algorithm`, `missing_component`, `outside_window`, `digest_mismatch`, `body_too_large`, `unknown_key`, `keys_unavailable`, `signature_invalid` or `event_invalid`. - Return `4xx` for invalid or expired signatures. - Return `503` for `keys_unavailable` so OrbCatalog retries once JWKS is reachable again. ## Next steps | You want to | Read | | ---------------------------------------------------- | ------------------------------------------------- | | Rotate reader keys, signing keys and webhook secrets | [Rotate credentials](/docs/run/credential-rotation) | | Read products and offers after a change | [Read the catalog](/docs/catalog/storefront) | | Sync products and prices from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Connect OrbCatalog to OrbCart and OrbSearch | [Connect the products](/docs/run/connect-the-products) | # Concepts OrbCatalog's seven core concepts, from Type and Product to Register, Offer and Channel. OrbCatalog models each **Product** (along with its **Variants**) as a single typed document. A versioned **Schema** defines your Types and shared attributes, automatically driving validation, admin grid columns, database filter indexes and OpenAPI. **Offers** live beside the product document because prices are operational data, not editorial content. Prices are stored as an append-only ledger where your ERP and editors write side by side, and every time-based change (scheduled publications or sales) is evaluated at read time. ## The seven core concepts ### Type Defines the shape of a product category (such as _Coffee_ or _Ceramics_): which attributes it uses, which are required, and which act as variant axes. All Types publish together as one immutable **Schema** version so shared attributes (such as `brand`) behave consistently across Types. ### Product One sellable item described once across all languages: its merchant `ref`, localized names and slugs, attributes, media, categories and Variants. Drafts and published snapshots live side by side, with version history stored as reverse patches. A single version spans **all locales**: shared facts (variants, SKUs, weights, media, categories) exist once, and each version lists which locales it releases. German can publish today and English next week without duplicating the product. ### Variant One concrete, buyable SKU inside a Product document, distinguished by the Type's variant axes (such as weight, grind or colour). SKUs are globally unique across live products. ### Category A node in the category tree with its own localized document (title, slug, description and pinned products), using the same draft and versioning model as Products. ### Register A structured reference list declared by the Schema (such as **Brands**, **Roasters** or **Certifications**). Editors and Sources add **Entries** (name, slug, description, image, link) without republishing the Schema. ### Offer What one SKU costs and whether it can ship in one Channel. Offers combine terms (availability, delivery days) with an append-only price ledger supporting base prices and scheduled sales from multiple writers. Offers are never drafted or versioned. ### Channel One storefront market defining currency, supported locales, gross or net pricing, country and storefront URLs. ## What a Product looks like Attribute values are keyed by stable attribute IDs internally; public APIs expose human-readable attribute keys: ```jsonc { "name": { "de": "Daybreak", "en": "Daybreak" }, "slug": { "de": "daybreak", "en": "daybreak" }, "search": { "title": { "en": "Daybreak Espresso Blend" } }, // optional; defaults to name "attributes": { "atr_roast0000001": ["medium"], "atr_origin000001": ["colombia"], // link to a Register entry "atr_desc00000001": { "de": { "type": "doc", "content": [] }, "en": { "type": "doc", "content": [] }, }, }, "variants": [ { "id": "var_4n8c2m6q0x1s", "sku": "DAYBREAK-250G-BEANS", "axes": { "atr_grind0000001": "whole-bean" }, "shipping": { "weightInGrams": 270 }, "taxCategory": "standard", }, ], "media": [ { "media": "med_1a2b3c4d5e6f", "width": 2000, "height": 2000, "alt": { "en": "Daybreak 250 g coffee bag" }, }, ], "categories": ["coffee"], } ``` ### Linking Register entries Because brands or origins live in a Register rather than a static dropdown, adding a new one requires no Schema publish and gives each entry its own page, logo and description: ```jsonc // GET /v1/registers/origins/entries/colombia?locale=en { "object": "entry", "register": "origins", "ref": "colombia", "locale": "en", "name": "Colombia", "slug": "colombia", "urls": { "en": "https://shop.example.com/en/origins/colombia" }, "description": { "html": "

Washed high-altitude lots from Huila.

" }, "image": { "url": "https://media.example.com/med_7c1d9e3f5a2b/640", "width": 640, "height": 480 }, "version": 3, "publishedAt": "2026-10-01T07:00:00.000Z", "sequence": 2107, } ``` ## Next steps | You want to | Read | | ----------------------------- | ------------------------------------------ | | Manage products in the admin | [The catalog in the admin](/docs/admin/catalog) | | Read products in a storefront | [Read the catalog](/docs/catalog/storefront) | | Sync from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Consume changes and webhooks | [Catalog changes](/docs/catalog/changes) | | Look up public HTTP routes | [HTTP API](/docs/catalog/http-api) | # HTTP API Public read routes, caching and purge rules, category trees, product cards with prices, and the staff client for OrbCatalog. All storefront reads go through OrbCatalog's cached `/v1` HTTP API. Every response is strictly validated, canonically cached and tagged for targeted CDN purges. ## Connect from a storefront If your storefront runs as a Cloudflare Worker in the same account, bind directly to Catalog's `Storefront` entrypoint to skip public network hops and per-IP miss budgets: ```jsonc title="Storefront wrangler.jsonc" { "services": [{ "binding": "CATALOG", "service": "orbcatalog", "entrypoint": "Storefront" }], } ``` Pass `fetch: (req) => env.CATALOG.fetch(req)` to `catalog({ url, fetch })`. The `Storefront` binding serves public reads only (never staff, Source or change-feed routes) and receives the same cache purges as the public URL. Browsers and external servers call the public Catalog URL directly. ## Public routes and cache lifetimes | Route | Purpose | Browser / Edge TTL | Cache tags | | ------------------------------------------------------------ | -------------------------------------------------------- | ------------------------- | ---------------------------------------------- | | `GET /v1/products/{ref}?locale=&fallback=default` | Published product in one locale (no prices) | 60 s / 600 s | `p:{h(ref)}`, linked `e:`, `catalog` | | `GET /v1/products?category=&locale=&limit=&after=` | Category product cards (pinned first, then newest) | 60 s / 600 s | `c:{h(category)}`, linked `e:`, `catalog` | | `GET /v1/categories/{ref+}?locale=` | Single category with `path` and `hasChildren` | 60 s / 600 s | `c:` (self + ancestors), `catalog` | | `GET /v1/categories?parent=&locale=` | Direct children of a category (or roots) | 60 s / 600 s | `c:`, `roots`, `catalog` | | `GET /v1/category-tree?parent=&depth=&locale=` | Full navigation tree up to `depth` (default `2`) | 60 s / 600 s | `c:`, `roots`, `catalog` | | `GET /v1/category-presence?category=&type=&locale=&channel=` | Which categories contain live products of given Types | 60 s / 600 s | Requested + subtree `c:`, `schema`, `settings` | | `GET /v1/registers/{register}/entries/{ref}?locale=` | Single Register entry (e.g. a brand) | 60 s / 600 s | `e:{h(register/ref)}`, `catalog` | | `GET /v1/find?q=&kind=®ister=&locale=&limit=` | Type-ahead search (up to 50 results) | 60 s / 600 s | Shown `p:`/`c:`/`e:`, `catalog` | | `GET /v1/routes/{slug}?locale=` | Resolve slug to target (`moved` for old slugs) | 60 s / 600 s (30 s moved) | Target `p:`/`c:`/`e:` | | `GET /v1/products/{ref}/offers?channel=` | All variant offers for one product | ≤ 30 s / ≤ 120 s | `op:{h(ref)}`, `offers` | | `GET /v1/offers/{sku}?channel=` | Single SKU offer | ≤ 30 s / ≤ 120 s | `o:{h(sku)}`, `op:{h(ref)}`, `offers` | | `GET /v1/shops` | Shop identity, languages, Channels and capabilities | 60 s / 600 s | `settings` | | `GET /v1/openapi.json` | OpenAPI spec including all published Types | 60 s / 600 s | `schema` | | `GET /v1/media/{id}?locale=` | Media metadata, `url`, `srcset`, `focalPoint`, `alt` | 60 s / 600 s | `m:{h(id)}`, `catalog` | | `GET /v1/locations?channel=` | Open Locations for a Channel + next 14 days of hours | 60 s / 600 s | `locations`, `catalog` | | `GET /v1/appointments/free-times?location=&sku=&...` | Bookable appointment slots (up to 14 days) | ≤ 10 s | `offers` | | `GET /v1/appointments/needs/{sku}` | Effective appointment requirements for a live SKU | 30 s / 120 s | `settings`, `catalog`, `p:` | | `GET /media/{id}/{version}[/{width}]` | Owned image original or WebP rendition | 1 year, `immutable` | None (versioned URL) | | `GET /media/{id}/current[/{width}]` | Registered private original or rendition | 30 s / 30 s | `m:{h(id)}` | | `GET /.well-known/jwks.json` | Public keys for [webhook verification](/docs/catalog/changes) | 60 s / 600 s | `catalog` | ## Caching, canonical URLs and freshness - **Strict parameters and canonical `308` redirects:** Unknown parameters return `400 parameter_unsupported`. Non-canonical parameter order, explicit defaults (such as `days=7`) or unencoded slashes redirect with `308` before spending any miss budget, keeping cache keys clean. - **Time-clamped lifetimes:** Every response TTL is automatically clamped to the next scheduled publish or price transition, dropping stale windows at the boundary so a sale starting at 12:00 is live at 12:00 without waiting for a purge. - **Limited stock and offers:** Responses containing a `limited` offer drop to a 10-second fresh lifetime. Offers include computed `unitPrice` (for measured goods) and `lowestPrior` (30-day lowest price during EU sales). - **Miss budgets and retries:** Cache misses are rate-limited per route and client network (`429 rate_limited`). The `@orbcatalog/client` retries once after 1 second on network errors, `429` or `5xx`. - **Image renditions:** Allowed widths are `160`, `320`, `640`, `960`, `1280` and `1920` px (`WebP`), controlled by `MEDIA_TRANSFORM` (`cloudflare`, `bunny`, `imgproxy` or `none`). Owned images use immutable content-digest URLs; see [Private media storage](/docs/catalog/media-storage#delivery-and-replacement-freshness). ## Common storefront queries ### Product cards with prices Pass `channel` to `products()` or `find()` to attach the cheapest orderable variant's `offer` to each card in one batched request (using the shorter offer cache lifetime): ```ts title="src/product-cards.ts" import { catalog } from "@orbcatalog/client"; export async function productCards(url: string) { const shop = catalog({ url }); return shop.products({ category: "coffee", locale: "de", channel: "de" }); } ``` ### Category subtree listings Pass `descendants: true` to include products from all live child categories in a single cursor-paginated list: ```ts title="src/category-products.ts" import { catalog } from "@orbcatalog/client"; export async function categoryProducts(url: string, after?: string) { const shop = catalog({ url }); return shop.products({ category: "coffee", descendants: true, locale: "de", channel: "de", limit: 20, after, }); } ``` ### Category product presence Check which navigation categories contain at least one live product of specific Types (including descendants) without fetching product rows: ```ts title="src/selling-categories.ts" import { catalog } from "@orbcatalog/client"; export async function sellingCategories(url: string) { const shop = catalog({ url }); const presence = await shop.categoryPresence({ categories: ["coffee", "ceramics"], types: ["coffee", "ceramic"], locale: "de", channel: "de", }); return new Set(presence.data.filter((row) => row.hasProducts).map((row) => row.ref)); } ``` Accepts 1–64 category refs and 1–32 Type keys. Returns `validUntil` so application caches respect scheduled publication boundaries. ## Staff management client Use `@orbcatalog/client/staff` to call `/panel/*` routes with a staff token or operator key. Every call validates responses with Zod and returns `{ ok: true, value }` or `{ ok: false, problem }` instead of throwing: ```ts title="src/products-to-check.ts" import { staffCatalog } from "@orbcatalog/client/staff"; export async function coffeesToCheck(staffToken: string) { const shop = staffCatalog({ url: "https://catalog.example.com", fetch: (request) => { request.headers.set("Authorization", `Bearer ${staffToken}`); return fetch(request); }, }); const page = await shop.grid({ search: "daybreak", limit: 25 }); if (!page.ok) throw new Error(page.problem.detail); return page.value.rows.map(({ ref, revision }) => ({ ref, revision })); } ``` ## Next steps | You want to | Read | | -------------------------------- | ----------------------------------------------- | | Build storefront product pages | [Read the catalog](/docs/catalog/storefront) | | Configure private R2 or S3 media | [Private media storage](/docs/catalog/media-storage) | | Connect AI agents over MCP | [Agents](/docs/catalog/agents) | # OrbCatalog OrbCatalog stores your products, variants, prices and stock and serves them through a CDN. What it does, what it leaves to you and where to start. OrbCatalog is the product database of a shop: Types, Products, Variants, Categories and Offers. Editors manage them in the admin, a PIM or ERP syncs them, and storefronts read published data through a CDN. One Postgres, one API, a CDN in front. Fetching a category's product cards with live prices in the German shop takes one call: ```ts title="src/product-cards.ts" import { catalog } from "@orbcatalog/client"; export async function productCards(url: string) { const shop = catalog({ url }); return shop.products({ category: "coffee", locale: "de", channel: "de" }); } ``` Each card includes its localized `slug` and, because the call specifies a `channel`, the `offer` of its cheapest orderable variant. [Your first product](/docs/get-started/first-product) walks you from an empty admin to a live product. ## What OrbCatalog does - **Shapes products by Type.** Design [Types](/docs/catalog/concepts#type) in the admin and publish them as one Schema. The Schema drives validators, grid columns, filter indexes and OpenAPI. - **Publishes per language and on schedule.** Release German today and English next week. Versions scheduled for a future timestamp go live at that exact minute without a cron job. - **Keeps prices as a ledger.** An [Offer](/docs/catalog/concepts#offer) holds one SKU's price and availability per Channel. Your ERP and editors write side by side, and scheduled sales activate automatically without cache purges. - **Edits at scale.** The [admin grid](/docs/admin/catalog) handles up to 2,000,000 products with instant filtering, bulk updates, previews and Undo. - **Syncs with your systems.** A PIM or ERP sends products, categories, offers and stock as a [Source](/docs/catalog/sources), with Source-owned fields locked in the admin. [File import](/docs/admin/import) supports CSV, JSON Lines and Excel. - **Streams every change.** A [change feed](/docs/catalog/changes) and signed webhooks notify downstream systems incrementally. - **Serves AI agents safely.** [Agents](/docs/catalog/agents) read the catalog over MCP and propose edits that a human approves in the admin. ## What OrbCatalog leaves to you | OrbCatalog does not | Who handles it | | ------------------------------------ | -------------------------------------------------------------------------------------------- | | Take orders or payments | OrbCart. Catalog prices are hints; OrbCart's [Quote](/docs/cart/concepts#quote) decides. | | Search and rank products | OrbSearch, fed from the catalog's NDJSON feed. | | Hold marketing pages and stories | OrbPage, which embeds catalog products as cards. | | Price per customer or customer group | Not possible today. | | Track stock per warehouse | Not possible today. Each SKU has one aggregate count shared across Channels. | | Run approval workflows or sync back | Not possible today. | | Mirror the whole catalog elsewhere | Not possible today. The [change feed](/docs/catalog/changes#where-the-feed-starts) holds 30 days. | ## Change what you need Everything in OrbCatalog adapts at one of three levels, from shallow to deep: | Depth | You | Example | | --------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | Configure | Design Types, languages and Channels. | [Unit prices](/docs/admin/catalog#unit-prices), [storefront paths](/docs/catalog/storefront#storefront-paths-and-sitemaps). | | Compose | Let a Source own some fields and editors the rest. | [Sync from a PIM or ERP](/docs/catalog/sources). | | Replace | Bring your own private R2 or S3 media bucket. | [Private media storage](/docs/catalog/media-storage). | ## With OrbCart, OrbPage and OrbSearch OrbCatalog runs completely on its own. Any sibling you add connects through configuration, not glue code: - **OrbCart** reads live offers and stock through its contracts and receives instant price invalidations. - **OrbPage** displays catalog products as cards (without prices). - **OrbSearch** polls the catalog feed and receives price updates in seconds. See [Connect the products](/docs/run/connect-the-products) for the setup. ## Next steps | You want to | Read | | -------------------------- | ------------------------------------------------ | | Publish your first product | [Your first product](/docs/get-started/first-product) | | Understand the data model | [Concepts](/docs/catalog/concepts) | | Edit products in the admin | [The catalog in the admin](/docs/admin/catalog) | | Build a storefront | [Read the catalog](/docs/catalog/storefront) | | Sync from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Look up public routes | [HTTP API](/docs/catalog/http-api) | # Private media storage Back OrbCatalog's media library with your own private Cloudflare R2 or S3-compatible bucket and serve images safely through Catalog. By default, OrbCatalog stores uploaded media in its native `MEDIA` Cloudflare R2 binding. You can point that binding at an existing private R2 bucket, or configure any private AWS S3 or S3-compatible bucket instead. Storage configuration is completely separate from image delivery (`MEDIA_ORIGIN` and `MEDIA_TRANSFORM`). Keeping your bucket private never changes how editors upload, replace or use images in the admin. ## Choose a storage backend Point the `MEDIA` binding's `bucket_name` in `wrangler.jsonc` at your existing private EU R2 bucket. No S3 credentials are required. You can also set `MEDIA_STORE=r2` explicitly. Set these **server-side** Worker vars: ```json { "MEDIA_STORE": "s3", "MEDIA_S3_ENDPOINT": "https://s3.eu-central-1.amazonaws.com", "MEDIA_S3_BUCKET": "merchant-private-media", "MEDIA_S3_REGION": "eu-central-1", "MEDIA_MANAGED_ROOT": "orbcatalog/test/" } ``` Install `MEDIA_S3_ACCESS_KEY_ID` and `MEDIA_S3_SECRET_ACCESS_KEY` (plus optional `MEDIA_S3_SESSION_TOKEN`) as Worker secrets via `wrangler secret put` (or `.dev.vars` locally). Never put them in vars, URLs or logs. Requests use path-style addressing and AWS SigV4 headers over HTTPS (no redirects, no presigned URLs). Keep buckets in the EU. ## Reserve `MEDIA_MANAGED_ROOT` `MEDIA_MANAGED_ROOT` defaults to `orbcatalog/` and must end with `/`. Choose a separate unused prefix for each environment sharing a bucket **before importing media** (changing it does not migrate existing files). | Prefix inside `MEDIA_MANAGED_ROOT` | Holds | | ----------------------------------------------- | -------------------------------------------------------- | | `{mediaId}` | Owned original uploads | | `renditions/{mediaId}/{validator}/{width}.webp` | Generated WebP renditions | | `locators/{mediaId}.json` | Protected JSON locators for registered private originals | | `replacing/{mediaId}/...` | Staging and permanent safety fences for replacements | Catalog never overwrites or deletes objects outside `MEDIA_MANAGED_ROOT`. Do not apply automated deletion lifecycle rules to `replacing/`, as its tiny fence markers protect concurrent replacement safety. ## Register existing private objects Selecting a bucket does not automatically import or expose its existing files. To let a Source register selected private objects without copying their bytes, configure `MEDIA_REGISTRATION_GRANTS` keyed by the Source's stable ID: ```json { "MEDIA_STORE_ID": "merchant-images-eu", "MEDIA_REGISTRATION_GRANTS": { "src_akeneo000002": [{ "prefix": "products/" }, { "key": "campaigns/winter-hero.jpg" }] } } ``` - **Explicit consent:** Grants authorize **public shopper delivery** through Catalog for those exact keys or directory prefixes (`products/` never matches `products-backup/`). Keys inside `MEDIA_MANAGED_ROOT` are always refused. - **`MEDIA_STORE_ID`:** Required when enabling registration on a native R2 binding so Catalog can verify physical bucket identity across deploys. Keep it stable for the same bucket; change it if binding a different bucket. - **Read-only originals:** Sources register files with [`registerMedia()`](/docs/catalog/sources#register-selected-private-objects). Registered originals are never modified or deleted by Catalog, even after unregistering or 30-day retention cleanup. - **Already-public CDN files:** Do not register them here; use [public media links](/docs/catalog/sources#keep-images-on-an-existing-cdn) instead. ### Replace a registered image with an owned copy Editors cannot overwrite a read-only registered original, but can adopt a new owned copy at the same media ID via **Media → Use owned copy** (`PUT /panel/media/{mediaId}/owned-copy`). - Keeps the same media ID, alt text, focal point, folder and all product/page references. - Requires matching aspect ratio (within 1% tolerance). - Leaves the original object in your bucket untouched and switches delivery to an immutable digest URL. ## Delivery and replacement freshness | Asset type | Delivery URL | Browser / Edge cache | Behavior on replace | | ------------------------- | -------------------------------- | ---------------------- | ---------------------------------------------------- | | Owned upload / owned copy | `/media/{id}/{sha256}[/{width}]` | 1 year, `immutable` | URL switches to new digest; old digest returns `404` | | Registered private object | `/media/{id}/current[/{width}]` | 30 s / 30 s, no stale | Revalidates within 30 s (`must-revalidate`) | | External public CDN link | Original external URL | External host's policy | Served directly without proxying | Catalog streams registered private originals through its `/media/{id}/current` handler using the protected locator JSON, never exposing raw bucket keys, endpoints or credentials, and without querying Postgres on image reads. ## Protected-origin recipes ### Cloudflare: private R2 with public Catalog delivery 1. Bind your private EU R2 bucket as `MEDIA`, set `MEDIA_MANAGED_ROOT`, and configure `MEDIA_STORE_ID` + `MEDIA_REGISTRATION_GRANTS` if registering existing objects. 2. Disable both R2's public development URL **and** any public custom domain on the bucket. 3. Point `PUBLIC_URL` (and optional `MEDIA_ORIGIN`) at Catalog's media handler, never directly at R2. 4. Set `MEDIA_TRANSFORM` to `none` or `cloudflare` (with the Images binding), and ensure Cloudflare Cache Rules do not override origin TTLs or enable Always Online for media. ### CloudFront: private S3 with Catalog as custom origin 1. Keep the EU S3 bucket private with S3 Block Public Access enabled and give Catalog's IAM credentials `GetObject` on registered prefixes plus `GetObject`, `PutObject`, `DeleteObject` inside `MEDIA_MANAGED_ROOT` (and bucket-level `s3:ListBucket` so missing objects return `404` rather than `403`). 2. Create a CloudFront **custom HTTPS origin** pointing at Catalog's `/media/*` routes (GET/HEAD only; do not expose `/panel` or sync routes). Set `MEDIA_ORIGIN` to the CloudFront `/media` URL. 3. Configure a custom cache policy (`Min TTL = 0`, `Default TTL = 0`, `Max TTL = 31536000`, error caching `0`, no arbitrary query strings) so CloudFront honors Catalog's `Cache-Control` headers. 4. Note that CloudFront does not process `Cloudflare-CDN-Cache-Control` or Catalog `Cache-Tag` purges, and S3 OAC does not apply to a custom HTTP origin. Required S3/R2 operations are `HeadObject`, `GetObject`, `PutObject` (with `If-Match` / `If-None-Match: *`), `ListObjectsV2` and `DeleteObject`. Live AWS S3 and CloudFront acceptance should be verified against your own EU bucket and cache policy before production use. ## Next steps | You want to | Read | | ----------------------------------- | --------------------------------------------- | | Register private objects from a PIM | [Sync from a PIM or ERP](/docs/catalog/sources) | | Manage images in the admin | [Media library](/docs/admin/catalog#media-library) | | Look up media delivery routes | [HTTP API](/docs/catalog/http-api) | # Sync from a PIM or ERP Push products, categories, register entries, media, offers and stock from external systems with @orbcatalog/client/source. A **Source** is an external system (such as a PIM or ERP) that owns specific fields on the products it syncs. Its API key authenticates it and makes its owned fields read-only in the admin panel. ## Push media, products, offers and stock Add a Source under _Connections_ in the admin (owner only; editors receive `owner_only`). Copy its key once, then push data with `@orbcatalog/client/source`: ```ts import { source } from "@orbcatalog/client/source"; const pim = source({ url: "https://catalog.clayandcrema.de", key: env.ORBCATALOG_AKENEO_KEY }); // 1. Queue images by URL (fetched in the background) const sent = await pim.media([{ url: "https://pim.clayandcrema.de/assets/daybreak-250g.jpg" }]); const acceptedUrls = sent.rows.filter((r) => r.outcome === "accepted").map(({ url }) => url); const rejected = await pim.fetchedImages(acceptedUrls); // 2. Sync products (client batches at 1,000 rows per NDJSON call) const { rows } = await pim.products([ { ref: "DAYBREAK", type: "coffee", name: { de: "Daybreak", en: "Daybreak" }, attributes: { roast: "medium", description: { en: "

Washed espresso blend.

" } }, variants: [ { sku: "DAYBREAK-250G-BEANS", axes: { grind: "whole-bean" }, weightInGrams: 270, netContent: { amount: 250, unit: "g" }, }, ], categories: ["coffee/espresso"], media: [ { url: "https://pim.clayandcrema.de/assets/daybreak-250g.jpg", alt: { en: "Daybreak bag" } }, ], }, ]); for (const row of rows) { if (row.outcome === "rejected") report(row.ref, row.errors); } ``` Every row is judged independently (`created`, `updated`, `unchanged`, `rejected`). Rows whose canonical hash matches the previous sync return `unchanged` and write nothing. Every write carries an `Idempotency-Key` and retries transient `429`, `5xx` and `409 request_in_progress` responses automatically. To resume a batch in a new process, [give it a key](#resume-a-batch-after-a-restart). ### Offers, stock and lifecycle ```ts continues // 3. Offers (fast lane: no draft or version) await pim.offers([ { sku: "DAYBREAK-250G-BEANS", channel: "de", price: { amount: 1290, currency: "EUR" }, sale: { price: { amount: 1090, currency: "EUR" }, from: "2026-11-27T00:00:00+01:00", until: "2026-12-01T00:00:00+01:00", }, availability: "in_stock", deliveryDays: { min: 1, max: 3 }, }, ]); // 4. Stock counts (from the Source that owns stock; null stops counting) const erp = source({ url: "https://catalog.clayandcrema.de", key: env.ORBCATALOG_ERP_KEY }); await erp.stock([ { sku: "DAYBREAK-250G-BEANS", available: 42, asOf: "2026-10-01T06:00:00+02:00" }, { sku: "GUJI-250G-BEANS", available: null, asOf: "2026-10-01T06:00:00+02:00" }, ]); // 5. Lifecycle await pim.discontinue(["HAND-GRINDER"]); // readable, marked discontinued, not sold await pim.withdraw(["COLD-BREW-6X330"]); // 404 everywhere, releases SKUs await pim.live(["HAND-GRINDER", "COLD-BREW-6X330"]); // restores last published version ``` ## Resume a batch after a restart Give a batch a key your job keeps before its first call. When the process dies and the job runs again, send the same rows under the same key: ```ts continues // The job as your ERP keeps it: saved before the first call, read back after a restart const job = { id: "withdrawals-2026-11-21", refs: ["COLD-BREW-6X330"], callsDone: 0 }; await erp.withdraw(job.refs, { key: job.id, from: job.callsDone, answered: (call) => { job.callsDone = call + 1; // save it with the job }, }); ``` Call `n` of the batch goes out with the `Idempotency-Key` `.`. A call the catalog already took is answered from its first answer and writes nothing again, so a `live()` sent in between stays live. `from` skips the calls whose answers `answered` let you keep; the answer then covers only the calls sent now. Every keyed method takes these options: `products`, `categories`, `entries`, `offers`, `stock`, `discontinue`, `live` and `withdraw`. | Case | What happens | | ---------------------------------- | ---------------------------------------------------------------------------- | | Same key and rows, within 24 hours | Each call taken is answered from its first answer. | | A call cut off half-way | Its retry goes on after the last write the catalog took. | | Its first request died | `409 request_in_progress` for up to 10 minutes, then the retry takes over. | | Same key, other rows in a call | `422 idempotency_key_reused`. A new batch takes a new key. | | After 24 hours | The key is forgotten. A call sent again is a new call and applies again. | | No `key` | A key per batch. Retries in the process replay; a restart sends a new batch. | A retry of a call cut off half-way answers the whole call, the rows the catalog took before as they landed then, so a row another call changed since is not landed again. Offers and stock land a call at once, so they never stop half-way. Raw HTTP callers send their own `Idempotency-Key` per call, up to 255 visible characters. ## Ownership and publishing rules | Scope | Rule | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | | Product fields | Claimed per product when synced; two Sources with disjoint fields can share one product. Conflicting fields fail with `field_owned`. | | Editorial products | Products created by editors or imports belong to editors in every field. Source writes reject with `product_editorial`. | | Publish on sync | Enabled on the Source: publishes only the Source's fields without touching an editor's draft. Disabled: waits in draft. | | Category tree | One Source owns the entire tree (`tree_not_owned` for others). Parents must precede children; moves are live immediately. | | Registers | One Source per register (`owns.registers`, `register_not_owned` for others). Entries stay live while linked by live products. | | Stock | One Source owns stock catalog-wide (`stock_not_owned` for others). Holds never lower the public band; orders and new counts do. | ### Categories, registers and reading back refs ```ts continues await pim.categories([ { ref: "coffee", position: 0, title: { de: "Kaffee", en: "Coffee" }, slug: { de: "kaffee", en: "coffee" }, }, { ref: "coffee/espresso", parent: "coffee", position: 0, title: { de: "Espresso", en: "Espresso" }, slug: { de: "espresso", en: "espresso" }, }, ]); await pim.entries("brands", [ { ref: "clay-and-crema", name: { en: "Clay & Crema" }, slug: { en: "clay-and-crema" }, image: { url: "https://pim.clayandcrema.de/assets/logo.png" }, link: "https://clayandcrema.de", }, ]); await pim.withdraw({ register: "brands", entries: ["old-roaster"] }); await pim.withdraw({ categories: ["coffee/archive"] }); ``` List every ref this Source owns (in product creation order, `limit` up to `100`) with `refs()`: ```ts continues const broughtRefs = new Set(); let brought = await pim.refs({ limit: 100 }); for (;;) { for (const ref of brought.data) broughtRefs.add(ref); if (brought.next === undefined) break; brought = await pim.refs({ limit: 100, after: brought.next }); } ``` ### Prices, rich text and variants - **Prices are a ledger.** Each Source's `price` and `sale` replace only its own earlier entries. A sale wins only while it is lower than the active base price; sales start and end at their timestamps on read. - **Rich text is HTML.** Paragraphs, lists, line breaks, bold, italic, `http(s)` links and allowed headings are kept; unknown attributes are stripped, empty HTML is rejected, and malformed markup is rejected at its pointer. - **Pictures per axis.** When a Type sets `picturesBy`, tag images with `{ url, shows: ["moss"] }`. Images without `shows` appear on every variant. - **Variant appointments.** Sending `appointments` on a variant replaces its Type default completely; omitting it on a variant clears its override. - **Lifecycle.** `live()` restores the last published version without publishing drafts. A withdrawn product releases its SKUs; restoring it fails with `sku_taken` if another product claimed one. ## Three ways to bring media | Method | When to use | How it behaves | | ----------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `media()` | Copy images into OrbCatalog storage | Background fetch (HTTPS, JPEG/PNG/WebP/AVIF, max 20 MB, 8 retries). Poll with `fetchedImages(urls)` or `images()`. | | `linkMedia()` | Keep images on your existing CDN | Immediate `linked` status; browsers fetch your CDN directly with up to 20 declared renditions. No proxy or transforms. | | `registerMedia()` | Reference objects in a private bucket | Max 50 rows/call; checks HEAD metadata only against [configured grants](/docs/catalog/media-storage#register-existing-private-objects). | ### Keep images on an existing CDN ```ts continues const linked = await pim.linkMedia([ { url: "https://cdn.clayandcrema.de/products/espresso-cup-moss.jpg", width: 1200, height: 900, contentType: "image/jpeg", renditions: [ { url: "https://cdn.clayandcrema.de/products/espresso-cup-moss-320.jpg", width: 320, height: 240, }, { url: "https://cdn.clayandcrema.de/products/espresso-cup-moss-640.jpg", width: 640, height: 480, }, ], }, ]); ``` Use stable public HTTPS URLs without query tokens or fragments. External files reject byte replacement (`media_external`); use versioned URLs for updates. ### Register selected private objects ```ts continues const privateImages = await pim.registerMedia([ { key: "products/espresso-cup-moss.jpg", width: 1200, height: 900, contentType: "image/jpeg" }, ]); for (const row of privateImages.rows) { if (row.outcome === "rejected") { report(row.key, row.errors); continue; } await pim.products([{ ref: "ESPRESSO-CUP", type: "ceramics", media: [{ media: row.media }] }]); } ``` Grant only image prefixes intended for shoppers. Registered files join the public media library; products reference the returned `media` ID, never the private key or bucket locator. Ordinary byte replacement fails with `media_readonly`. Editors can adopt a file with **Use owned copy** ([Media storage](/docs/catalog/media-storage#replace-a-registered-image-with-an-owned-copy)); resending `registerMedia()` after adoption returns the owned ID without reverting it. ## Staff product handover and Type moves Use `@orbcatalog/client/products` with an authenticated staff `fetch` (Products `edit` permission) to hand a Source product to editors or change a product's Type. ### Hand a product to editors ```ts import { products } from "@orbcatalog/client/products"; import type { Fetch } from "@orbcatalog/client"; async function handToEditors(staffFetch: Fetch, ref: string, idempotencyKey: string) { const staffProducts = products({ url: "https://catalog.clayandcrema.de", fetch: staffFetch }); const found = await staffProducts.view(ref); if (found.status !== "found") return found; const answer = await staffProducts.handover( ref, { basedOn: found.view.draft.revision }, { idempotencyKey }, ); if (answer.status === "ok") return answer.body; return answer.status; // draft_stale | product_not_found } ``` After handover (`POST /panel/products/{ref}/handover`), subsequent Source syncs for that `ref` reject with `product_editorial`. Offers and stock remain independent. ### Move a product to another Type ```ts import { products } from "@orbcatalog/client/products"; import type { Fetch } from "@orbcatalog/client"; async function moveToType(staffFetch: Fetch, ref: string, type: string, idempotencyKey: string) { const staffProducts = products({ url: "https://catalog.clayandcrema.de", fetch: staffFetch }); const found = await staffProducts.view(ref); if (found.status !== "found") return found.status; const change = { basedOn: found.view.draft.revision, type }; const preview = await staffProducts.previewTypeChange(ref, change); if (preview.status !== "ok") return preview.status; const { dropped, kept, check } = preview.body; if (check.result !== "ready") return check; const changed = await staffProducts.changeType(ref, change, { idempotencyKey }); return changed.status === "ok" ? { revision: changed.body.revision, dropped, kept } : changed.status; } ``` `changeType()` updates only the draft; publish separately to take it live. The same client also exposes `changePublication(ref, "withdrawn" | "live", { idempotencyKey })` and `saveDraft(ref, { basedOn, edits }, { idempotencyKey })`. ## Customize | You want to | Do this | Default | | ------------------------------------------ | ---------------------------------------------- | ------------------------------- | | Require editorial review before going live | Turn off **Publish on sync** on the Source | Publishes Source fields on sync | | Tune the low-stock band threshold | Change the count in _Settings → Stock_ | `5` units | | Import spreadsheets without writing code | Use [Import](/docs/admin/import) in the admin panel | Source API sync | | Keep images on an existing CDN or bucket | Use `linkMedia()` or `registerMedia()` | Background copy via `media()` | ## Next steps | You want to | Read | | ------------------------------------------ | ------------------------------------------------ | | Configure private media storage and grants | [Media storage](/docs/catalog/media-storage) | | Follow changes via feed or webhooks | [Follow the catalog's changes](/docs/catalog/changes) | | Rotate Source and reader API keys | [Rotate credentials](/docs/run/credential-rotation) | | Import CSV, JSONL or XLSX in the admin | [Import](/docs/admin/import) | # Read the catalog Render product, category, brand and store-finder pages with @orbcatalog/client and generated TypeScript types. `@orbcatalog/client` reads published products, offers, categories, registers, Locations and appointment times from OrbCatalog with schema-generated TypeScript types. ## Generate types and render a product page Generate a deterministic types file from your live catalog's OpenAPI description, and verify it in CI after Schema publishes: ```sh pnpm add @orbcatalog/client pnpm exec orbcatalog types --url https://catalog.clayandcrema.de > app/catalog.types.ts pnpm exec orbcatalog types --url https://catalog.clayandcrema.de --check app/catalog.types.ts ``` Resolve a slug with `route()`, then fetch base product data and short-lived offers in parallel: ```ts import { catalog } from "@orbcatalog/client"; import type { Nordgrat } from "~/catalog.types"; const store = catalog({ url: "https://catalog.clayandcrema.de" }); export async function loader({ params }: LoaderArgs) { const route = await store.route(params.slug, { locale: "de" }); if (route.status === "not_found" || route.kind !== "product") throw notFound(); const [found, offers] = await Promise.all([ store.product(route.ref, { locale: "de" }), store.offers(route.ref, { channel: "de" }), ]); if (found.status !== "found") throw notFound(); const { product } = found; if (route.status === "moved" && product.urls.de !== undefined) throw redirect(product.urls.de, 301); if (product.type === "backpack") { const [brand] = product.attributes.brand; // { ref, name, slug, image } product.attributes.volume; // typed from the Schema } return { product, offers: offers.data, canonical: product.urls.de }; } ``` ### What each product carries | Field | What it gives you | | -------------------- | ------------------------------------------------------------------------------------- | | `product.labels` | Localised attribute labels from the Schema (for example `product.labels.brand`). | | `product.urls` | Canonical URL per Channel, built from each Channel's storefront path settings. | | `product.alternates` | `urls` grouped by locale across every released language for ``. | | `product.search` | `{ title, description? }`, falling back to `product.name` when no SEO title is set. | Renamed slugs return `route.status === "moved"` across any chain of renames until another product, category or entry claims the old slug. Discontinued products remain readable; withdrawn products return `not_found` for every slug they held. ### Unit prices and mini-cart hints Goods sold by measure include `offer.unitPrice` computed from the active price (including sales): ```ts continues const per = { kg: "1 kg", "100g": "100 g", l: "1 l", "100ml": "100 ml", m: "1 m", m2: "1 m²" }; const coffee = await store.offer("DAYBREAK-250G-BEANS", { channel: "de" }); if (coffee.status === "found" && coffee.offer.unitPrice) { const { price, per: unit } = coffee.offer.unitPrice; const euros = new Intl.NumberFormat("de-DE", { style: "currency", currency: price.currency }); console.log(`${euros.format(price.amount / 100)} / ${per[unit]}`); } ``` Use `offer()` for price hints in a mini cart; OrbCart's signed [Quote](/docs/cart/quotes) always decides the checkout total. ### Shipping restrictions and line limits Each variant carries its published shipping traits and per-line quantity cap so your storefront can inform shoppers before checkout: ```ts continues const coldBrew = await store.product("COLD-BREW-6X330", { locale: "de" }); if (coldBrew.status === "found") { for (const variant of coldBrew.product.variants) { variant.shipping; // { weightInGrams: 3600, restrictions: ["bulky", "pickup_only"] } variant.limits; // { max: 2 } when capped, otherwise undefined } } ``` ### Error handling Expected misses return discriminated statuses (`not_found`, `locale_unavailable`) so you can switch on them. Invalid requests, `429` and `5xx` responses throw `CatalogError` with the problem payload and `requestId`. Network failures rethrow the underlying `fetch` error. The client reads answers tolerantly, so a storefront keeps working when the catalog is deployed ahead of it: fields a newer catalog adds, at any depth, are left out of what you get. A known field that is missing or malformed, or a status or enum value the client does not know, still throws `CatalogError` with the answer's status and no problem payload. Update the client to read new fields. ## Storefront paths and sitemaps Each Channel configures URL templates per locale in _Settings → Shops_. `product` is the default; `productByType` overrides it by published Type key: ```json { "origin": "https://clayandcrema.de", "product": "/p/{slug}", "productByType": { "coffee": "/coffee/{slug}", "service": "/service/{slug}" }, "category": "/shop/{path}", "entry": "/{register}/{slug}" } ``` With `category: "/shop/{path}"`, every ancestor contributes its published slug in the requested locale (`{slug}` keeps a leaf-only path). Always render the delivered `urls` instead of assembling paths from leaf slugs, because template changes and ancestor moves do not create redirect history. `route()` resolves a single slug, not a full path. ### Stream sitemap entries `sitemap()` streams published products (including readable discontinued ones) and categories from `/feeds/sitemap.ndjson` without caching: ```ts continues for await (const entry of store.sitemap({ channel: "de", locale: "de" })) { entry.url; // canonical URL in this Channel and locale entry.alternates; // alternates for languages sold by this Channel } ``` Write the stream into partitioned XML sitemaps and add OrbPage pages or register entries from their own public reads. ## Categories and brands ### Category tree and product lists Fetch a navigation tree down to a given depth (default `2`) in one cached call, then load a category and its paged `ProductCard[]` list: ```ts continues const menu = await store.categoryTree({ locale: "de", depth: 2 }); const branch = await store.categoryTree({ parent: "coffee", locale: "de", depth: 3 }); const category = await store.category("coffee/single-origin", { locale: "de" }); if (category.status !== "found") throw notFound(); const children = await store.categories({ parent: "coffee/single-origin", locale: "de" }); const page = await store.products({ category: "coffee/single-origin", locale: "de", limit: 24, after: new URL(request.url).searchParams.get("after") ?? undefined, }); ``` `categoryTree()` returns depth-first roots (or children of `parent`) in position order, with `parent`, breadcrumb `path`, `urls` and `hasChildren`. Only categories whose full ancestor chain released the locale appear. ### Register entries (brands) Resolve register entries (such as `brands`) with `route()` and `entry()`, or list them with `entries()`: ```ts continues const route = await store.route("clay-and-crema", { locale: "de" }); if (route.status !== "found" || route.kind !== "entry") throw notFound(); const found = await store.entry(route.register, route.ref, { locale: "de" }); if (found.status !== "found") throw notFound(); const brands = await store.entries("brands", { locale: "de", limit: 100 }); ``` ## Store finder and appointments ### Locations Read every open Location serving a Channel, including its address, services (`pickup`, `shipping`, `appointments`), weekly `hours` and upcoming `days`: ```ts continues const stores = await store.locations.list("de"); for (const location of stores) { location.address; // absent for warehouses shoppers do not visit location.services; // ["pickup", "appointments"] location.hours; // openingHoursSpecification rules and exceptions location.days[0]; // { date, open: [{ start, end }] } or closed reason } ``` New catalogs start with a shipping Location named `Warehouse` (`loc_warehouse000`) that serves no Channels until you assign it in _Settings_. ### Free appointment times Query bookable slots up to 14 days ahead, or inspect a SKU's effective published appointment needs: ```ts continues const times = await store.appointments.freeTimes({ location: "loc_roastery0001", sku: "TASTING-SESSION", from: "2026-12-05T00:00:00+01:00", days: 7, }); const effective = await store.appointments.needs("TASTING-SESSION"); if (effective.status === "found") { effective.needs.requirements; // capabilities per concrete resource effective.needs.buffer; effective.needs.leadMinutes; effective.needs.choice; } ``` A variant's `appointments` setting replaces its Type default completely rather than merging with it. Per-appointment work jobs take their duration once regardless of quantity; `per: "unit"` multiplies by line quantity, and rentals use an explicit return `end`. Free times are `private, no-store`; the database prevents double-booking any resource. ## Customize | You want to | Do this | Default | | -------------------------------------- | --------------------------------------------------------- | ------------------------------------- | | Override product URLs per Type | Set `productByType` in _Settings → Shops_ | `product` template (`/p/{slug}`) | | Keep flat category URLs | Use `{slug}` instead of `{path}` in the category template | Full ancestor `{path}` | | Control navigation tree depth | Pass `depth` to `categoryTree()` | `2` levels | | Add search facets and full-text search | Connect [OrbSearch](/docs/search) for faceted listings | Paged category lists via `products()` | ## Next steps | You want to | Read | | ------------------------------------------------- | ------------------------------------------------ | | Understand Types, Variants, Offers and Channels | [Catalog concepts](/docs/catalog/concepts) | | Sync products, prices and stock from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Follow changes via feed or signed webhooks | [Follow the catalog's changes](/docs/catalog/changes) | | Look up every HTTP endpoint | [Catalog HTTP API](/docs/catalog/http-api) | # Your first product Go from an empty admin to a live product shoppers can open, using the admin screens alone. This walkthrough takes you from a fresh, empty admin to your first published product without writing code. The **First steps** checklist appears on _Products → Overview_ while your catalog has no published products. If you started with `pnpm dev`, the Clay & Crema demo products are already published, so you can follow the same screens directly. ## Publish your first product ### Set up languages and your shop Open _Settings → Languages_ and choose the languages your shop sells in. The first language is your default authoring language. Next, open _Settings → Shops_ and add your shop: its currency, country, tax mode (gross or net) and storefront URL, such as `https://shop.example.com` with products at `/p/{slug}`. Select **Publish** to apply your settings. ### Design a Type A **Type** defines a kind of product and its fields, such as a backpack's volume and colour. Open _Products → Types_, select **Add Type**, give it a name and add its attributes. Mark the fields required for publishing and the attributes that variants differ by, such as colour. Select **Publish** on the Schema so products can use the Type. ### Create the product and a variant Open _Products_ and select **New product**. Pick your Type, enter a name and keep the suggested reference or enter your own ID. Select **Create** to open the draft. Fill in the fields your Type asks for. Every field saves automatically when you leave it. Then open _Variants_ and add at least one variant with a SKU so shoppers can buy it. ### Publish and open it Select **Publish** on the product page. If a required field is missing in any language, the page highlights exactly what to fix. Once published, the product reaches shoppers within seconds. Follow the link in the product's **Addresses** card to open it in your storefront. ## Bringing products in bulk You do not have to enter products by hand: - **Files:** Open _Products → Import_ to upload CSV, JSON Lines or Excel files ([Import a file](/docs/admin/import)). - **PIM or ERP:** Add a Source in _Connections → Products_ to sync products over the API ([Sync from a PIM or ERP](/docs/catalog/sources)). Its key comes with a ready-to-paste terminal call for your first product. ## Next steps | You want to | Read | | ----------------------------- | ------------------------------------------ | | Edit products at scale | [The catalog in the admin](/docs/admin/catalog) | | Import a spreadsheet | [Import a file](/docs/admin/import) | | Sync from a PIM or ERP | [Sync from a PIM or ERP](/docs/catalog/sources) | | Read products in a storefront | [Read the catalog](/docs/catalog/storefront) | # Run it locally Start OrbCatalog, OrbCart, OrbPage, the admin and the Clay & Crema demo shop on your machine with one command. Run the full OrbCommerce stack on your machine with a single command. It starts every product, migrates Postgres and seeds the **Clay & Crema** demo shop. Just want to look around first? Try the hosted demo shop at [demo.orbcommerce.dev](https://demo.orbcommerce.dev/en). ## Start the stack You need **Node.js 24+**, **pnpm** and **Docker** running locally. From the repository root: ```sh pnpm install pnpm dev ``` When everything is ready, the terminal prints the local addresses: | Service | Address | | ---------- | ------------------------ | | Demo shop | http://localhost:5173/en | | Admin | http://localhost:8789 | | OrbCatalog | http://localhost:8787 | | OrbCart | http://localhost:8797 | | OrbPage | http://localhost:8807 | To sign in to the admin on a fresh setup, use `owner@claycrema.test`. The generated password is stored in `catalog/.env` under `ORBCATALOG_OWNER_PASSWORD` and is never printed to the terminal. ## What `pnpm dev` sets up On the first run, `pnpm dev` handles the full local setup automatically: - **Database:** Starts Postgres via Docker on port `55432` and runs all product migrations. - **Local secrets:** Generates missing secrets (`.dev.vars` and `catalog/.env`) once and leaves existing ones untouched. All secret files are git-ignored. - **Product connections:** Wires OrbCart's keys into OrbCatalog and the demo storefront automatically. - **Demo data:** Seeds Clay & Crema's settings, Schema, stores, categories, 19 products and multilingual pages. Running `pnpm dev` a second time reuses your existing database, secrets and data. Press `Ctrl+C` to stop all processes. To wipe the local database and re-seed from scratch: ```sh docker compose -p orbcommerce down -v pnpm dev ``` ## Test payments with Stripe or PayPal Payment provider sandbox keys cannot be generated automatically. Add your Stripe or PayPal test credentials to `.dev.vars` in the repository root: ```dotenv title=".dev.vars" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... PAYPAL_CLIENT_ID=... PAYPAL_CLIENT_SECRET=... PAYPAL_WEBHOOK_ID=... ``` For Stripe webhooks, forward events to OrbCart in a second terminal: ```sh stripe listen --latest --all-snapshot --forward-to localhost:8797/webhooks/stripe ``` Without provider keys, OrbCart still runs and accepts Carts, but hides payment methods whose provider has no keys configured. With Stripe keys in place, you can check out using `4242 4242 4242 4242` and inspect the Order in the admin. See [Test payments](/docs/cart/test-payments) for more test cards. ## Troubleshooting ### Docker is not running or a port is taken `pnpm dev` checks Docker and all required ports before starting any service, and stops early with the exact cause. Only one checkout can run the full stack at a time. ### Running a single product alone If you only want to run OrbCart on its own, follow the [OrbCart quickstart](/docs/get-started/orbcart). Each product's README documents how to start that product individually. ## Next steps | You want to | Read | | ------------------------------- | ------------------------------------------------ | | Publish your own first product | [Your first product](/docs/get-started/first-product) | | Manage products in the admin | [The catalog in the admin](/docs/admin/catalog) | | Read products from a storefront | [Read the catalog](/docs/catalog/storefront) | | Write OrbPage content from code | [Write content from code](/docs/page/write-content) | | Deploy the stack to Cloudflare | [The test environment](/docs/run/test-environment) | # OrbCart quickstart Run OrbCart locally in minutes, complete a test purchase, and make your first checkout in five lines of code. OrbCart runs the transaction layer of your shop: Cart, Quote, Payment and Order. You keep your catalog and storefront, and OrbCart asks your systems for current prices and stock when a buyer checks out. OrbCart is pre-release and not published to npm yet. You need the repository checkout, **Node.js 24+**, **pnpm**, **Docker** and a free **Stripe** test account. Just browsing? [Try the live demo](https://demo.orbcommerce.dev/en): nothing is charged or shipped. ## Run a complete checkout locally ### Install dependencies From the repository root: ```sh pnpm install ``` ### Add your Stripe test keys Create `.dev.vars` in the repository root with your Stripe test keys. If you also want PayPal, add its sandbox credentials here too: ```dotenv title=".dev.vars" STRIPE_SECRET_KEY=sk_test_... STRIPE_PUBLISHABLE_KEY=pk_test_... STRIPE_WEBHOOK_SECRET=whsec_... ``` `pnpm dev` generates `ROOT_SECRET` and all internal keys automatically on first run. See [Payments](/docs/cart/payments) for PayPal and other providers. ### Start the local stack and Stripe webhooks Start the local services from the repository root: ```sh pnpm dev ``` In a second terminal, forward Stripe webhooks to OrbCart on port `8797`: ```sh stripe listen --latest --all-snapshot --forward-to localhost:8797/webhooks/stripe ``` Copy the `whsec_...` signing secret that `stripe listen` prints into `STRIPE_WEBHOOK_SECRET` in `.dev.vars` and restart `pnpm dev`. You only need to do this once. ### Complete a test purchase Open [http://localhost:5173/en](http://localhost:5173/en), add an item to the Cart and check out with made-up details and a [test card](/docs/cart/test-payments) such as `4242 4242 4242 4242`. Once paid, the Order appears in the admin at [http://localhost:8789](http://localhost:8789). ## A purchase in five lines Under the hood, an entire purchase with `@orbcart/client` is four calls. `shipTo` is the buyer's address and `payment` is the card field mounted on your page: ```ts import { createCommerce } from "@orbcart/client"; const commerce = createCommerce({ url: "http://localhost:8797", key: "pk_test_..." }); const cart = await commerce.cart(); await cart.add("DAYBREAK-250G-BEANS"); const quote = await cart.quote({ shipTo, contact: { email: "anna@example.com" } }); const result = await quote.pay({ payment }); ``` When payment succeeds, `result.status` is `"ordered"` and `result.order.number` looks like `CC-2026-004711`. See [Quotes and orders](/docs/cart/quotes#4-place-the-order) for every other outcome, or [How it works](/docs/cart/how-it-works) to trace this purchase through the server. ## Run OrbCart without OrbCatalog OrbCart does not require OrbCatalog or Postgres. A minimal standalone Worker only needs `channels` and an `offers` function: ```ts title="src/worker.ts" worker import { defineCommerce } from "@orbcart/runtime"; export * from "@orbcart/runtime/objects"; export default defineCommerce({ channels: { de: { currency: "EUR", pricesIncludeTax: true, locale: "de-DE" }, }, offers: (lines, { currency }) => lines.map(({ reference }) => ({ reference, title: "Daybreak · 250 g · Whole bean", price: { amount: 1290, currency }, taxCategory: "standard", })), }); ``` Start it locally with `pnpm exec orbcart dev --channel de --keys .orbcart/local.env` (with `ROOT_SECRET` in `.dev.vars` and `ENVIRONMENT=test` in `wrangler.jsonc`). When no `HYPERDRIVE` binding is configured, `orbcart dev` skips Postgres migrations automatically. See [Configuration](/docs/cart/configuration) to add shipping, tax and payment providers. ## Where things live When exploring the example commerce Worker in the repository, these four files do most of the work: | Path | What you change there | | ------------------------------------------- | ------------------------------------------------------ | | `apps/nordgrat-cart-worker/src/commerce.ts` | Markets, shipping, payment methods and discount codes. | | `apps/nordgrat-cart-worker/src/offers.ts` | How prices and product facts reach OrbCart. | | `apps/nordgrat-cart-worker/src/catalog.ts` | Stock checks against the catalog. | | `apps/nordgrat-cart-worker/src/systems.ts` | ERP order hand-off and parcel labels. | ## Troubleshooting ### Payment methods do not appear in checkout A provider in `payments` is missing its credentials in `.dev.vars`. OrbCart hides methods for unconfigured providers and logs which ones were skipped. Add the missing keys and restart. ### A payment stays `"processing"` `stripe listen` is not running, or its signing secret does not match `STRIPE_WEBHOOK_SECRET` in `.dev.vars`. Without webhooks, OrbCart cannot receive the final payment confirmation. ### `origin_not_allowed` in the browser Your storefront is running on a host that is not listed in the Channel's `origins`. `localhost` is always allowed in test mode. ## Next steps | You want to | Read | | ------------------------------------- | -------------------------------------- | | Understand the mental model | [Concepts](/docs/cart/concepts) | | Configure markets, shipping and rules | [Configuration](/docs/cart/configuration) | | Connect your own prices and products | [Offers](/docs/cart/offers) | | Drop in a ready-made React checkout | [React checkout](/docs/cart/react-checkout) | # Overview OrbCommerce is four products for commerce that fit together and can be used one at a time. Pick a product, or follow a path through several. Four products. **One shop.** OrbCatalog knows the products, OrbSearch finds them, OrbPage tells their story and OrbCart sells them. Start with one and add the others when you need them. - [Run the family locally](/docs/get-started) - [Open the demo shop](https://demo.orbcommerce.dev/en) ## Pick a product Each product has its own section with the same layout: an overview, core concepts, task guides and a reference. You never need to read about a product you do not use. ### OrbCatalog Knows the products. Types, variants, prices and pictures in one database, edited in the admin or synced from a PIM. - [Overview](/docs/catalog) - [Concepts](/docs/catalog/concepts) - [HTTP API](/docs/catalog/http-api) ### OrbSearch Finds them. Search that understands the query, applies your rules and explains each result it gives back. - [Overview](/docs/search) - [Quickstart](/docs/search/quickstart) - [Concepts](/docs/search/concepts) ### OrbPage Tells their story. Pages, menus and forms that editors build from your shop's sections. It is built on OrbCatalog. - [Overview](/docs/page) - [Sections and slots](/docs/page/sections) - [Read the content](/docs/page/content) ### OrbCart Sells them. Cart, checkout, tax, shipping, payment and Order, with prices and stock asked from your systems. - [Overview](/docs/cart) - [Quickstart](/docs/get-started/orbcart) - [Concepts](/docs/cart/concepts) ## Or follow a path Follow a path to walk through several products in the order you build. ### Build a storefront Products, content and a checkout in the framework you like. 1. [Read the catalog](/docs/catalog/storefront) 2. [Declare sections](/docs/page/sections) 3. [Add a cart](/docs/cart/carts) 4. [Take payments](/docs/cart/payments) ### Connect your systems Your PIM and ERP send products and stock and receive Orders. 1. [Sync from a PIM or ERP](/docs/catalog/sources) 2. [Answer prices and stock](/docs/cart/erp-prices-and-stock) 3. [Hand Orders to your ERP](/docs/cart/erp-order-handoff) 4. [React to Order events](/docs/cart/order-events) ### Work in the admin Products, orders and pages in one place for the whole team. 1. [Your first product](/docs/get-started/first-product) 2. [Keep the catalog](/docs/admin/catalog) 3. [Import a file](/docs/admin/import) 4. [Bring your own screens](/docs/admin/your-own-module) ### Run it yourself Your own Cloudflare account, your own keys, your own data. 1. [The test environment](/docs/run/test-environment) 2. [Connect the products](/docs/run/connect-the-products) 3. [Deploy OrbCart](/docs/run/deployment) 4. [Rotate credentials](/docs/run/credential-rotation) ## For AI agents Every page has a plain Markdown twin, and every product has its own map. Point your agent to the smallest file that answers its question. | Address | Holds | | ---------------------- | -------------------------------------------------- | | `/llms.txt` | Map of every page, with a one-line summary. | | `//llms.txt` | One product's pages, such as `/cart/llms.txt`. | | `/llms-full.txt` | Every page in a single Markdown file. | | `/.md` | One page as Markdown, such as `/cart/concepts.md`. | | `/openapi/v1.json` | OrbCart's HTTP API as OpenAPI 3.2. | | `/openapi/search.json` | OrbSearch's HTTP APIs as OpenAPI 3.1. | Agents can also act directly: they [manage the catalog over MCP](/docs/catalog/agents) and [buy for a shopper over UCP](/docs/cart/agents). OrbCommerce is pre-release. You build from source today, and npm packages come later. See [OrbCart's status](/docs/cart/status) for what works today. # Read the content Fetch published pages, category slots, menus and live admin previews from OrbPage with @orbpage/client. OrbPage is built on [OrbCatalog](/docs/catalog). Your shop reads published pages, category slots, menus and admin previews through `@orbpage/client`, typed by the sections you [declared](/docs/page/sections). Reads never throw. ## Create a client and read content ```ts import { createClient } from "@orbpage/client"; import { sections } from "./sections"; const content = createClient({ baseUrl: env.PAGE_URL, // e.g. https://content.clayandcrema.de sections, }); const category = await content.categories.get("coffee/single-origin", { locale: "de" }); if (category.ok) { category.content.slots.top; category.content.slots.main; category.content.template; category.content.meta.unresolved; } else { category.problem.code; // "entry_not_found" | "unreachable" | "unexpected_response" } ``` On Cloudflare Workers, pass Service Bindings so published reads hit OrbPage's cached `Delivery` entrypoint directly while previews and forms use the main binding: ```ts continues const bound = createClient({ baseUrl: env.PAGE_URL, sections, fetch: (request) => env.PAGE.fetch(request), delivery: (request) => env.PAGE_DELIVERY.fetch(request), }); ``` ```jsonc title="wrangler.jsonc" "services": [ { "binding": "PAGE", "service": "orbpage" }, { "binding": "PAGE_DELIVERY", "service": "orbpage", "entrypoint": "Delivery" } ] ``` ## Read pages, home and menus ```ts continues const imprint = await content.pages.get("impressum", { locale: "de" }); const home = await content.home.get({ locale: "de" }); const footer = await content.menus.get("footer", { locale: "de" }); if (footer.ok) { for (const item of footer.content.items) item.label; // plus item.href and item.children } ``` - Categories are read by catalog `ref` (for example `coffee/single-origin`), never by slug. - Standalone pages are read by their locale address; the home page has no address. - Unresolved cards, links or pictures are omitted so the page stays intact, and listed in `meta.unresolved` (`not_found`, `discontinued`, `timeout`, `error`, `read_limit`). - When OrbPage is unreachable on a category page, fall back to rendering the catalog products without the editorial slots. ### Read options | Option | Effect | | -------------- | ---------------------------------------------------------------------------------------- | | `locale` | Target locale; falls back to client default, then site default. | | `fallback` | `"default"` serves the site's default locale when untranslated. | | `signal` | `AbortSignal` (such as `AbortSignal.timeout(2000)`); aborted reads return `unreachable`. | | `headingLevel` | First heading level for rich text (`2` by default, never `1`). | | `links` | `"path"` rewrites own links to root-relative paths; `"absolute"` is default. | | `format` | `"md"` returns Markdown instead of JSON (for agents and Markdown twins). | | `include` | `["markdown"]` embeds Markdown under `content.rendered` alongside JSON. | | `preview` | Preview token to read an editor's draft past every cache. | Every response carries `cacheControl` and `age` so your storefront cache never outlives the content. ### Root-relative links Request `links: "path"` (HTTP `links=path`) to receive own-origin links as root-relative paths across section settings, cards, HTML and Markdown: ```ts continues const local = await content.pages.get("impressum", { links: "path", include: ["markdown"] }); const localFooter = await content.menus.get("footer", { links: "path" }); ``` External URLs, `mailto:`, `tel:` and media URLs stay absolute. Editors can also enter site-relative `path` links (such as `/booking?service=tasting#time`) that follow each environment's origin automatically. ## Rendered HTML conventions - **Decorative pictures:** delivered with empty `alt=""` and omitted from Markdown. Linked pictures must have an accessible alt text before publishing. - **Form inputs:** spread `constraintsOf(field)` from `@orbpage/client` onto inputs to apply validation attributes and `autoComplete` hints from the field's `purpose`. - **Tables:** wrapped in `div.op-table` around a semantic `` with `
` scopes; add `overflow-x: auto` to the wrapper for narrow viewports. - **Videos:** delivered as `figure.op-video` linking to YouTube or Vimeo with `.op-video__poster` and `.op-video__title` (no third-party iframe requests until consent). Read `data-op-provider` and `data-op-video` to mount an inline player after consent. ## Live previews in the admin The admin renders drafts inside your storefront in an iframe. Handle `previewPath` (`/preview`) with `startPreview()`, then pass `previewTokenOf(request)` to your content reads: ```ts continues import { previewPath, previewTokenOf, startPreview } from "@orbpage/client"; import type { StartPreview } from "@orbpage/client"; const pathOf: StartPreview["pathOf"] = async ({ shows, locale }) => { if (shows.kind === "category") return `/${locale}/c/${shows.category}`; if (shows.home) return `/${locale}`; return `/${locale}/${shows.slug ?? ""}`; }; async function handle(request: Request): Promise { if (new URL(request.url).pathname === previewPath) { return startPreview(request, { studio: env.ADMIN_URL, content, pathOf }); } const preview = previewTokenOf(request); const draft = await content.categories.get("coffee/single-origin", { locale: "de", preview }); return Response.json(draft.ok ? draft.content.slots : {}); } ``` ### Checklist for working previews ### Configure each locale's origin Set each locale's `origin` via `manageContent().configure(...)` so the admin posts preview tokens to `{origin}/preview`. ### Handle `/preview` and forward tokens Mount `startPreview()` at `previewPath`, pass `previewTokenOf(request)` to every content read, and wrap preview responses with `previewed(response, env.ADMIN_URL)` so caches never store drafts. ### Mount `PreviewBridge` and marks Render `PreviewBridge` from `@orbpage/react` while previewing, and keep `sectionMark(section.id)`, `slotMark(name)` and `AddToSlot` inside `PageLayout` so clicking a section opens its editor. Expired tokens return `preview_token_expired`; fall back to the published page. ## Lifecycle, archive and re-declaration ### Delete or archive pages Unpublished pages can be permanently deleted (`deletePage`). Once published in any language, a page can only be archived (`archivePage`), which takes every language offline, frees its addresses, revokes preview tokens and stops identity links from resolving while keeping drafts and versions readable. `restorePage` returns an archived page as drafts only (refusing with `page_address_taken` if another active page claimed an address). The home page cannot be deleted or archived. ### Re-declare and migrate sections 1. Run `declareSections(sections, { ...options, check: true })` to inspect `misfits`. 2. Push the new declaration. Live versions keep delivering what still fits; misfit drafts must be updated before saving. 3. For each misfit, overwrite in place (`applyPage`, `applyMenu`, or category/template save + publish), archive it (`archivePage`), or leave it if harmless. ## Current limits Not possible today in OrbPage: - **Site-wide snippets** (such as a global announcement bar). Keep these in storefront code rather than abusing a menu. - **Per-product editorial content** (beyond OrbCatalog product attributes). - **Articles** (locale settings reserve optional article URL templates, but creating and publishing articles is not built yet). ## Customize | You want to | Do this | Default | | -------------------------------------- | ---------------------------------------------- | ------------------------- | | Avoid internet hops on Cloudflare | Pass `fetch` and `delivery` Service Bindings | HTTPS fetch to `baseUrl` | | Serve default locale when untranslated | Pass `fallback: "default"` on reads | Returns `entry_not_found` | | Emit root-relative storefront links | Pass `links: "path"` on reads | Absolute URLs | | Serve Markdown twins for AI agents | Pass `format: "md"` or `include: ["markdown"]` | JSON only | ## Built on OrbCatalog Category slots, product cards, category cards and media assets resolve from [OrbCatalog](/docs/catalog). ## Next steps | You want to | Read | | --------------------------------- | ---------------------------------------------- | | Declare sections, slots and menus | [Declare sections and slots](/docs/page/sections) | | Seed or migrate pages from code | [Write content from code](/docs/page/write-content) | | Render product and category pages | [Read the catalog](/docs/catalog/storefront) | | Rotate OrbPage event signing keys | [Rotate credentials](/docs/run/credential-rotation) | # OrbPage OrbPage holds editorial pages, category content, templates, menus and forms built from your shop's declared sections. Built on OrbCatalog. OrbPage is the content layer of a shop: pages, category content, templates, menus and forms. Your storefront declares the sections editors can use, editors arrange them in the admin's _Content_ area, and your shop reads what they publish. It is built on OrbCatalog, so products, categories and media are read live and never copied. Reading a category's editorial content through `@orbpage/client` is fully typed against your declared sections: ```ts import { createClient } from "@orbpage/client"; import { sections } from "./sections"; const content = createClient({ baseUrl: env.PAGE_URL, // e.g. https://content.example.com sections, }); ``` ```ts continues const read = await content.categories.get("coffee", { locale: "de" }); if (read.ok) { read.content.slots.top; // typed sections in the top slot read.content.slots.main; read.content.template; // the template it inherits from read.content.meta.unresolved; // omitted items (e.g. a discontinued product) } else { read.problem.code; // "entry_not_found", "unreachable" or "unexpected_response" } ``` No read throws. If OrbPage is unreachable, your storefront still renders the catalog category without editorial slots. The client reads answers tolerantly: fields a newer OrbPage adds, at any depth, are left out, while a known field that is missing or malformed returns `unexpected_response`. See [Read the content](/docs/page/content) for pages, menus and live previews. ## What OrbPage does - **Builds pages from your sections.** Your storefront [declares](/docs/page/sections) sections with typed settings and allowed slots. The editor, drafts, publishing and delivery all validate against that single declaration. - **Shares templates across categories.** Categories inherit a template slot by slot until an editor overrides a slot, and can reset back to the template anytime. - **Previews drafts inside your real storefront.** The admin renders drafts inside your shop's actual layout using a short-lived uncached preview token. - **Delivers structured JSON and safe HTML.** Running text arrives as sanitized HTML inside JSON. Discontinued products are omitted automatically and listed in `meta.unresolved`. - **Collects form submissions.** Form answers stay in a dedicated Inbox for 180 days and can emit signed `form.submitted` events. - **Notifies downstream systems.** Every publish, rollback or withdrawal can emit a signed `content.published` event. - **Supports human-approved AI edits.** Agents propose page or template changes over MCP (including column rows); a person approves drafts and publishing separately in the admin. ## What OrbPage leaves to you | OrbPage does not | Who handles it | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Render or style your shop | Your storefront. `@orbpage/react` provides row layout and preview bindings. | | Store products or images | OrbCatalog, read at delivery along with its [media library](/docs/admin/catalog#media-library). | | Display prices or stock | Your storefront. Product cards carry name, URL and primary image only. | | Send form notification emails | Your receiver of the signed `form.submitted` event. | | Host the runtime for you | You deploy one Worker in your own Cloudflare account ([Deployment](/docs/run/deployment#headless-setup-for-catalog-and-orbpage)). | ## Change what you need | Depth | You | Example | | --------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | Configure | Set defaults and help text in your [declaration](/docs/page/sections#declare-sections-slots-and-menus). | Setting defaults, colour palette, menu slots. | | Compose | Let editors arrange sections and rows in the admin. | [Rows](/docs/page/sections#rows-and-columns) in six layouts, [templates](/docs/page/sections#templates). | | Replace | Render each section with your own frontend component. | [Switch on section type](/docs/page/sections#render-a-slot-and-rows). | ## Built on OrbCatalog OrbPage requires OrbCatalog and reads products, categories, media and site languages from it at delivery. OrbPage does not require OrbCart or OrbSearch. See [Connect the products](/docs/run/connect-the-products). ## Next steps | You want to | Read | | ---------------------------------- | ------------------------------------------------------------------------ | | Run the stack locally | [Run it locally](/docs/get-started) | | Declare sections and slots | [Declare sections and slots](/docs/page/sections) | | Read pages, menus and previews | [Read the content](/docs/page/content) | | Seed or import pages from a script | [Write content from code](/docs/page/write-content) | | Connect OrbPage to OrbCatalog | [Connect the products](/docs/run/connect-the-products) | | Provision OrbPage from CI/CD | [Headless setup](/docs/run/deployment#headless-setup-for-catalog-and-orbpage) | # Declare sections and slots Define typed sections, slots, palettes and menus in code so editors can build templates and pages in OrbPage. OrbPage is built on [OrbCatalog](/docs/catalog). Your shop declares typed sections, slots, palettes and menus in code, and editors arrange them into templates and pages in the admin's _Content_ area. | Concept | What it is | Defined by | | ------------ | --------------------------------------------------------------------- | ---------- | | **Section** | A building block with typed settings (such as a hero or product row). | Your shop | | **Slot** | A named area on a category, page or home page that holds sections. | Your shop | | **Palette** | Named colours shown as swatches in the admin; delivered as names. | Your shop | | **Menu** | A named navigation slot (such as `footer`) that editors populate. | Your shop | | **Template** | Default slot content shared by categories that follow it. | An editor | | **Page** | A category page, home page or standalone page built from sections. | An editor | ## Declare sections, slots and menus `declare()` from `@orbpage/client` defines your contract and exports TypeScript types for your renderers: ```tsx import { declare, setting } from "@orbpage/client"; import type { BodyOf, HomeSlotsOf, SectionOf, SlotItem, SlotsOf } from "@orbpage/client"; export const sections = declare({ palette: { cream: { label: "Cream", value: "#f6f4ef" }, moss: { label: "Moss", value: "#3e5a48" }, }, sections: { hero: { name: "Hero", settings: { title: setting.line("Title").describe("A few words that name the page."), text: setting.text("Text").optional(), picture: setting.picture("Picture").optional(), link: setting.link("Button link").optional(), label: setting.line("Button text").optional(), tone: setting.colour("Background"), }, }, text: { name: "Text", settings: { body: setting.text("Text"), width: setting.choice("Width", { narrow: "Narrow", wide: "Wide" }), }, }, productRow: { name: "Product row", settings: { title: setting.line("Title").optional(), products: setting.products("Products", { max: 12 }), columns: setting.number("Columns", { min: 2, max: 4 }).default(4), }, }, }, slots: { category: { top: { name: "Top", sections: ["hero"] }, main: { name: "Main", sections: ["text", "productRow"] }, }, page: { body: { name: "Body", sections: ["text"] }, }, home: { body: { name: "Body", sections: ["hero", "text", "productRow"] }, }, }, menus: { footer: { name: "Footer" } }, }); export type Section = SectionOf; export type CategorySlots = SlotsOf; export type PageSlots = BodyOf; export type HomeSlots = HomeSlotsOf; ``` Slots accept only declared section keys, so typos fail at compile time. `slots.home` and `slots.page` are independent and default to empty when omitted. ## Render a slot and rows Use `PageLayout` from `@orbpage/react` and switch exhaustively on `section.type`: ```tsx continues import { PageLayout } from "@orbpage/react"; function Slot({ sections }: { sections: readonly SlotItem
[] }) { return ( {(section) => } ); } function ContentSection({ section }: { section: Section }) { switch (section.type) { case "hero": return

{section.settings.title}

; case "text": return
; case "productRow": return ( ); } } ``` Unknown section types are omitted from delivery and unknown slots return empty, so adding a section never breaks older deployments. ### Rows and columns Editors can place sections directly in a slot or group them into rows (`kind: "row"`, `row_…` ID) using six presets: `full`, `halves`, `thirds`, `quarters`, `oneTwo` (1:2) and `twoOne` (2:1). - `PageLayout` renders column proportions and stacks them in content order when its container narrows. - The default column gap is `1.5rem`, configurable via `--orbpage-row-gap`. - A slot holds up to 100 sections across all rows and columns; rows cannot be nested. - Reducing a row's column count appends removed columns' sections to the last remaining column without changing section IDs. ## Setting types Settings are delivered resolved for rendering rather than in their stored form: | Setting | Stored as | Delivered as | Optional / default | | ------------------------------------- | --------------------------------------------------- | --------------------------------------------------- | ---------------------------- | | `setting.line(label)` | String (max 300 chars) | `string` | `.optional()` | | `setting.text(label)` | [Document](/docs/page/write-content#write-running-text) | `{ html }` (safe HTML fragment) | `.optional()` | | `setting.picture(label)` | `{ media, decorative? }` | `{ url, width, height, alt, srcset?, focalPoint? }` | `.optional()` | | `setting.link(label)` | Target by identity | `{ href }` | `.optional()` | | `setting.products(label, { max })` | Picked `refs` or `{ kind: "category", ref, limit }` | Product cards | Empty list | | `setting.categories(label, { max })` | Category `refs` | Category cards | Empty list | | `setting.pages(label, { max })` | `pag_` IDs (never home) | Page cards (`id`, `title`, `href`, `publishedAt`) | Empty list | | `setting.form(label)` | `frm_` ID | Form definition and fields | `.optional()` | | `setting.choice(label, options)` | Option key | Option key | First key | | `setting.toggle(label)` | Boolean | Boolean | `false` or `.default(true)` | | `setting.number(label, { min, max })` | Integer | Integer | `min` or `.default(n)` | | `setting.colour(label)` | Palette key | Palette key | First key or `.default(key)` | Links store stable identities (`page`, `category`, `product`, `path` or `url`) using catalog `ref` rather than slugs, so renamed URLs keep resolving. On category pages, `line`, `text` and `picture` settings can follow the category's catalog data (`{ follow: "name" | "description" | "picture" }`). In rich text, image blocks support **Display width** (`full`, `50%`, `33%`, `25%` or a custom positive integer pixel width) without exceeding the container. ## Push declarations to OrbPage Run a dry-run check during deployment to see structural changes and any drafts or live versions that would no longer fit, then push the declaration: ```tsx continues import { declareSections } from "@orbpage/client"; const options = { baseUrl: process.env.ORBPAGE_URL, token: process.env.ORBPAGE_STAFF_TOKEN }; const checked = await declareSections(sections, { ...options, check: true }); if (!checked.ok) throw new Error(`OrbPage refused the check: ${checked.problem.code}`); for (const { kind, key, state } of checked.content.misfits) { console.log(`No longer fits: the ${state} ${kind} ${key}`); } const declared = await declareSections(sections, options); if (!declared.ok) throw new Error(`OrbPage refused the sections: ${declared.problem.code}`); ``` `declareSections()` requires a staff token with Content edit (see [Write content from code](/docs/page/write-content#sign-in-from-a-script)). `manageContent(options).declare(sections.declarations, idempotencyKey)` performs the same operation and also accepts an operator key. Content that no longer fits stays stored; delivery shows only what still fits. ## Templates Editors build category templates in the admin from your declared category slots. Every category follows the default template until an editor assigns another or edits a slot on that category. Resetting a slot returns it to its template. Your storefront reads the resolved slots directly and receives the `template` name alongside them. ## Customize | You want to | Do this | Default | | ---------------------------------------- | ----------------------------------------- | ----------------------------------- | | Add help text in the admin | Chain `.describe("…")` on any setting | No help text | | Change the gap between row columns | Set `--orbpage-row-gap` in CSS | `1.5rem` | | Preview declaration changes safely | Pass `check: true` to `declareSections()` | Applies immediately | | Manage declarations with an operator key | Use `manageContent(options).declare()` | Staff token via `declareSections()` | ## Built on OrbCatalog OrbPage resolves product cards, category cards, media library pictures and category follow values directly from [OrbCatalog](/docs/catalog). ## Next steps | You want to | Read | | ---------------------------------------- | ---------------------------------------------- | | Read published pages, menus and previews | [Read the content](/docs/page/content) | | Seed or migrate pages from scripts | [Write content from code](/docs/page/write-content) | | Understand OrbPage's architecture | [OrbPage overview](/docs/page) | | Configure OrbCatalog products and media | [Read the catalog](/docs/catalog/storefront) | # Write content from code Seed or import OrbPage pages and menus from a script. Sign in, write and publish a body, mint ids, use library pictures and pass the audit. A seed, an import or a migration writes OrbPage content through `manageContent` from `@orbpage/client`, on the same drafts and versions editors use in the admin. By the end of this page your script makes a page and a menu, publishes both, and a second run changes nothing. ## Write and publish a page ```ts import { manageContent } from "@orbpage/client"; const content = manageContent({ baseUrl: process.env.ORBPAGE_URL, // http://localhost:8807 in pnpm dev token: process.env.ORBPAGE_STAFF_TOKEN, }); const run = crypto.randomUUID(); const shipping = await content.ensurePage( { locale: "en", title: "Shipping", slug: "shipping" }, `${run}:shipping`, ); if (!shipping.ok) throw new Error(`OrbPage made no page: ${shipping.problem.code}`); const { id } = shipping.content; const opened = await content.page(id, "en"); if (!opened.ok) throw new Error(`OrbPage opened no draft: ${opened.problem.code}`); ``` The body names the slots and sections your shop [declared](/docs/page/sections) for pages: ```ts continues const text = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "We ship within two days." }] }], }; const applied = await content.applyPage( id, "en", { basedOn: opened.content.draft?.revision ?? null, content: { title: "Shipping", slug: "shipping", seo: { description: "How Clay & Crema ships coffee and stoneware." }, slots: { body: [{ id: "sec_shippingtext", type: "text", settings: { body: text } }] }, }, }, `${run}:shipping:en`, ); if (!applied.ok) throw new Error(`OrbPage refused the page: ${applied.problem.code}`); applied.content.status; // "applied", or "unchanged" when this body is already live ``` `ensurePage` finds the page that holds the address in the locale, drafted or live, or makes it. `applyPage` saves the body as the draft and publishes it in one call. - **`basedOn`** is the draft revision you read, `null` when the entry has no draft. A newer draft answers `draft_stale`, so an editor's work is never overwritten unread. - **The idempotency key** makes a retry safe. The client sends `:save` and `:publish` keys derived from it; reusing a key for another body answers `idempotency_key_reused`. - **A malformed body** throws a `ZodError` before anything is sent: an id, a link or the shape of a slot. OrbPage checks settings against your declaration and answers `body_invalid`, with a pointer such as `#/body/content/slots/body/0/settings/body`. The home page is never made: it is always `homePageId` (`pag_home00000000`) and has no `slug`. ## Sign in from a script | Where | Credential | `manageContent` takes | | -------------------------- | --------------------------------------- | --------------------- | | `pnpm dev` on your machine | The owner's staff token, from a sign-in | `token` | | A deployment script | The environment's operator key | `operatorKey` | | A person's tool | A staff token with Content edit | `token` | ### Sign in as the owner locally `pnpm dev` writes the owner's email and password into `catalog/.env`. Sign in at the admin, as a browser would, and ask for a staff token: ```ts continues const admin = "http://localhost:8789"; const signedIn = await fetch(`${admin}/api/auth/sign-in/email`, { method: "POST", headers: { "Content-Type": "application/json", Origin: admin }, body: JSON.stringify({ email: process.env.ORBCATALOG_OWNER_EMAIL, password: process.env.ORBCATALOG_OWNER_PASSWORD, }), }); const cookie = signedIn.headers .getSetCookie() .map((each) => each.split(";")[0]) .join("; "); const answer = await fetch(`${admin}/api/auth/token`, { headers: { Cookie: cookie } }); const { token } = (await answer.json()) as { token: string }; ``` The same token reads the catalog's media library. The local OrbPage has no operator key until you set `OPERATOR_KEY_HASH` in its Worker's environment. ### Use the operator key when deployed ```ts continues const deployed = manageContent({ baseUrl: process.env.ORBPAGE_URL, operatorKey: process.env.ORBPAGE_OPERATOR_KEY, }); ``` [Deployment](/docs/run/deployment#headless-setup-for-catalog-and-orbpage) shows how to issue the key. It configures the site, declares, and adds, saves and publishes pages, menus, forms, templates and category content. It cannot withdraw, roll back, archive, restore or delete, and it cannot publish over the audit's errors: those take a staff token. ## Write a menu ```ts continues const footer = await content.addMenu("footer", `${run}:menu:footer`); if (!footer.ok) throw new Error(`OrbPage opened no menu: ${footer.problem.code}`); const menu = await content.menu(footer.content.id, "en"); if (!menu.ok) throw new Error(`OrbPage opened no draft: ${menu.problem.code}`); const coffee = { id: "itm_coffee000001", label: "Coffee", link: { kind: "category", ref: "coffee" }, } as const; const written = await content.applyMenu( footer.content.id, "en", { basedOn: menu.content.draft?.revision ?? null, content: { items: [{ id: "itm_colshop00001", label: "Shop", children: [coffee] }] }, }, `${run}:menu:footer:en`, ); if (!written.ok) throw new Error(`OrbPage refused the menu: ${written.problem.code}`); ``` `addMenu` opens the entry of a menu your declaration names, new or existing, so a second run finds the same one. A menu's body as JSON: ```json { "items": [ { "id": "itm_colshop00001", "label": "Shop", "children": [ { "id": "itm_coffee000001", "label": "Coffee", "link": { "kind": "category", "ref": "coffee" } }, { "id": "itm_journal00001", "label": "Journal", "link": { "kind": "page", "id": "pag_uxfcp1ysqmn5" } } ] }, { "id": "itm_workshops001", "label": "Workshops", "link": { "kind": "path", "path": "/en/workshops" } }, { "id": "itm_contact00001", "label": "Contact", "link": { "kind": "url", "href": "mailto:hello@claycrema.test" } } ] } ``` An entry without a link heads its children, as a footer's column does. Children go one level deep. A level holds at most 30 entries and a label at most 60 characters. A menu links to a `page`, a `category`, a `path` or a `url`. ## A complete page body The home page of Clay & Crema, as `applyPage` sends it in English: ```json { "title": "Clay & Crema", "slots": { "body": [ { "id": "sec_hero00000001", "type": "hero", "settings": { "title": "Slow coffee,", "picture": { "media": "med_j9ag8qeq8697", "decorative": true }, "primary": { "kind": "category", "ref": "coffee" }, "primaryLabel": "Shop coffee" } }, { "kind": "row", "id": "row_tiles0000001", "layout": "halves", "columns": [ [ { "id": "sec_tilecoffee01", "type": "tile", "settings": { "title": "Coffee", "picture": { "media": "med_4k2v9x7p1q3m" }, "link": { "kind": "category", "ref": "coffee" }, "linkLabel": "Coffee" } } ], [ { "id": "sec_tileceramic1", "type": "tile", "settings": { "title": "Ceramics", "picture": { "media": "med_8w3n5r2t6y0z" }, "link": { "kind": "category", "ref": "ceramics" }, "linkLabel": "Ceramics" } } ] ] }, { "id": "sec_newpieces001", "type": "productRow", "settings": { "title": "New from the kiln", "products": { "kind": "category", "ref": "ceramics", "limit": 4 } } }, { "id": "sec_journal00001", "type": "journal", "settings": { "title": "From the journal", "stories": ["pag_uxfcp1ysqmn5"] } } ] } } ``` A section is `{ id, type, settings }`; `"kind": "section"` may stand beside them. A row is `{ kind: "row", id, layout, columns }`, as [Rows and columns](/docs/page/sections#rows-and-columns) shows. Each setting stores the value the "Stored as" column of [the settings table](/docs/page/sections#setting-types) names. A category or product is named by the catalog's `ref`, a page by its `pag_` id. ## Mint section, row and entry ids Your script makes the ids of sections (`sec_`), rows (`row_`) and menu entries (`itm_`): the prefix and exactly 12 characters of `0-9` and `a-z`. Each is used once in its page or menu. A readable id such as `sec_shippingtext` is fine. OrbPage makes page and menu ids itself. Keep an id for the life of its section: the editor and the preview point at it. Derive it from a name, and a second run sends the same body, which `applyPage` answers `unchanged`: ```ts continues async function idOf(prefix: "sec" | "row" | "itm", name: string): Promise { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(name)); const letters = [...new Uint8Array(digest).slice(0, 12)].map((byte) => (byte % 36).toString(36)); return `${prefix}_${letters.join("")}`; } const heroId = await idOf("sec", "home:hero"); ``` ## Write running text A `setting.text` stores a document: Tiptap's ProseMirror JSON, limited to a fixed set of nodes. ```json { "type": "doc", "content": [ { "type": "heading", "attrs": { "level": 1 }, "content": [{ "type": "text", "text": "Roast days" }] }, { "type": "paragraph", "content": [ { "type": "text", "text": "We roast on " }, { "type": "text", "text": "Tuesdays and Fridays", "marks": [{ "type": "bold" }] }, { "type": "hardBreak" }, { "type": "text", "text": "Read the journal", "marks": [ { "type": "link", "attrs": { "link": { "kind": "page", "id": "pag_uxfcp1ysqmn5" } } } ] } ] }, { "type": "bulletList", "content": [ { "type": "listItem", "content": [ { "type": "paragraph", "content": [{ "type": "text", "text": "Beans ship the next day." }] } ] } ] } ] } ``` | Part | Allowed | | ------ | -------------------------------------------------------------------------------- | | Blocks | `paragraph`, `heading` (level 1 to 3), `bulletList`, `orderedList`, `blockquote` | | Inline | `text`, never empty, and `hardBreak` | | Marks | `bold`, `italic`, `link` with `attrs.link` holding a link | Anything else is refused, and a document holds at least one node. A heading's level is relative: delivery maps level 1 to the page's base level. Pictures, tables and videos inside running text are blocks the admin's editor writes; write them there. ## Use pictures from the media library A picture setting holds a file of the catalog's media library by its id. Find it by name with the catalog's staff client: ```ts continues import { staffCatalog } from "@orbcatalog/client/staff"; const catalog = staffCatalog({ url: process.env.ORBCATALOG_URL, fetch: (request) => { request.headers.set("Authorization", `Bearer ${token}`); return fetch(request); }, }); const found = await catalog.library({ q: "hero.jpg" }); const file = found.ok ? found.value.files.find(({ name }) => name === "hero.jpg") : undefined; const hero = file === undefined ? undefined : { media: file.media, decorative: true }; ``` `library({ q })` lists every file whose name holds `q`; pass `next` as `after` for the next page. The setting stores `{ media }`, and `decorative: true` for this use only. Delivery reads the file's alt text in the page's language from the library. No client uploads a file into the library today: upload it in the admin, or import it with a product's pictures. ## Pass the publication audit `applyPage` publishes, so OrbPage's audit runs on every write. Errors block publishing: | Code | Fix | | ---------------------- | --------------------------------------------------------- | | `image_alt_missing` | Describe the file in the library, or `decorative: true` | | `link_text_empty` | Give the link words; a decorative linked picture has none | | `heading_empty` | Write the heading, or remove it | | `video_poster_missing` | Pick a poster for the video | Warnings never block: `link_text_vague`, `link_text_url`, `link_text_ambiguous`, `link_target_unavailable`, `heading_level_skipped`, `image_alt_file_name`, `image_alt_redundant`, `image_alt_caption` and `image_alt_long`. Editors see them in the admin. A blocked write answers `422` with `publish_blocked`; the draft stays saved. `applied.problem.audit` names each issue: ```json { "code": "publish_blocked", "detail": "The audit found errors; fix them, or the owner publishes with a reason.", "audit": { "issues": [ { "code": "image_alt_missing", "severity": "error", "message": "Describe this image, or mark it decorative.", "path": "slots.body.0.settings.picture", "section": "sec_hero00000001" } ], "blocking": true } } ``` Fix the body and apply it again. Only the owner publishes over errors, with `publishPage(id, locale, { revision, overrideReason }, key)`. Anyone else, the operator key included, gets `override_forbidden`. ## Customize | You want to | Do this | Default | | --------------------------- | ------------------------------------------------------------- | --------------------------- | | Keep what editors published | Skip an entry whose `published` is set | `applyPage` writes it again | | Describe a library picture | `catalog.editFile(media, { alt: { en } }, key)` | No alt text | | Write forms | `addForm`, then `applyForm` | None | | Write templates | `addTemplate`, `saveTemplate`, `publishTemplate` | The default template | | Write a category's content | `addCategory`, `saveCategory`, `publishCategory` | Follows its template | | Retire a page | `archivePage` or `deletePage` with a staff token | Stays live | | Take one language offline | `POST /api/pages/{page}/{locale}/withdraw` with a staff token | Stays live | Withdrawing has no `manageContent` method today; send the request with a staff token and an `Idempotency-Key`. Menus and forms withdraw at `/api/menus/{menu}/{locale}/withdraw` and `/api/forms/{form}/{locale}/withdraw`. [Read the content](/docs/page/content#delete-or-archive-pages) covers deleting and archiving. ## Next steps | You want to | Read | | ------------------------------------ | ----------------------------------------------------------------------- | | Declare what a body may hold | [Declare sections and slots](/docs/page/sections) | | Replace content after a re-declaring | [Re-declare and migrate](/docs/page/content#re-declare-and-migrate-sections) | | Read what your script published | [Read the content](/docs/page/content) | | Issue an operator key | [Deployment](/docs/run/deployment#headless-setup-for-catalog-and-orbpage) | # Connect the products Wire OrbPage, OrbCart and OrbSearch to OrbCatalog using environment variables, Service Bindings and feeds. Each OrbCommerce product works on its own. When you run several together, you connect them through configuration and bindings rather than glue code. ## Connect OrbPage to OrbCatalog OrbPage reads products, categories and listings through `@orbcatalog/client`. Set two variables in OrbPage's `wrangler.jsonc`: ```dotenv title="OrbPage wrangler.jsonc vars" CATALOG_URL=https://catalog.example.com CATALOG_CHANNEL=de ``` `CATALOG_CHANNEL` determines which storefront links product cards point to. Cards show the product's name, link and primary image, without prices or stock (since OrbPage caches pages and does not track live checkout prices). Discontinued or unreleased products are omitted and listed in `meta.unresolved`. ## Connect OrbCart to OrbCatalog OrbCart asks OrbCatalog for live offers, inventory and pickup locations. Choose **Service Bindings** if both Workers run in the same Cloudflare account, or **HTTP** if they run in separate accounts. Export the entrypoint from your Catalog Worker alongside its default export: ```ts skip="Catalog Worker entrypoint" export const OrbCart = orbCartEntrypoint(shop); ``` Bind it in OrbCart's `wrangler.jsonc`: ```jsonc title="OrbCart wrangler.jsonc" "services": [{ "binding": "CATALOG", "service": "orbcatalog", "entrypoint": "OrbCart" }] ``` Attach the contracts to the binding in your OrbCart Worker: ```ts title="src/worker.ts" import { defineCommerce, service } from "@orbcart/runtime"; export default defineCommerce({ channels, offers: service("CATALOG"), pickupLocations: service("CATALOG"), inventory: { check: service("CATALOG"), reserve: service("CATALOG"), release: service("CATALOG"), commit: service("CATALOG"), restock: service("CATALOG"), }, }); ``` Because only Workers in your account can call the binding, no public gateway or request signature is needed. Point OrbCart's contracts at your Catalog's `/orbcart/*` routes. OrbCart signs every request automatically with the Environment's ES256 key: ```ts title="src/worker.ts" import { defineCommerce, http } from "@orbcart/runtime"; export default defineCommerce({ channels, offers: http("https://catalog.example.com/orbcart/offers"), inventory: { check: http("https://catalog.example.com/orbcart/inventory/check"), reserve: http("https://catalog.example.com/orbcart/inventory/reserve"), release: http("https://catalog.example.com/orbcart/inventory/release"), commit: http("https://catalog.example.com/orbcart/inventory/commit"), restock: http("https://catalog.example.com/orbcart/inventory/restock"), }, }); ``` ### Push price invalidations from Catalog to OrbCart Configure OrbCatalog with OrbCart's URL and secret key so price or availability changes invalidate open Carts immediately instead of waiting for `expiresAt`: ```sh # Set ORBCART_URL="https://commerce.example.com" in Catalog's wrangler.jsonc vars pnpm exec wrangler secret put ORBCART_SECRET_KEY ``` ### How offers and inventory stay accurate - **Offers read the primary database.** `POST /orbcart/offers` never reads the CDN. It returns localized titles, variant attributes, minor-unit prices, tax category, shipping weight, image (up to 400 px), limits, delivery time and `expiresAt` (at most 15 minutes or the next scheduled price step). - **Inventory holds are atomic and idempotent.** `check` returns available counts (uncounted SKUs are treated as unlimited). `reserve`, `release` and `commit` lock counts in SKU order and key holds by the `hold.id` OrbCart sends, so retries never double-reserve, a payment's extension moves `expiresAt`, and abandoned holds expire automatically at `expiresAt`. ## Connect OrbSearch to OrbCatalog OrbSearch pulls the full catalog through an NDJSON feed and receives live offer pushes in seconds. ### 1. Point OrbSearch at the catalog feed Configure OrbSearch to poll `/feeds/orbsearch.ndjson` (supported intervals: `10`, `30`, `60`, `180`, `360`, `720` or `1440` minutes): ```sh curl -X PUT https://search.example.com/api/v1/catalog-source \ -H "Authorization: Bearer $ORBSEARCH_KEY" \ -H "Content-Type: application/json" \ -d '{"url":"https://catalog.example.com/feeds/orbsearch.ndjson","interval_minutes":10}' ``` ### 2. Enable instant offer pushes Give OrbCatalog your OrbSearch control plane URL and management key so price and sale changes push to `PUT /api/v1/offers` in batches of 1,000: ```sh # Set ORBSEARCH_URL="https://search.example.com" in Catalog's wrangler.jsonc vars pnpm exec wrangler secret put ORBSEARCH_KEY ``` If both Workers run in the same Cloudflare account, add an optional Service Binding on the Catalog Worker (keep `ORBSEARCH_URL` and `ORBSEARCH_KEY` set): ```jsonc title="Catalog wrangler.jsonc" "services": [{ "binding": "ORBSEARCH", "service": "orbsearch-gateway" }] ``` ### What the feed and pushes carry | Aspect | Behavior | | -------------------- | ----------------------------------------------------------------------------------------- | | Feed structure | Categories (parents first), then published products with variants, URLs and offers. | | Media | Primary card image per variant (colour-matched, never falling back to another colour). | | Purchase constraints | Per-SKU minimum/maximum quantities, increments, configuration and appointment flags. | | Prices & sales | Major-unit base/sale prices, unit prices, deposits and `sale_window` transitions. | | Caching & freshness | Feed uses `ETag` (`304` when unchanged) with `private, no-store`; drafts never affect it. | Content changes (titles, images, publications) propagate on the feed poll interval ([Scheduled feeds](/docs/search/feeds)), while price and sale updates push in seconds ([Live prices and stock](/docs/search/prices-and-stock)). Exact stock counts are never sent to Search: Cart and checkout remain authoritative. ## Next steps | You want to | Read | | ------------------------------- | --------------------------------------------- | | Deploy the test environment | [The test environment](/docs/run/test-environment) | | Deploy OrbCart step by step | [Deployment](/docs/run/deployment) | | Learn how remote contracts work | [Remote contracts](/docs/cart/remote-contracts) | # Rotate credentials Replace integration keys, signing keys and webhook secrets safely across OrbCatalog, OrbPage and OrbCart. Rotate one product and environment at a time. Keep an inventory of each credential's purpose, consumers, public key ID or digest, and owner. Store recoverable secrets only in your secret store or owner-only files, never in tickets, shell arguments, URLs or logs. Overlap windows deliberately keep old credentials usable while consumers update, and public verification keys stay cached for several minutes. Replacing an API key does not cancel already-authenticated requests or revoke Cart, Order or preview tokens. ## What can be rotated today | Credential | Seam | Cutover and overlap | | -------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------ | | Catalog Source key | _Connections → New key_ or `newSourceKey` | Same Source, new hash; old key stops at commit (no overlap). | | Catalog change-feed key | `addReader` / `removeReader` | Same reader ID replaces without overlap; a second reader ID overlaps. | | Catalog event signing key | `rotateSigningKey` | New key prepublished 31 minutes; old public key kept 6 minutes after. | | Catalog webhook secret | `rollWebhookSecret` / `webhookSecret` | New secret starts at once; old secret signs beside it for 24 hours. | | Page event signing key | `EVENT_SIGNING_KEY` and `EVENT_VERIFICATION_KEYS` | Publish next and retiring public keys independently of the signer. | | Catalog/Page operator key | `orbcatalog operator-key`, replace `OPERATOR_KEY_HASH` | No overlap; older deployments accept the old hash until rollout ends. | | Cart API keys | `orbcart keys issue` / `revoke` / `status --env test` | Overlap via a second key file; terminal digest revocation (`test` only). | | Cart signing key | `orbcart signing prepare` / `activate` / `status --env test` | 1-day prepublication after replica confirmation; explicit activation. | | Staff / delegated token | Merchant staff sign-in | Short-lived tokens; existing tokens expire naturally. | | Buyer identity key | Your identity provider's JWKS or inline public keys | Provider-owned lifecycle; inline keys require a deploy. | | Payment / external secrets | Provider console and Worker secrets | Issue with provider, update every consumer, then revoke. | Keep the Hyperdrive query cache disabled for OrbCatalog so Source and reader key lookups always read fresh rows from Postgres. ## OrbCatalog Source and reader keys The management methods below (`newSourceKey`, `addReader`, `removeReader`, `rotateSigningKey`, `rollWebhookSecret` and `webhookSecret`) live on `staffCatalog(transport)` exported from `@orbcatalog/client/staff`. ### Rotate a Source key ### Pause sync and issue a new key Pause the Source's sync and finish any in-flight writes. Call `newSourceKey` for the existing Source ID with a stable idempotency key, or click **New key** under _Connections_. Do not create a second Source or remove the existing one, as removing a Source relinquishes its field ownership. ### Install the key and verify Store the returned secret immediately: it is shown only once, and retrying with the same idempotency key does not return it again. If you lose the response, rotate again with a new idempotency key. Update your integrator, resume sync, and verify that the new key succeeds while the old key fails. ### Rotate a change-feed reader key Save the consumer's last processed cursor before changing keys. - **Without overlap:** call `addReader` with the existing reader ID to replace its key immediately. - **With overlap:** call `addReader` with a new reader ID, deploy that key to your consumer while keeping its cursor and deduplication state, verify progress, then call `removeReader` on the old ID. Removing the old reader disables its key without undoing processed events. ## OrbCatalog signing keys and webhook secrets ### Event signing keys Call `rotateSigningKey` with a stable idempotency key and record the returned key IDs and `signsFrom` timestamp. A pending rotation responds with `key_waiting` instead of creating a second waiting key. Wait until `signsFrom` (31 minutes after preparation), verify a delivery under the new key, and allow the previous key's 6-minute verification window to finish. ### Webhook secrets Call `rollWebhookSecret` once and install the returned secret at your receiver. Keep accepting the previous secret until its returned `previousUntil` timestamp (24 hours). If the response is lost, retry with the same idempotency key or read the active secret with `webhookSecret`. Do not start a second roll as a retry, as that drops the older previous secret early. ## OrbPage event signing keys OrbPage has no public integration API key: staff tokens authorise management calls, and an operator key authorises setup only. Its signing key signs outgoing form notifications and `content.published` events. - `EVENT_SIGNING_KEY` holds the active ES256 private key (base64 PKCS #8). - `EVENT_VERIFICATION_KEYS` holds a JSON JWKS of public ES256 keys only (`kty`, `crv`, `x`, `y`, `kid`, `alg: "ES256"`, `use: "sig"`), using each key's JWK thumbprint as `kid`. Never include private `d` members. OrbPage publishes the active public key plus `EVENT_VERIFICATION_KEYS` at `/.well-known/jwks.json` with `Cache-Control: no-store`. ### Prepublish the next public key Deploy `EVENT_VERIFICATION_KEYS` with both the current and next public keys while leaving `EVENT_SIGNING_KEY` unchanged. Confirm both `kid` values appear at `/.well-known/jwks.json`. ### Wait for verifier caches Wait at least 5 minutes after rollout finishes (longer if a receiver caches JWKS for longer). ### Switch the active signer Update `EVENT_SIGNING_KEY` to the new private key, keeping both public keys in `EVENT_VERIFICATION_KEYS`. Complete the rollout and confirm fresh deliveries carry the new `kid`. ### Retire the old public key Wait at least 6 minutes after the last old deployment stops signing (and keep the overlap until rollback is no longer needed). Remove the old public key from `EVENT_VERIFICATION_KEYS`, redeploy, and verify that new deliveries succeed while a synthetic request signed by the old key fails. On retry, OrbPage preserves the event ID and JSON body and signs anew with the current key. Deduplicate by source and event ID, never by signature or `kid`. ## OrbCart API keys The `orbcart keys` commands and private `CommerceKeys` entrypoint run only against `test` today. Run them from your commerce Worker directory (`--config` and `--worker` select non-default targets). There is no public HTTP endpoint for key management, so a stolen secret key cannot mint or revoke keys. ### Issue replacement keys into a new file Keep the old key file until cutover is complete: ```sh orbcart keys issue --env test --channel de --keys .orbcart/keys/test-de-next.env ``` The CLI writes random keys to an owner-only file, syncs it to disk, and registers only their SHA-256 digests. Retrying with the same path and channel reuses the saved secrets and digests. A sibling `.lock` file prevents concurrent writes; never delete the key file to clear a stale lock. ### Wait for confirmed receipts The command prints secret-free receipts with `digest`, `state` (`registered` or `revoked`), `version` and `status` (`pending`, `confirmed` or `conflict`). It exits non-zero until every replica confirms both registrations. Do not install keys that are still `pending`. ### Switch consumers and revoke old digests Drain and reconcile ambiguous writes before cutover, because Cart idempotency keys are scoped to the credential digest. Install the new keys, verify requests succeed, then revoke each old digest from its original receipt: ```sh orbcart keys revoke --env test --digest orbcart keys status --env test --digest ``` Retry until the receipt reports `state: revoked` and `status: confirmed`, then confirm the old key fails. Revocation is terminal, even if it arrives before a delayed registration. Replicas catch up on every cold start before serving; warm replicas receive asynchronous pushes. During a network partition, a warm isolated replica may still accept an old key until confirmation completes. ## OrbCart signing keys ```sh orbcart signing prepare --env test orbcart signing status --env test --generation orbcart signing activate --env test --generation ``` `prepare` publishes one next generation to JWKS while keeping the current signer active. Only one unfinished generation is allowed at a time. | State | Meaning | | ------------ | --------------------------------------------------------------------------------------- | | `publishing` | Committed, waiting for all replicas to confirm publication (`publishedAt` is `null`). | | `waiting` | All replicas confirmed at `publishedAt`; `activatesFrom` is exactly 24 hours later. | | `ready` | The 24-hour window elapsed; the old key still signs until you run `activate`. | | `activating` | Activation committed; some replicas already sign with the new key while others confirm. | | `active` | Activation confirmed everywhere. Retrying reports completion without changing signers. | Old public keys remain in JWKS so historical Quotes stay verifiable. This is an availability-safe rotation, not emergency revocation of a compromised signing key. ## Cache freshness and retry behaviour | Verifier | Cache lifetime | Unknown-key refresh | Notes | | ------------------------------ | -------------- | ------------------------------ | ----------------------------------------------------------------- | | Family HTTP-signature verifier | 5 minutes | At most once per minute | Failed fetch does not extend cache; returns `keys_unavailable`. | | JWT verifier (JOSE) | 10 minutes | 30-second cooldown, 5s timeout | Staff tokens last 15 min (60s tolerance); delegated tokens 5 min. | When an HTTP-signature verifier returns `keys_unavailable` during a JWKS outage, respond with a retryable status such as HTTP `503` without acknowledging the event. Invalid signatures are always rejected. ## Never rotate a sealing root routinely OrbCatalog's `SIGNING_KEY` seals later signing keys and webhook secrets. OrbCart's `ROOT_SECRET` derives signing-key encryption, buyer-index names, gift-card functions and hand-off signatures. Replacing either without a dedicated migration plan makes stored state unreadable. ## Verify an installation Local tests do not replace deployed verification. With explicit authorisation for the target environment, record the product and environment, public key IDs or digests, rollout and overlap timestamps, old-key rejection, new-key acceptance, warm-cache verification, outage retry and restart recovery. Keep raw secrets, provider responses and personal data out of the verification record. ## Next steps | You want to | Read | | ------------------------------------ | ------------------------------------------------- | | Review OrbCart's security model | [Security](/docs/cart/security) | | Deploy services to Cloudflare | [Deployment](/docs/run/deployment) | | Connect products across environments | [Connect the products](/docs/run/connect-the-products) | | Verify signed OrbCatalog webhooks | [Follow the catalog's changes](/docs/catalog/changes) | # Deployment Deploy OrbCart to your Cloudflare account step by step, automate headless Catalog and OrbPage setup, and verify your go-live checklist. OrbCart runs in **your own** Cloudflare account with no OrbCart-hosted server in between. Keep `test` and `live` as separate Workers with separate keys and data. ## Architecture overview | Component | Purpose | | -------------------- | ----------------------------------------------------------- | | Worker (one per env) | Serves the `/v1` API and calls your contracts. | | Durable Objects | Hold Carts, Payments and Orders. Single source of truth. | | Postgres (optional) | Read-only Order and event lists for the Admin API and UI. | | Cron trigger | Runs daily EU VAT imports and cleans up old event rows. | | Storefront | Hosted anywhere you like. Only the Worker needs Cloudflare. | ## Deploy OrbCart to a test environment Until `orbcart deploy` ships, set up a test environment with Wrangler from your commerce Worker's directory (`apps/nordgrat-cart-worker` is the reference): ### Set up Postgres and Hyperdrive (optional) Order lists, attention queues and checkout metrics live in a `cart` schema inside your EU Postgres database (shared across OrbCommerce products). Run the migration with the database owner URL and the `orbcart` role URL: ```sh ORBCOMMERCE_OWNER_DATABASE_URL="$OWNER_URL" ORBCART_DATABASE_URL="$ORBCART_URL" \ pnpm dlx tsx node_modules/@orbcart/runtime/scripts/migrate.ts ``` Connect the Worker through Hyperdrive with caching **disabled** so lists never return stale data, then add the returned ID to your `HYPERDRIVE` binding in `wrangler.jsonc`: ```sh pnpm exec wrangler hyperdrive create shop-commerce-test-lists --connection-string="$ORBCART_URL" --caching-disabled ``` Also enable the cron trigger in `wrangler.jsonc` (handles both 30-day event cleanup and daily EU VAT sync): ```jsonc title="wrangler.jsonc" "triggers": { "crons": ["*/15 * * * *"] } ``` Preview environments can skip Postgres; list endpoints then answer `projection_unavailable`. ### Deploy the Worker ```sh pnpm exec wrangler deploy --name shop-commerce-test ``` ### Set `ROOT_SECRET` Generate a 32-byte secret and pipe it straight into Wrangler so it never hits your shell history: ```sh openssl rand -base64 32 | tr '+/' '-_' | tr -d '=\n' | pnpm exec wrangler secret put ROOT_SECRET --name shop-commerce-test ``` ### Add payment provider secrets Set credentials only for the providers your Channels use (see [Payments](/docs/cart/payments)): ```sh pnpm exec wrangler secret put STRIPE_SECRET_KEY --name shop-commerce-test pnpm exec wrangler secret put STRIPE_PUBLISHABLE_KEY --name shop-commerce-test pnpm exec wrangler secret put STRIPE_WEBHOOK_SECRET --name shop-commerce-test ``` If a required secret is missing, check `pnpm exec wrangler tail --name shop-commerce-test` to see which binding is absent. ### Register provider webhooks | Provider | Webhook URL | | -------- | ------------------------------------------------------------------ | | Stripe | `https://shop-commerce-test..workers.dev/webhooks/stripe` | | Adyen | `https://shop-commerce-test..workers.dev/webhooks/adyen` | | PayPal | `https://shop-commerce-test..workers.dev/webhooks/paypal` | ### Issue storefront keys ```sh pnpm exec orbcart keys issue --env test --channel de --url https://shop-commerce-test..workers.dev ``` This writes `ORBCART_URL`, a publishable key and a secret key to `.orbcart/keys/test-de.env`. ### Prime EU VAT rates If any Channel uses `tax: "eu-standard"`: ```sh pnpm exec orbcart tax sync --env test ``` ### Connect the OrbCommerce Admin Set `STAFF_ISSUER` to your OrbCommerce Admin URL and invite staff members with their required areas ([Staff access](/docs/cart/security#staff-access-in-the-admin)). ## Connect the storefront - Add your storefront's origin to the Channel's `origins`, set `returnUrl`, and redeploy the Worker. - Pass `ORBCART_URL` and `ORBCART_PUBLISHABLE_KEY` to your frontend; keep `ORBCART_SECRET_KEY` on your server only. - For Apple Pay, register your storefront domain with your payment provider ([Express checkout](/docs/cart/express-checkout#setup-checklist)). ## Protect cart creation and checkout - **Cloudflare WAF:** Add a [rate limiting rule](https://developers.cloudflare.com/waf/rate-limiting-rules/) on `POST /v1/carts` (and any storefront proxy route that creates Carts). Place a Managed Challenge on your browser checkout page, never on the `/v1` API or provider webhooks. - **Discount code rate limit:** Configure `CODE_ENTRIES_PER_ADDRESS` as a Workers rate limit binding (30 attempts per 60 seconds, distinct namespace ID per Environment). [OrbCart's exact budgets](/docs/cart/security#rate-limits) apply behind it. ## Headless setup for Catalog and OrbPage You can provision a fresh OrbCatalog and OrbPage from a deployment script without opening the admin, using a deployment-scoped **operator key**. Configure Catalog's [private media store](/docs/catalog/media-storage) (native R2 `MEDIA` binding or a private S3-compatible bucket) before importing any media. Route public media URLs through Catalog, never directly to the bucket. ### 1. Issue an operator key offline Generate one key per product and environment: ```sh pnpm exec orbcatalog operator-key --out "$HOME/.config/shop/catalog-test.key" pnpm exec orbcatalog operator-key --out "$HOME/.config/shop/page-test.key" ``` Each command writes a 32-byte `op_…` key to a mode-`0600` file and prints **only its SHA-256 hash**. Store the hash as `OPERATOR_KEY_HASH` via `wrangler secret put` on the target Worker, and keep the raw key in your CI/deployment secret store. Rotating or deleting `OPERATOR_KEY_HASH` revokes the key immediately. ### 2. Apply settings, Schema and declarations Use `@orbcatalog/client/staff` and `@orbpage/client` with the operator key: ```ts worker import { staffCatalog } from "@orbcatalog/client/staff"; import type { SchemaDocument, SettingsDocument } from "@orbcatalog/client/staff"; import { manageContent } from "@orbpage/client"; import type { Declarations, Settings } from "@orbpage/client"; export async function applySetup(input: { catalogUrl: string; catalogKey: string; pageUrl: string; pageKey: string; settings: SettingsDocument; schema: SchemaDocument; site: Settings; declarations: Declarations; }) { const { catalogUrl, catalogKey, pageUrl, pageKey, settings, schema, site } = input; const run = crypto.randomUUID(); const catalog = staffCatalog({ url: catalogUrl, operatorKey: catalogKey, fetch: (request) => fetch(request), }); const page = manageContent({ baseUrl: pageUrl, operatorKey: pageKey }); const settingsResult = await catalog.applySettings(settings, { idempotencyKey: `${run}:settings`, }); if (!settingsResult.ok) throw new Error(settingsResult.problem.code); const schemaResult = await catalog.applySchema(schema, { idempotencyKey: `${run}:schema`, }); if (!schemaResult.ok) throw new Error(schemaResult.problem.code); const configured = await page.configure(site); if (!configured.ok) throw new Error(configured.problem.code); const declared = await page.declare(input.declarations, `${run}:declarations`); if (!declared.ok) throw new Error(declared.problem.code); } ``` ### 3. Follow the provisioning order 1. Apply Catalog settings, Schema, Locations (`applyLocation`) and Resources (`applyResource`). 2. Provision your sync Source once via `addSource` and store its returned Source key outside Git (use `@orbcatalog/client/source` for product, media, offer and stock sync; the operator key is not a Source key). 3. Configure OrbPage and declare sections (`page.declare`). 4. Resolve all page IDs with `ensurePage` before writing cross-page links, then import media and publish pages (`applyPage`), menus (`applyMenu`) and forms (`applyForm`). See [Write content from code](/docs/page/write-content). Every `apply*` call compares against the current revision and returns `unchanged` when nothing differs, without creating empty drafts. Operator keys are strictly scoped to setup and content publishing: they cannot read form inboxes, erase customer data, manage staff, approve MCP proposals or trigger payments and refunds. ## Cache invalidation across deploys Catalog and OrbPage retain their Workers Cache across compatible deploys. If a release changes the cached response shape, increment `deliveryShape` in the affected product before deploying (and run Catalog migrations first). The dispatcher purges old delivery tags automatically, and Catalog's Search feed updates its `ETag`. If old and new Worker versions cannot share cached responses during a rollout or rollback, disable `cross_version_cache` for that deploy and re-enable it once old entries expire. ## Updating OrbCart Run migrations, then deploy the updated Worker: ```sh ORBCOMMERCE_OWNER_DATABASE_URL="$OWNER_URL" ORBCART_DATABASE_URL="$ORBCART_URL" \ pnpm dlx tsx node_modules/@orbcart/runtime/scripts/migrate.ts pnpm exec wrangler deploy --name shop-commerce-test ``` Worker secrets persist across deploys, and open Carts keep working. Do not rename or remove a Channel that still has active Carts. ## Checklist before real money - [ ] [Cart creation rate rules and checkout challenges](#protect-cart-creation-and-checkout) are tested. - [ ] Every item on the [Security go-live checklist](/docs/cart/security#go-live-checklist) is complete. - [ ] `orbcart tax status` shows today's date in `availableOn` (when using EU VAT). - [ ] `deliverOrder` deduplicates by `order.id`. - [ ] Every Channel defines `withdrawal_policy` and `privacy_policy` in [`legal`](/docs/cart/configuration#legal) (required for `live` Workers). - [ ] Confirmation emails and the [order page](/docs/cart/order-page) are in place. `orbcart keys issue` supports `test` environments only today. Guided `live` provisioning ships with `orbcart deploy`. Check [Project status](/docs/cart/status) before taking live orders. ## Next steps | You want to | Read | | ----------------------------- | ------------------------------------------------- | | Review security before launch | [Security](/docs/cart/security) | | Rotate credentials safely | [Credential rotation](/docs/run/credential-rotation) | | Connect multiple products | [Connect the products](/docs/run/connect-the-products) | # The test environment Every product, the admin and Clay & Crema, the demo shop, on Cloudflare, seeded, with one command. ```sh pnpm ship test # every product, the admin and Clay & Crema, seeded, then a read of each pnpm ship test --plan # what a run would deploy, make, seed and refuse; changes nothing pnpm ship test --reset # empties every product's data first, once you type the environment's name ``` | What | Where | | --------------------------- | --------------------------------------------------- | | Clay & Crema, the demo shop | https://demo.orbcommerce.dev | | The admin | https://admin.orbcommerce.dev | | The catalog | https://catalog.orbcart.dev | | OrbPage | https://page.orbcart.dev | | OrbCart | `nordgrat-commerce-test` on its workers.dev address | **What it needs:** Wrangler signed in to the Cloudflare account (`pnpm exec wrangler login`), `cloudflared` on the path (`brew install cloudflared`), and `.env.test` at the root, copied from `.env.test.example`, which names every key: the Postgres connection strings, the owner the seed signs up, OrbSearch's key and the payment providers' sandbox keys. The file is ignored and never printed. ## What it does First it checks what would stop the seed later, before it changes anything: a catalog that holds Nordgrat's season, the catalog's scale fixture, and shopper keys in the database that a new shop Worker's sign-in secret cannot open. Both need `--reset`; the plan says so. Then, in the order the bindings and keys need: the catalog's database (migrations, Hyperdrive, the media bucket); OrbCart (the ERP's stand-in, its lists' migrations, its Worker, and a publishable and a secret key per Channel); the catalog's Worker, holding OrbCart's secret key and OrbSearch's; OrbPage (its buckets and Worker); the admin, which binds all three; and Clay & Crema, holding OrbCart's address and the `de` Channel's publishable key. Then Clay & Crema's seed, the one `pnpm dev` runs locally. The catalog's seed (`pnpm seed` in `catalog/`) signs the owner up through the admin, publishes the settings and the Schema, saves the stores and workshop benches, and pushes the studio's range as a Source to the catalog's Worker. The catalog's Worker fetches the 39 photographs from the seed's server on this machine. So the ship opens a Cloudflare quick tunnel to that port, 8790, while the seed runs, and closes it afterwards, also when the seed fails: `cloudflared tunnel --url http://localhost:8790`. Last, OrbPage's site is set up from the catalog's Channel, the shop's sections are declared and its first content written as the owner (`pnpm --filter @orbcommerce/clay-crema content`), and every product and the shop are read. Every seed step writes only what is missing, so a run that stopped halfway is finished by the next, and a second run changes nothing the owner changed since. Secrets it can make (signing keys, sign-in and root secrets) it makes once; keys between products live only as Worker secrets and in OrbCart's ignored key files. ## A second run changes nothing that did not change A Worker is deployed with a tag, the first 16 hex digits of a SHA-256 over its built bundle, its config and the values of the secrets handed to it, such as OrbCart's keys; a run builds it again, compares that digest with the tag of the version serving all traffic and deploys only when they differ or a secret it requires is missing. So a handed-in secret whose value changed is written again, while a secret the ship made (a signing key, a sign-in or root secret) is made once and never rewritten. `--reset` empties the catalog's database, which drops everything the worker role owns, the staff's and shoppers' sign-in with it; OrbPage's site; and OrbCart: its Worker gets a fresh root secret, then with that secret wipes every Durable Object Cloudflare lists for it and empties its lists, its key files go, and the catalog and the shop are deployed with the fresh keys it issues. ## By hand, once per environment The command names at its end what it cannot do: the Postgres database and its roles; a shop on the OrbSearch box for the catalog's feed, with the admin as its staff issuer and its key in `.env.test`, whose Query API Clay & Crema's search asks (`SEARCH_URL`); and the Stripe and PayPal webhooks, whose secrets go into `.env.test`, with the shop's host as a Stripe payment method domain. Each product's own ship (`pnpm ship test` in `catalog/`, which plays Nordgrat's season instead, `pnpm --filter @orbpage/runtime ship test`, `pnpm --filter @orbcart/example-nordgrat ship test --url …`) brings that product up alone. OrbCart's own deployment, step by step, is in [Deployment](/docs/run/deployment). # Accessibility Built-in WCAG 2.2 AA keyboard, focus, screen-reader and progressive-enhancement behaviour in @orbsearch/react, plus what your shell owns. `@orbsearch/react` targets **WCAG 2.2 AA**. Every search, filter, sort and pagination control is a native link or `GET` form underneath, so pages work before JavaScript hydrates and every view has a shareable URL. ## Live-region announcements `StorefrontProvider` renders a polite and an assertive live region automatically (debounced by `500 ms`, deduplicated, silent during initial page load). Announce custom errors or status updates with `useAnnouncement`: ```tsx title="app/unavailable.tsx" import { useAnnouncement } from "@orbsearch/react"; export function Unavailable() { useAnnouncement("Search is currently unavailable", true); return

Search is currently unavailable

; } ``` ## Built-in semantics by area | Area | Keyboard, ARIA and screen-reader behaviour | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Search box | Labelled combobox in ``; opens only when suggestions arrive; focus stays in input while arrows navigate; `Escape` restores typed text. | | Listing | Single `

` title; tiles are `
` with one link on the heading and `alt=""` on duplicate photos; banners are not `
`; "Load more" moves focus to the first new tile. | | Facets | Disclosure buttons (`aria-expanded`) keep closed options in DOM for Ctrl+F; native checkboxes/radios with counts in labels; range inputs validate min ≤ max urgently; chips move focus cleanly on removal. | | Filter sheet | Modal dialog; `Escape` or close discards pending choices and returns focus to the trigger button. | | Product page | Variant axes are `
` groups of native radios; unavailable combinations announce clearly; chosen values use double ring + heavier weight (never colour alone); price/stock updates announce politely. | ## Motion, focus and touch targets - **Focus rings** live on component classes directly so CSS resets cannot strip them; interactive targets meet `--orb-spacing-target` (`2.75rem`). - **Reduced motion:** transforms and scaling run only under `prefers-reduced-motion: no-preference`. - **No flicker on fast answers:** result images dim only after `--orb-motion-wait` (`150 ms`). - **Touch and forced colours:** hover states stay off on touch devices, inputs stay ≥ 16 px to avoid iOS zoom, and forced-colours mode delegates controls to system styling. ## What your storefront shell owns Set ``, `` and a skip link to `<main id="content" tabIndex={-1}>` in your root layout: ```tsx title="app/root.tsx (excerpt)" elements <> <a href="#content">Skip to content</a> <main id="content" tabIndex={-1}> Content </main> </> ``` In a custom listing layout without `<ListingPage>`, put `tabIndex={-1}` on the heading passed to `AppliedFilters`'s `resultsHeading` so focus lands cleanly after the last filter chip is removed. ## Customize | You want to | Do this | Default | | ----------------------------------- | --------------------------------------------------------------------------------------- | ------------------------- | | Translate screen-reader labels | Pass `messages` to `<StorefrontProvider>` | German (`de`) and English | | Adjust minimum touch target height | Set `--orb-spacing-target` ([Theming](/docs/search/theming)) | `2.75rem` | | Keep semantics when changing markup | Use the `render` prop ([React components](/docs/search/react#change-an-element-with-render)) | Default HTML elements | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------------- | | Verify colour contrast token pairs | [Theming](/docs/search/theming#contrast-pairs-wcag-22-aa) | | Build accessible custom facet renders | [Extend OrbSearch](/docs/search/extend) | | Explore React components and hooks | [React components](/docs/search/react) | # AI agents Connect shopper, merchant and coding agents to OrbSearch via WebMCP browser tools, HTTP APIs, Markdown twins and OpenAPI. Every surface of OrbSearch serves structured, self-explaining data for AI agents alongside people. ## Agent connection points | Agent role | Connects via | Capabilities | | ---------------- | -------------------- | ----------------------------------------------------------------------------- | | Shopper's agent | Browser WebMCP tools | Calls `search`, `get_facets` and `set_filters` registered by your storefront. | | Server / bot | Public Query API | Runs searches, product lookups and URL resolution with `debug=1` traces. | | Merchant's agent | Management API | Manages catalogs, drafts, synonyms, rules, previews, releases and insights. | | Coding agent | Docs + OpenAPI | Reads `/search/llms.txt`, any page at `<path>.md` and `/openapi/search.json`. | ## Register WebMCP tools in your storefront Call `registerAgentTools` from `@orbsearch/client` inside your storefront layout so browser-based agents can search, inspect available filters and drive your router directly: ```tsx title="app/root.tsx" import type { Search } from "@orbsearch/client"; import { registerAgentTools } from "@orbsearch/client"; import { useEffect } from "react"; import { useNavigate } from "react-router"; export function useSearchAgentTools(search: Search) { const navigate = useNavigate(); useEffect(() => { const registration = new AbortController(); registerAgentTools(search, { locale: "de", signal: registration.signal, navigate: (href) => void navigate(href, { preventScrollReset: true }), }).catch(reportError); return () => registration.abort(); }, [navigate, search]); } ``` When a browser does not expose WebMCP (`document.modelContext` or `navigator.modelContext`), `registerAgentTools` exits quietly without errors. ### Exposed browser tools | Tool | Parameters | Behaviour | | ------------- | ------------------------------------------------------ | ------------------------------------------------------------------------- | | `search` | `{ query, filters?, sort?, page?, facets? }` | Queries OrbSearch without navigating; returns JSON search results. | | `get_facets` | `{ facets?: string[] }` | Reads current page URL, total, active filters, sorts, facets and banners. | | `set_filters` | `{ filters?: Record<string, unknown>, sort?: string }` | Navigates via your router (`filters: {}` clears active filters). | Invalid filter fields or values fail with a descriptive sentence naming the page's valid options so the agent can self-correct. ### Agent view attribution Every hit and banner returned to a tool call is reported via `search.report` with `surface: "agent"` (unless `report: false` is set on the client), allowing [Insights](/docs/search/insights) to separate agent views from human shopper views. <Callout title="WebMCP is a draft" type="warn"> WebMCP is an evolving W3C Web Machine Learning draft API available only behind browser experiments. `registerAgentTools` targets its `registerTool` surface and degrades to a no-op elsewhere. </Callout> ## Customize | You want to | Do this | Default | | ------------------------------------- | -------------------------------------------------------- | ------------------------------- | | Disable agent view reporting | Pass `report: false` to `createSearch()` | Reports with `surface: "agent"` | | Let agents manage search rules safely | Issue a named API key and use draft + `review` endpoints | Manual admin/panel edits | ## Next steps | You want to | Read | | --------------------------------- | ----------------------------------- | | Download OrbSearch's OpenAPI spec | [HTTP API](/docs/search/http-api) | | Inspect client options and types | [TypeScript client](/docs/search/client) | | Track agent vs shopper views | [Insights](/docs/search/insights) | # Autocomplete Return query suggestions, category scopes and top hits in one request while the shopper types. Pass `on=autocomplete` to `/v1/search` to complete partial queries with your catalog's own vocabulary alongside instant product, category and guide hits. ## Fetch suggestions ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=autocomplete&query=ecks' | jq -c '.suggestions[]' ``` `"ecks"` completes to `"Ecksofa"` (corner sofa), once as a plain query and once scoped inside `wohnen/sofas`. ## Text and scoped suggestions Pass `debug=1` to inspect where each suggestion originated: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=autocomplete&query=ecks&debug=1' \ | jq -r '.trace.steps[] | select(.step == "suggest") | .suggestions[].source' ``` | Suggestion type | What it returns | | --------------- | ---------------------------------------------------------------------------------------------------------------------- | | Text | Up to 5 completions from category titles, brands, detectable attribute labels and product titles, most frequent first. | | Scoped | Takes the top text suggestion and pairs it with up to 2 categories holding the most matching products. | When a shopper selects a scoped suggestion, send both the suggested text and its category filter: ```json title="POST /v1/search" { "query": "Ecksofa", "filters": { "category": { "within": "wohnen/sofas" } } } ``` ## Return products and categories in the same call Autocomplete responses also include result sections, so a single request populates suggestions, product previews, categories and guides: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=autocomplete&query=sof&per_page=3' \ | jq -c '.suggestions, (.sections[] | select(.total > 0) | {type, hits: [.hits[].entity]})' ``` `per_page` controls how many product hits come back. Secondary sections return up to 6 hits each. ## Why typing never redirects A submitted search for `"sofa"` returns a `redirect` to `/wohnen/sofas`, while `on=autocomplete` leaves `redirect` empty so the shopper can keep typing: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa' | jq -c '.redirect' curl -s 'http://127.0.0.1:7800/v1/search?on=autocomplete&query=sofa' | jq -c '.redirect' ``` A custom redirect Rule without `when.on` still fires during autocomplete. Add `"on": "search"` to Rules meant only for submitted searches. ## Wire a search box with the client `search.suggestions()` debounces typing by 100 ms and discards stale responses automatically: ```ts title="app/search-box.ts" import { createSearch } from "@orbsearch/client"; const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); const box = search.suggestions({ locale: "de", per_page: 3 }); box.subscribe(() => { const { response } = box.current(); for (const { text, scope } of response?.suggestions ?? []) { console.log(scope ? `${text} in ${scope.title}` : text); } }); box.type("ecks"); ``` `current()` and `subscribe()` match React's `useSyncExternalStore`. For a ready-made accessible combobox, use `SearchBox` from `@orbsearch/react` ([React components](/docs/search/react)). <Callout type="info"> Suggestions are ranked by product counts across all channels, so a channel may occasionally be suggested a brand sold only in another channel. </Callout> ## Customize | You want to | Do this | Default | | ---------------------------------- | ---------------------------------------------- | ----------------------- | | Control preview product count | Pass `per_page` on the autocomplete request | `24` | | Keep redirect Rules off type-ahead | Add `"on": "search"` to the Rule's `when` | Matches every surface | | Reorder or add suggestion groups | Pass `groups` or `suggestion` to `<SearchBox>` | Default built-in groups | ## Next steps | You want to | Read | | --------------------------------- | ----------------------------------------------------------------- | | Use the accessible `<SearchBox>` | [React components](/docs/search/react) | | Understand submitted queries | [Query understanding](/docs/search/query-understanding) | | Check keyboard and ARIA behaviour | [Accessibility](/docs/search/accessibility#built-in-semantics-by-area) | # Banners and teasers Place campaign banners and grid teasers on search and category pages through rules, with schedules, conflict handling and WebP image uploads. A banner is a [Rule](/docs/search/rules) effect (`then.place`), not a catalog entity. Because it lives on a rule, it inherits conditions, schedules, rule priority, draft previews and full trace explanations. ## Define banners in `rules.json` ```json title="rules.json" { "id": "home/sofa-sale", "when": { "category": { "is": "wohnen/sofas" } }, "then": { "place": [ { "slot": "top", "banner": { "kind": "banner", "title": { "de": "Sofas im Angebot", "en": "Sofas on sale" }, "link": { "to": "category:wohnen/sofas", "filters": { "on_sale": true } } } }, { "slot": "grid", "position": 4, "banner": { "kind": "teaser", "title": { "de": "Sessel aus Leder und Samt", "en": "Armchairs in leather and velvet" }, "link": { "to": "category:wohnen/sessel" } } } ] } } ``` | Slot | Width (`kind`) | Placed where | Shown on | | -------- | --------------------------------- | -------------------------------- | ---------------------- | | `top` | `banner` (full width) or `teaser` | Above the results | Page 1 only | | `grid` | `teaser` (tile width) or `banner` | Before tile `position` (1-based) | Page holding that tile | | `bottom` | `banner` or `teaser` | Below the results | Last page only | Banners never alter product totals, facets or pagination. They are omitted on autocomplete, redirect responses and `count_only` calls. ## Precedence and limits - **Rule order settles clashes:** when two rules place a `grid` banner at the same `position`, the higher rule wins and the lower rule shifts to the next free slot (dropped if past the last tile on the page). - **Maximum 8 banners per page:** excess placements are skipped in rule order and recorded in the trace. - **No rebuilding needed:** adding, editing or scheduling banners goes live via an instant **Switch**. ## Add a banner <Tab value="Panel"> Open _Merchandising → Banners_ (or edit a rule under _Search → Rules_) and click **New banner**: 1. Pick the **Category page** (or choose **Other pages or searches** for a custom condition). 2. Choose **Place** (`top`, `grid` with a 1-based position, or `bottom`) and **Kind** (`banner` or `teaser`). 3. Enter localised **Title**, optional copy, **Image** (with required **Image description**) and **Leads to** destination. 4. Optionally set **Starts** and **Ends** under **When**, then **Save** and **Publish**. </Tab> <Tab value="API"> Add a rule with `then.place` in a draft and preview its placements immediately: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) jq -n --arg version "$version" '{version: $version, name: "Sofa guide among sofas", fields: { when: {trigger: {kind: "category", category: "wohnen/sofas"}}, then: {place: [{slot: "grid", position: 2, banner: {kind: "teaser", title: {de: "Welches Sofa passt?", en: "Which sofa fits?"}, link: {to: "content:guide-sofa-finden"}}}]}}}' \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/rules \ | jq -r '.rules.rules[:2][] | "\(.position). \(.summary)"' ``` </Tab> ## Upload banner images Upload an image through the control plane (`POST /api/v1/media`) or the panel's image uploader so you do not need separate image hosting: ```sh curl -s -H "Authorization: Bearer $key" -F file=@sale.jpg $api/media | jq -r .url ``` | Rule | Behaviour | | -------------- | ------------------------------------------------------------------------------- | | Accepted input | JPEG, PNG, WebP or AVIF up to 20 MB (SVG is rejected for security). | | Normalisation | Converted to WebP, max 2,400 px on the long side, auto-oriented, EXIF stripped. | | URL & caching | Content-addressed `/media/<shop>/<hash>.webp` with 1-year `immutable` cache. | | Clean-up | Unreferenced uploads are removed automatically after 24 hours. | <Callout type="warn"> Releases accept `http://` image URLs only for `localhost`. Production shops require `https://` via `APP_URL`, `ORBSEARCH_MEDIA_URL` or a public bucket ([Self-hosting](/docs/search/self-hosting#storage-media-backups-and-upgrades)). </Callout> ## Customize | You want to | Do this | Default | | -------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------- | | Host uploaded images in R2 / S3 | Set `ORBSEARCH_MEDIA_DISK=s3` and `ORBSEARCH_MEDIA_URL` | Local `media` volume | | Restyle or replace `<Banner>` in React | Select `[data-slot="banner"]` or pass `banner` prop to `<ListingPage>` | Built-in `Banner` | | Track banner impressions and clicks | Report `placement: "<rule-id>"` ([Clicks and views](/docs/search/clicks-and-views)) | Automatic in `@orbsearch/react` | ## Next steps | You want to | Read | | ----------------------------------- | ---------------------------------------- | | Render placements on category pages | [Category pages](/docs/search/category-pages) | | Learn rule conditions and schedules | [Rules](/docs/search/rules) | | Configure media bucket storage | [Self-hosting](/docs/search/self-hosting) | # Category pages Serve category listings with descendant products, hierarchical subcategories, banners and breadcrumbs in one request. A category page is a search without query text on `on=category_page`. Pass the category ID directly, or let `/v1/resolve` match the category's URL and return results, breadcrumbs and SEO headers in one call. ## List a category ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas' \ | jq -c '.listed, (.sections[] | {type, total, hits: [.hits[].entity]})' ``` The answer contains one section (`listed`, usually `product`) along with the page's [Facets](/docs/search/facets) and `sorts`. An unknown category ID returns an empty product section on `/v1/search`, whereas `/v1/resolve` returns `not_found` (`404`). ## Subtree products and subcategories Every category page includes products assigned to that category and every descendant category beneath it: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen' \ | jq -c '.sections[] | select(.type == "product") | .total, (.facets[] | select(.field == "category") | .values[] | {value, label, count})' ``` The `category` facet is `hierarchical` and lists direct child categories one level down. - **Filter within the current page:** pass `"filters": { "category": { "within": "wohnen/sofas" } }`. - **Navigate to the child category:** link to the child's URL so the shopper gets that category's own facets, default sort and banners. <Callout type="info"> `where` on a category node in `categories.json` is validated on save but not evaluated at query time. Category pages list only items assigned in the catalog. </Callout> ## Banners and teasers across pages `placements` holds banners and teasers placed by [Rules](/docs/search/rules) for the category, localised in the request's locale: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas&per_page=2&page=2' \ | jq -c '[.placements[] | {slot, position}], (.sections[] | {total, hits: [.hits[].entity]})' ``` | Slot | Shown on | Positioning rule | | -------- | -------------- | ----------------------------------------------------------------------------- | | `top` | Page 1 only | Above the product grid. | | `grid` | Matching page | `position` counts across all pages: index `position - (page - 1) * per_page`. | | `bottom` | Last page only | Below the product grid. | Banners never alter `total`, facet counts or product pagination, and are omitted on `count_only` requests. ## Breadcrumbs and canonical URLs via resolve Storefronts serving pages by path call `/v1/resolve` to receive `breadcrumbs`, `canonical`, `robots` and `results` together: ```sh curl -s -G http://127.0.0.1:7800/v1/resolve --data-urlencode 'url=/wohnen/sofas' -d results=0 \ | jq -c '{entity, canonical}, .breadcrumbs' ``` Omit `-d results=0` to receive the full listing in the same HTTP round trip. ## Customize | You want to | Do this | Default | | ----------------------------------- | ------------------------------------------------------------- | ----------------------------- | | Pick category-specific facets/sorts | Add a node in [Pages and filters](/docs/search/pages) | Inherited from parent/default | | Pin hero products at the top | Configure the category's Grid or a pin [Rule](/docs/search/rules) | Relevance / business score | | Place campaign banners in the grid | Add a `place` effect ([Banners and teasers](/docs/search/banners)) | None | ## Next steps | You want to | Read | | ----------------------------------- | -------------------------------------- | | Place banners on category pages | [Banners and teasers](/docs/search/banners) | | Serve categories at your own URLs | [URLs and redirects](/docs/search/urls) | | Configure category facets and grids | [Pages and filters](/docs/search/pages) | | Render `<ListingPage>` in React | [React components](/docs/search/react) | # Channels Configure markets with their locales, currency, phone-masking countries, product assortments and rule context keys. A [Channel](/docs/search/concepts#channel) represents one storefront market: the languages it speaks, its currency, the countries it serves and which products it carries. ## Declare channels in `channels.json` ```json title="channels.json" { "channels": [ { "id": "de", "label": { "de": "Deutschland", "en": "Germany" }, "locales": ["de", "en"], "currency": "EUR", "countries": ["DE"] } ], "context": { "customer_group": ["b2c", "b2b"] } } ``` - **Defaults:** requests omitting `channel` or `locale` use the first channel and its first locale; passing an undeclared locale returns `400`. - **Privacy masking:** `countries` guides national phone-number redaction before queries enter the search log ([Insights](/docs/search/insights#personal-data)). - **Auto-derivation:** omitting `channels.json` derives channels, locales and currencies from your catalog. Editing `channels.json` triggers a **Rebuild**. ## Per-channel offers and currencies Every offer must match its channel's currency (rows naming another currency are rejected and logged). Shops with multiple channels pass an `offers` array per variant: ```json title="catalog.jsonl (variant excerpt)" { "id": "SOFA-ASKA-2-GRAU", "offers": [ { "channel": "de", "price": 749.0, "currency": "EUR", "availability": "in_stock" }, { "channel": "ch", "price": 729.0, "currency": "CHF", "availability": "in_stock" } ] } ``` Single-channel catalogs can write `price`, `sale_price` and `availability` directly on the variant. ## Restrict a channel's assortment Add an `assortment` selector on a channel to exclude variants at index time: ```json title="channels.json" { "channels": [ { "id": "de", "locales": ["de", "en"], "currency": "EUR", "assortment": { "not": { "brand": "Lumivo" } } } ] } ``` Excluded variants disappear completely from searches, facets, suggestions and `GET /v1/product` in that channel. `POST /api/v1/preview/find` names the channel's assortment if you ask why an excluded product is missing. ## Declare `context` for targeting rules Declare allowed request context keys and values under top-level `context` (such as `"customer_group": ["b2c", "b2b"]`). Storefronts then pass `"context": { "customer_group": "b2b" }` on `POST /v1/search`, and [Rules](/docs/search/rules) match on `when.context`. Undeclared keys or values return `400`. Never pass personal data in `context`. ## Customize | You want to | Do this | Default | | ------------------------------------- | --------------------------------------------------- | -------------------------- | | Hide a brand in one market only | Set `assortment` on that channel in `channels.json` | All priced/member variants | | Target B2B vs B2C merchandising rules | Declare `context` keys in `channels.json` | None declared | | Mask national phone numbers in logs | List ISO country codes in `countries` | International formats only | ## Next steps | You want to | Read | | -------------------------------------- | -------------------------------------------------------------- | | Pass `channel`, `locale` and `context` | [Search and browse](/docs/search/search#channel-locale-and-context) | | Localise attribute labels and slugs | [Types and attributes](/docs/search/types-and-attributes) | | Push per-channel price updates | [Live prices and stock](/docs/search/prices-and-stock) | # Clicks and views Report shopper clicks and views to POST /v1/events with zero cookies, automatic React tracking and Global Privacy Control support. A search that returns hits can still miss what shoppers wanted. Reporting clicks and views feeds [Insights](/docs/search/insights) with click-through rates, zero-click queries and sponsored campaign metrics, without storing anything on the shopper's device. `@orbsearch/react` reports automatically. For custom storefronts, call `search.report`: ## Report clicks and views with the client ```ts title="app/results.ts" import { createSearch } from "@orbsearch/client"; const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); const answer = await search.query("", { on: "category_page", category: "wohnen/sofas" }); const sofa = { query_id: answer.query_id, entity: "product:SOFA-ASKA-2", position: 1 }; export function reportTile(tile: Element) { tile.addEventListener("click", () => search.report.click(sofa)); return search.report.watch(tile, sofa); // reports one view after >=50% visible for 1s } search.report.view({ query_id: answer.query_id, placement: "home/sofa-sale" }); search.report.flush(); ``` - **Clicks** fire immediately via `navigator.sendBeacon` (including middle-clicks) so navigation never blocks. - **Views** fire once an element is at least 50 % visible for 1 second (deduplicated per `query_id` and item), queued in memory and flushed on page hide or at 100 events. - **"Load more" hits** keep the first page's `query_id` with continuous 1-based `position`; sponsored hits also pass `campaign`. ## Report from custom React lists Wrap your list in `<Answer queryId={...}>` inside `<StorefrontProvider>` and spread `useReport()` onto each item: ```tsx title="app/sofa-link.tsx" import { Answer, useReport } from "@orbsearch/react"; export function SofaLinks({ queryId }: { queryId: string }) { return ( <Answer queryId={queryId}> <ul> <SofaLink entity="product:SOFA-ASKA-2" position={1} /> </ul> </Answer> ); } function SofaLink({ entity, position }: { entity: string; position: number }) { const report = useReport({ entity, position }); return ( <li {...report}> <a href="/p/aska-2-sitzer-sofa">Aska 2-Sitzer-Sofa aus Samt</a> </li> ); } ``` ## Respect consent and Global Privacy Control Pass `report: false` to disable all reporting (including inside `@orbsearch/react` components and WebMCP tools): ```ts title="app/privacy-search.ts" import { createSearch } from "@orbsearch/client"; const gpc = typeof navigator !== "undefined" && "globalPrivacyControl" in navigator && navigator.globalPrivacyControl === true; export const search = createSearch({ endpoint: "http://127.0.0.1:7800", report: !gpc }); ``` Recreating the client with `report: false` for the same `pageView` drops any buffered views immediately. On the server, report calls are no-ops. ## The Events API underneath The client posts batches to `POST /v1/events` on the Query API with no key, no cookies and `Content-Type: text/plain` (avoiding CORS preflight on beacons): ```sh query_id=$(curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa' | jq -r .query_id) curl -s http://127.0.0.1:7800/v1/events -H 'Content-Type: text/plain' \ -d '{"events": [{"type": "click", "query_id": "'"$query_id"'", "entity": "product:SOFA-ASKA-2", "position": 1}]}' ``` | Rule | Value | | ------------ | ------------------------------------------------------------------------------ | | Response | `202` with `{ "accepted": N, "late": M }`. | | Batch limits | 1 to `100` events, max `64 kB` (`413` if larger, `400` if any item invalid). | | Late window | Events older than `48 hours` (derived from UUIDv7 `query_id`) count as `late`. | ## Customize | You want to | Do this | Default | | ----------------------------------- | ---------------------------------------------------------- | ------------------------------- | | Gate reporting on user consent | Pass `report: hasConsent` to `createSearch()` | Enabled in browsers | | Attribute sponsored campaign events | Include `campaign` in `click()` / `watch()` | Automatic in `@orbsearch/react` | | Distinguish AI agent views | Set `surface: "agent"` (automatic in `registerAgentTools`) | `"storefront"` | ## Next steps | You want to | Read | | --------------------------------------- | ------------------------------------------------ | | Read click-through and campaign reports | [Insights](/docs/search/insights) | | Learn how sponsored campaigns bill | [Sponsored products](/docs/search/sponsored-products) | | Check Events API schema & limits | [HTTP API](/docs/search/http-api#query-api) | # TypeScript client Call OrbSearch's Query API from any framework or server with generated contract types, error handling and listing URL helpers. `@orbsearch/client` is a framework-free TypeScript client for the Query API with types generated straight from OrbSearch's Rust contract. `@orbsearch/react` builds on top of it. ## Create a client and query ```ts title="app/search.ts" import { createSearch } from "@orbsearch/client"; export const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); const answer = await search.query("graues Sofa"); const sofa = await search.product({ id: "SOFA-ASKA-2" }); const page = await search.resolve("/wohnen/sofas/farbe--grau"); ``` Every method accepts an optional third `{ signal }` argument to abort stale requests when shoppers navigate. | Method | Calls | Returns | | ----------------------- | -------------------------------- | ------------------------------------------------------------------- | | `search.query(q, opts)` | `POST /v1/search` | `SearchResponse` (sections, facets, resolution, sorts, placements). | | `search.product(opts)` | `GET /v1/product` | `Product` or `null` when `404`. | | `search.resolve(url)` | `GET /v1/resolve` | `PageResponse` (listing, product, redirect, `gone` or `not_found`). | | `search.facets(req)` | `POST /v1/search` (`count_only`) | Full counts for deferred or truncated facets. | | `search.suggestions()` | Debounced `autocomplete` | External store (`current()`, `subscribe()`, `type()`). | | `search.robots()` | `GET /v1/robots` | `Disallow` lines for `robots.txt`. | | `search.report.*` | `POST /v1/events` | `click()`, `view()`, `watch()`, `flush()`. | ## One client per page load and custom `fetch` Create one client per server request (forwarding the shopper's `User-Agent` so bot filtering works) and pass its `pageView` to the browser client so Insights counts one page view: ```ts worker title="app/search.server.ts" import { createSearch } from "@orbsearch/client/server"; export function searchFor(request: Request, transport?: typeof fetch) { const userAgent = request.headers.get("user-agent"); return createSearch({ endpoint: "https://search.internal", ...(userAgent && { userAgent }), ...(transport && { fetch: transport }), }); } ``` Use `@orbsearch/client/server` in Workers and server bundles (no DOM types, no browser beacon reporter). Set `traffic: "test"` or `"bench"` to keep automated runs out of shopper reports. <Callout type="warn"> Never ship a management API key to the browser. The Query API is public, read-only and CORS-enabled for every origin. </Callout> ## Handle errors Non-2xx responses throw `SearchError` carrying the RFC 9457 `problem` object: ```ts title="app/handle-error.ts" import { createSearch, SearchError } from "@orbsearch/client"; const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); try { await search.query("sofa", { sort: "cheapest" }); } catch (error) { if (!(error instanceof SearchError)) throw error; console.error(error.problem.status, error.problem.detail); } ``` - **`400`:** invalid parameter, sort or filter; inspect `problem.violations`. - **`503`:** engine unreachable or no index live yet; let the shopper retry. ## Generated types and URL helpers Import contract types such as `SearchResponse`, `FacetResult`, `PageResponse` and `Product` (note: `@orbsearch/client`'s `Product` is a PDP product; `@orbsearch/react`'s `Product` is a tile view), plus constants `SEARCH_PATH`, `RELEVANCE_SORT` and `EVENT_HOURS`. `@orbsearch/client/schema/listing-card.json` exports the standalone JSON Schema 2020-12 for `ListingCard`. Build canonical listing URLs when a facet value does not provide a pre-built `url` (such as ranges or multi-select changes): ```ts title="app/links.ts" import { listingHref } from "@orbsearch/client"; const href = listingHref("/suche", { query: "sofa", filters: { color: ["grey", "green"], price: { gte: 100, lte: 300 }, on_sale: true }, sort: "price_asc", page: 2, }); ``` Companion URL helpers: - **`listingOf(page)`** reads listing state from a `resolve()` answer (respecting renamed parameters). - **`keptParams(listing)`** returns hidden form inputs (`q`, `sort`, etc.) to preserve across plain HTML form submissions. - **`filtersOf(url, facets)`** parses query parameters against facet definitions (distinguishing `seats=1` from toggle `on_sale=1`). ## Customize | You want to | Do this | Default | | ------------------------------------------ | --------------------------------------------------------- | ------------------- | | Route through a Cloudflare Service Binding | Pass `fetch: (req) => env.SEARCH.fetch(req)` | Global `fetch` | | Disable browser click/view reporting | Pass `report: false` to `createSearch()` | Enabled in browsers | | Expose browser tools to AI agents | Call `registerAgentTools()` ([AI agents](/docs/search/agents)) | Disabled | ## Next steps | You want to | Read | | -------------------------------- | --------------------------------------------- | | Build a full React storefront | [Build a storefront](/docs/search/your-storefront) | | Report clicks and views manually | [Clicks and views](/docs/search/clicks-and-views) | | Register WebMCP browser tools | [AI agents](/docs/search/agents) | # Concepts How OrbSearch separates catalog indexing from query answering, and the core terms every page uses. OrbSearch splits work into two paths. Everything you send (your catalog and your rules) is compiled ahead of time, so a shopper's search runs in memory and makes a single call to Meilisearch. The write path turns your shop's export into an immutable Snapshot and your configuration files into an immutable Release. An Index run compiles both into fresh Meilisearch indexes and swaps them live, while the Query API loads the Release into memory. On the read path, the Query API resolves the shopper's query, applies rules, makes one call to Meilisearch, and returns ranked sections, facets and an optional debug Trace. ## How the two paths work ### The write path Every catalog upload is stored byte for byte as a **Snapshot**, and every configuration bundle is stored as a **Release**. Neither changes after it is stored. An **Index run** compiles one Snapshot and one Release into new Meilisearch indexes beside the live ones, then swaps them in atomically. A run starts when a catalog arrives, a Release or Import publishes, a scheduled feed changes, a rebuild is requested, or a sale window opens or closes. ### The read path When a search arrives, the **Query API** resolves the query against the live Release in memory, applies merchandising rules and sends one request to Meilisearch. It then ranks the hits, counts facets and builds the answer. Every answer names the exact `release` and `snapshot` that produced it: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=couch' | jq -c '{release, snapshot}' ``` Two exceptions make a different number of engine calls: a redirect to a fixed URL skips Meilisearch altogether, and a zero-hit query with detected filters retries with [relaxation](/docs/search/no-results). ## The four moving parts | Part | Responsibility | | ------------- | --------------------------------------------------------------------------- | | Control plane | Serves the Management API and panel; stores Releases, runs and Snapshots. | | Indexer | Executes Index runs, compiling Snapshots and Releases into Meilisearch. | | Query API | Answers searches, products and URLs without a key; never waits on Postgres. | | Meilisearch | Holds compiled, disposable indexes per entity type and locale. | ## Core terms ### Release The complete search configuration stored as up to fourteen JSON files (such as `synonyms.json` and `rules.json`). Releases are content-addressed and immutable; rolling back publishes an earlier Release again ([Releases](/docs/search/releases)). ### Snapshot One catalog upload kept byte for byte and identified by its content hash. Sending identical bytes reuses the same Snapshot ([Catalog formats](/docs/search/formats)). ### Index run The background job that compiles one Snapshot and one Release into Meilisearch. Only a `succeeded` run goes live; a failed run leaves live search untouched ([Import reports](/docs/search/import-report)). ### Resolution Structured intent extracted from a shopper's query before text search runs: category, attribute filters, numeric bounds and the leftover text ([Query understanding](/docs/search/query-understanding)). ### Trace The step-by-step audit attached when `debug=1` is passed, recording every detection, rule outcome, sort decision, relaxation step and ranking reason ([Search and browse](/docs/search/search#the-trace)). ### Section One entity type's results inside a search answer, such as `product`, `category`, `content` or `brand`. One Section is `listed` and carries paging and facets. ### Channel One storefront market defining currency, supported locales, phone-masking countries and optional product assortment ([Channels](/docs/search/channels)). ### Facet A filter shoppers choose from (list, swatch, range, buckets, toggle or hierarchical tree) paired with live result counts ([Facets and filters](/docs/search/facets)). ### Rule A condition (`when`) and effects (`then`) in `rules.json` that pin, boost, bury, hide, filter, redirect or place banners, evaluated in strict priority order ([Rules](/docs/search/rules)). ### Draft An unpublished Import holding a catalog and modified Release files. You edit, inspect, preview and validate a Draft before publishing it ([Releases](/docs/search/releases#work-in-a-draft)). ## Design principles - **Fast without a query cache.** Configuration compiles on publish, so each search is in-memory planning plus one engine round trip. - **Self-explaining answers.** Content-addressed Releases and Snapshots plus `debug=1` traces let you explain any ranking decision. - **Rebuilds replace nothing live.** Meilisearch holds derived state only; new indexes build beside live ones and swap atomically. - **Rollback is one publish.** Because Releases never mutate, restoring a prior state republishes its ID. ## Next steps | You want to | Read | | ------------------------------- | -------------------------------------------------- | | Run both paths locally | [Quickstart](/docs/search/quickstart) | | See request and response shapes | [Search and browse](/docs/search/search) | | Follow how queries are resolved | [Query understanding](/docs/search/query-understanding) | | Publish and roll back safely | [Releases](/docs/search/releases) | # Environment variables Reference of every .env variable in OrbSearch's Docker Compose stack, its default, whether it is required and which services read it. All stack configuration lives in `.env`. Run `make .env` in the OrbSearch repository to copy `.env.example` and generate missing secrets without overwriting existing values. ## Core secrets and authentication | Variable | Required | Default | Purpose | | -------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ | | `APP_KEY` | Yes | None | Control plane encryption key (`base64:` + 32 random bytes) for cookies, 2FA and feed auth. | | `POSTGRES_PASSWORD` | Yes | None | Postgres superuser password (used once at volume init and by `roles`). | | `DB_PASSWORD` | Yes | None | Password for the control plane's `control` Postgres role. | | `NODE_DB_PASSWORD` | Yes | None | Password for the first shop's node role `orbsearch_shop_shop`. | | `MEILI_MASTER_KEY` | Yes | None | Meilisearch master key (≥ 16 bytes); held only by `indexer`. | | `MEILI_SEARCH_KEY` | Yes | None | Search-only key for `orbsearch`, derived as HMAC of `MEILI_MASTER_KEY`. | | `ORBSEARCH_MANAGEMENT_KEY` | Yes\* | None | First shop's initial Management API key (taken once on first migration; omit on operator-only setups). | | `ORBSEARCH_NODE_KEY` | Yes | None | Node key (≥ 32 printable ASCII chars) protecting `/internal/*` and snapshot downloads. | | `ORBSEARCH_OPERATOR_KEY` | No | Empty | Enables `/api/v1/shops/*` Operator API; empty disables it. | | `ORBSEARCH_STAFF_ISSUER` | No | Empty | OrbCommerce Admin URL whose EdDSA staff JWTs the first shop trusts on initial migration. | ## Networking, ports and versions | Variable | Default | Purpose | | ------------------- | ----------------------- | ----------------------------------------------------------------------------- | | `APP_URL` | `http://localhost:8000` | Public panel URL; an `https://` URL enables secure session cookies. | | `PUBLISH_ADDRESS` | `127.0.0.1` | Host bind address for `control` and `orbsearch` (`0.0.0.0` exposes directly). | | `CONTROL_PORT` | `8000` | Host port for the panel and Management/Operator APIs. | | `ORBSEARCH_PORT` | `7800` | Host port for the Query API. | | `POSTGRES_PORT` | `5432` | Host port for Postgres (always `127.0.0.1` only). | | `MEILISEARCH_PORT` | `7700` | Host port for Meilisearch (always `127.0.0.1` only). | | `TRUSTED_PROXIES` | Empty | Comma-separated reverse proxy IPs in front of `control` (never `*`). | | `ORBSEARCH_VERSION` | Build local | Release tag without `v` (e.g. `0.1.0` or `edge`) for `docker compose pull`. | | `SHOP_URL` | `http://localhost:3000` | Storefront origin used to resolve relative preview images in the panel. | ## Feeds, storage, media and optional services | Variable | Default | Purpose | | ------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------- | | `ORBSEARCH_FEEDS_FROM_PRIVATE_NETWORKS` | `false` | Set `true` to allow scheduled feeds on private/loopback networks. | | `ORBSEARCH_FEED_TIMEZONE` | `Europe/Berlin` | Timezone for 12-hour (`04:00`/`16:00`) and daily (`04:00`) feed polls. | | `ORBSEARCH_SNAPSHOT_DISK` | `snapshots` | `snapshots` (local volume) or `s3` (Cloudflare R2 / S3 bucket). | | `ORBSEARCH_MEDIA_DISK` | `media` | `media` (local volume at `/media`) or `s3` (public bucket). | | `ORBSEARCH_MEDIA_BUCKET` | Empty | Dedicated public bucket name when `ORBSEARCH_MEDIA_DISK=s3`. | | `ORBSEARCH_MEDIA_URL` | `APP_URL/media` | Public HTTPS base URL browsers load uploaded banner images from. | | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`, `AWS_BUCKET`, `AWS_ENDPOINT`, `AWS_USE_PATH_STYLE_ENDPOINT` | Empty | S3/R2 credentials and endpoint (`auto` region, path-style `true` for R2). | | `MAIL_MAILER`, `MAIL_SCHEME`, `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD`, `MAIL_FROM_ADDRESS` | Log mailer | SMTP settings for panel emails; enables email verification when configured. | | `AI_GATEWAY_API_KEY` | Empty | Optional Vercel AI Gateway key enabling `typesafe-ai/jev` column mapping suggestions. | ## Test and multi-copy Compose profiles Variables used only by `compose.yaml` profiles (`second-shop` and `second-copy`) and `make e2e`: | Variable | Default | Purpose | | ------------------------------------------------------------------------- | -------------- | ---------------------------------------------- | | `DEMO_PORT` | `3000` | Local demo storefront port for E2E tests. | | `SECOND_SHOP_KEY`, `SECOND_SHOP_NODE_KEY`, `SECOND_SHOP_NODE_DB_PASSWORD` | Empty | Secrets for the `second-shop` Compose profile. | | `SECOND_ORBSEARCH_PORT`, `SECOND_MEILISEARCH_PORT` | `7801`, `7701` | Host ports for the second shop's node. | | `COPY_ORBSEARCH_PORT`, `COPY_MEILISEARCH_PORT` | `7802`, `7702` | Host ports for the `second-copy` profile. | ## Next steps | You want to | Read | | ----------------------------------- | ---------------------------------------------- | | Deploy and secure the Compose stack | [Self-hosting](/docs/search/self-hosting) | | Run the stack locally in minutes | [Quickstart](/docs/search/quickstart) | | Check hard API and engine limits | [Errors and limits](/docs/search/errors-and-limits) | # Errors and limits RFC 9457 Problem Details error format, HTTP status codes, conflict payloads and every hard limit enforced by OrbSearch. Every error from the Query, Management and Operator APIs returns [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457) (`application/problem+json`), except `GET /ready` `503` which returns its readiness JSON with `reasons`. ## Error format ```json title="GET /v1/search?query=sofa&per_page=500" { "type": "about:blank", "title": "Bad Request", "status": 400, "detail": "The request cannot be answered as sent; each violation names the field.", "violations": [{ "pointer": "/per_page", "message": "A page holds 1 to 100 hits." }] } ``` `type` is always `about:blank`. Branch on `status`, display `detail` and each entry in `violations` (`pointer`, optional `file`, `message`). ### Extended conflict payloads - **`DraftConflict` (`409`):** includes `draft` (the latest draft state and `version`) when a write used a stale `version`, so callers can reapply cleanly; `draft` is omitted if the draft was already published or discarded. - **`SynonymsRefused` (`422`):** includes `refused` listing each clashing synonym entry and its exact `conflicts`. ## HTTP status codes | Status | Meaning | Recovery | | ------ | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | `400` | Malformed request or unknown channel, locale, sort, filter field, context or event. | Fix the fields listed in `violations`. | | `401` | Missing, wrong or expired key/staff token, or untrusted `staff_issuer`. | Authenticate with a valid key or fresh staff token. | | `403` | Staff token lacks `search` access (`view` on a write, or removed from staff). | Grant `search: edit` in the OrbCommerce Admin. | | `404` | Unknown product, import, working draft, release, index run, catalog source or shop. | Check the ID or handle missing products cleanly. | | `409` | Stale draft `version`, action before first catalog, or ≥ 50 % removal unconfirmed. | Refetch `draft.version`, upload catalog first or confirm `removing`. | | `413` | Request exceeds upload limit (`64 kB` on `/v1/events`, control plane limit on uploads). | Chunk events to ≤ 100 per call or split large payloads. | | `422` | Schema or cross-file release violation, batch cap exceeded, or broken test without reason. | Fix `violations`, respect batch limits or supply `reason`. | | `503` | No live index yet, Meilisearch unreachable, or admin JWKS temporarily unavailable. | Retry with backoff (respect `Retry-After` if present). | ## Hard limits All limits below come directly from `contracts/limits.json`. ### Search, facets and URLs | Limit | Value | Applies to | | --------------------- | -------- | --------------------------------------------------------------------------- | | `per_page` | `100` | Maximum hits per page (default `24`). | | `reachable_hits` | `1,000` | Deepest hit reachable via pagination (totals still count past it). | | `counted_facets` | `30` | Facets counted up front per page before remaining ones return `deferred`. | | `facet_values` | `50` | Values returned per list/swatch facet before `more` signals truncation. | | `token_dimensions` | `8` | Variant-level fields combined into combination tokens per Type (`2^n - 1`). | | `filter_combinations` | `1,000` | Cross-product combinations across chosen variant-level filter values. | | `placements_per_page` | `8` | Maximum banners/teasers shown per page across `top`, `grid` and `bottom`. | | `redirect_patterns` | `500` | Regex patterns in `redirects.json` (exact redirects have no cap). | | `sitemap_urls` | `50,000` | URLs returned per page of `GET /v1/sitemap`. | ### Rules and expressions | Limit | Value | Applies to | | ---------------------- | -------- | -------------------------------------------------------------------------- | | `rules_per_release` | `10,000` | Maximum rules in `rules.json`. | | `description_length` | `200` | Maximum characters in a rule's description or sponsored campaign name. | | `pins_per_rule` | `100` | Maximum pins inside one rule. | | `pins_per_query` | `100` | Maximum active pins per section on one request. | | `targets_per_query` | `4` | Maximum boost/bury targets per section (`2^n - 1` engine sub-searches). | | `keys_per_query` | `96` | Total active engine rule keys (pins + targets) per request. | | `hidden_per_query` | `100` | Entity IDs hidden by rules on one request (use Overlays for global hides). | | `phrases_per_operator` | `100` | Phrases in one `is`, `contains` or `starts_with` clause. | | `nesting_depth` | `3` | Maximum nesting of `any`, `all` and `not`. | ### Writes, events and previews | Limit | Value | Applies to | | ------------------- | ------- | --------------------------------------------------------------------------- | | `offers_per_call` | `1,000` | Offer changes per `PUT /api/v1/offers` call. | | `products_per_call` | `200` | Entities + `gone` entries per `PUT /api/v1/products` call. | | `synonyms_per_call` | `1,000` | Entries added in one `POST .../synonyms` call. | | `words_per_check` | `50` | Words checked per `POST .../synonyms/check` call. | | `events_per_call` | `100` | Events per `POST /v1/events` call (and `64 kB` max body). | | `event_hours` | `48` | Hours after an answer that clicks and views join its search (`late` after). | | `arrival_hours` | `24` | Max upload/fetch duration before stale arrivals expire. | | `moved_urls` | `100` | Sample moved/lost URLs listed in `POST /api/v1/preview/urls` (all counted). | | `compared_queries` | `100` | Top queries compared in `GET /api/v1/imports/{import}/review`. | ## Next steps | You want to | Read | | ---------------------------------- | ------------------------------------------------- | | Browse every HTTP endpoint | [HTTP API](/docs/search/http-api) | | Handle `SearchError` in TypeScript | [TypeScript client](/docs/search/client#handle-errors) | | Check current product limitations | [Project status](/docs/search/status) | # Extend OrbSearch Map every OrbSearch extension point from CSS tokens and slots to custom tiles, facet displays, BuyBox source and release APIs. OrbSearch adapts in clear layers. Most shops stop after overriding `--orb-*` tokens and a few `data-slot` rules; when you need bespoke layouts or behaviour, compose or swap individual parts without losing accessibility or reporting. | Depth | Seam | Best for | | ----- | --------------------------------------------------- | -------------------------------------------------------------------- | | 1 | [Design tokens](#set-design-tokens) | Brand colours, fonts, radii, grid columns and dark themes. | | 2 | [Slot selectors](#style-parts-by-data-slot) | Targeted CSS on prices, sold-out tiles, chips or specific facets. | | 3 | [Compose parts](#swap-a-product-tile-or-banner) | Adding badges, reordering fields or wrapping elements (`render`). | | 4 | [Custom components](#build-a-component-of-your-own) | Custom facet displays (`custom_display`) and owning `BuyBox` source. | | 5 | [Release files & APIs](#extend-search-behaviour) | Custom entity types, patterns, rules, overlays and live pushes. | ### Set design tokens Override `--orb-*` custom properties in a stylesheet imported after `@orbsearch/react/orbsearch.css`: ```css title="app/theme.css" :root { --orb-color-accent: #2f4636; --orb-color-accent-soft: #e8efe9; --orb-color-focus: #2f4636; --orb-radius-control: 999px; --orb-font-sans: "Inter", system-ui, sans-serif; } ``` Keep WCAG 2.2 AA contrast pairs aligned when changing colours ([Theming](/docs/search/theming#contrast-pairs-wcag-22-aa)). ### Style parts by `data-slot` Select individual parts and states directly without fragile class names: ```css title="app/theme.css" [data-slot="tile-price"] { font-weight: 600; } [data-slot="product-tile"][data-sold-out] [data-slot="tile-price"] { color: var(--orb-color-ink-muted); } ``` Combine slots with state attributes such as `[data-slot="facet"][data-field="color"]` or `[data-slot="filter-chip"][data-source="query"]`. ### Swap a product tile or banner Build your own tile from `ProductTile.*` primitives and pass it to `<ListingPage tile={ShopTile} />`: ```tsx title="app/tile.tsx" import { ProductTile, useTile, type TileProps } from "@orbsearch/react"; export function ShopTile(props: TileProps) { return ( <ProductTile.Root {...props}> <ProductTile.Title /> <ProductTile.Media> <ProductTile.Image /> <ProductTile.Badges> <QuickBadge /> </ProductTile.Badges> </ProductTile.Media> <ProductTile.Price /> <ProductTile.Brand /> </ProductTile.Root> ); } function QuickBadge() { const { product } = useTile(); if (product.delivery === null || product.delivery.max > 2) return null; return <ProductTile.Badge>Fast delivery</ProductTile.Badge>; } ``` Keep `<ProductTile.Title />` first: it holds the heading, the tile's link and focus management for "Load more". Banners compose identically from `Banner.*` parts. ### Build a component of your own Declare `"custom_display": "color_tiles"` on a facet in `categories.json`, implement a component using `FacetGroup`, `ValueList` and `state.getValueProps()`, and register it once on `<StorefrontProvider displays={{ color_tiles: ColorTiles }}>`: ```tsx title="app/color-tiles.tsx" import { FacetGroup, ValueList, ValueName, type FacetDisplayProps } from "@orbsearch/react"; export function ColorTiles({ state }: FacetDisplayProps) { return ( <FacetGroup state={state}> <ValueList state={state} className="color-tiles" row={(value) => ( <li key={value.code}> <label> <input {...state.getValueProps(value)} /> <ValueName value={value} /> </label> </li> )} /> </FacetGroup> ); } ColorTiles.shown = 9; ``` **Own the BuyBox source.** Copy the `BuyBox` component source directly into your storefront with the shadcn CLI, customise it freely, and pass `buyBox={<BuyBox product={product} />}` to `<ProductPage>`: ```sh npx shadcn@latest add ./node_modules/@orbsearch/react/registry/r/buy-box.json ``` Keep its `data-slot` attributes so themes and tests continue matching it. ### Extend search behaviour Beyond UI, extend indexing and query behaviour cleanly through declarative Release files and HTTP contracts: - **Custom entity types:** declare types with `variants`, `offers` or `tree` capabilities in [Types and attributes](/docs/search/types-and-attributes). - **Domain phrases & rules:** add [Patterns](/docs/search/patterns), [Synonyms](/docs/search/synonyms) and context-targeted [Rules](/docs/search/rules). - **Catalog enrichment & real-time sync:** layer [Overlays](/docs/search/overlays), [Live prices](/docs/search/prices-and-stock) and [Live product changes](/docs/search/live-products). ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------- | | Browse every `--orb-*` token and slot | [Theming](/docs/search/theming) | | Inspect every React part and hook | [React components](/docs/search/react) | | Copy standalone facet & sheet recipes | [Storefront recipes](/docs/search/recipes) | | Check current extension limits | [Project status](/docs/search/status) | # Facets and filters Read facet counts, send shopper filter choices, render price histograms and load deferred facets on demand. Every listing response brings the page's [Facets](/docs/search/concepts#facet) with localised labels and live hit counts. ## Read facets and send filter choices Inspect the colour facet on the sofa category page: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas' \ | jq -c '.sections[] | select(.type == "product") | .facets[] | select(.field == "color") | {field, kind, label}, (.values[] | {value, label, count})' ``` Send shopper choices in `filters` via `POST /v1/search`. Values within one field combine with OR; separate fields narrow each other with AND: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{"on": "category_page", "category": "wohnen/sofas", "filters": {"color": ["grey", "green"], "width": {"gte": 160, "lte": 220}, "on_sale": true}}' \ | jq -c '.sections[] | select(.type == "product") | .hits[] | {entity, variant}' ``` The matching tile returns `variant` pointing to the exact variant that satisfies all three filters (here the sage variant on sale). | Facet kind | Request format | Example | | ---------------- | ------------------------- | ------------------------------------------ | | `list`, `swatch` | Value or group codes | `"color": ["grey", "green"]` | | `buckets` | Bucket bound code | `"delivery_days": ["-15"]` | | `range` | `gte`, `lte` or both | `"width": { "gte": 160, "lte": 220 }` | | `toggle` | `true` | `"on_sale": true` | | `hierarchical` | Category subtree selector | `"category": { "within": "wohnen/sofas" }` | `filters` accepts any field counted by at least one page in your Release; any other field returns `400`. The response's top-level `filters` array provides localised labels and `source` (`shopper`, `query` or `rule`) for filter chips. ## Disjunctive counting and upper bounds ### Chosen values stay visible Each facet is counted under every active filter except its own, so selecting `"grey"` never hides `"green"`: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{"on": "category_page", "category": "wohnen/sofas", "filters": {"color": "grey", "on_sale": true}}' \ | jq -c '.sections[] | select(.type == "product") | .total, (.facets[] | select(.field == "color") | .values[] | del(.label, .swatch))' ``` Even when zero grey sofas are on sale, `"grey"` stays in the facet at `count: 0` with `selected: true` so the shopper can deselect it, while `"green"` still shows `1`. Unselected empty values are omitted. ### Upper bounds on variant facets When a product's variants differ across multiple chosen fields (such as two sizes and two colours), some facet counts can only be upper bounds. Those facets carry `upper_bound: true`, and `debug=1` explains why. Result hits themselves always evaluate all variant choices together before counting and paging. ## Price histogram A price facet configured with `"display": "histogram"` returns fixed logarithmic bins (24 steps per decade) so bar positions stay steady while filters change: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas' \ | jq -c '.sections[] | select(.type == "product") | .facets[] | select(.field == "price") | {min, max}, (.histogram[] | select(.count > 0))' ``` Empty bins are included to keep bar alignment consistent. A product with multiple variant prices counts in every bin one of its prices lands in. ## Deferred facets and long value lists To keep every search fast, a page counts at most **30 facets** up front (plus any active filter) and returns up to **50 values** per list or swatch (`more` reports how many remain). Extra facets arrive with `deferred: true` and no values. Load a deferred or truncated facet when the shopper opens it by passing `facets` with `count_only: true`: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{"on": "category_page", "category": "wohnen/sofas", "filters": {"color": "grey"}, "facets": ["brand"], "count_only": true}' \ | jq -c '.sections[] | {total, hits, facets}' ``` `@orbsearch/react`'s `<ListingPage>` handles this automatically via `<LateFacets>` ([React components](/docs/search/react#facets-that-load-when-opened)). ## Which facets appear on a page `categories.json` sets `default.facets` for all pages and overrides specific categories under `nodes`: ```json title="categories.json" { "default": { "facets": ["category", { "field": "price", "display": "histogram" }, "style", "on_sale"] }, "nodes": [ { "category": "wohnen/sofas", "facets": ["width", "color", "upholstery", "seat_height", "price"] } ] } ``` Child categories inherit from their nearest configured ancestor. A search page uses `default`, or the resolved category's facets when the query names one. ## Customize | You want to | Do this | Default | | ---------------------------------- | ------------------------------------------------------------ | ----------------------------------- | | Choose facets per category | Edit [Pages and filters](/docs/search/pages) or `categories.json` | Derived from catalog attributes | | Group facets under one heading | Add `groups` on a node in `categories.json` | Flat facet list | | Render a custom facet UI component | Set `custom_display` and register it on `StorefrontProvider` | Built-in display for the facet kind | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------- | | Configure facets and buckets per page | [Pages and filters](/docs/search/pages) | | Browse categories with banners | [Category pages](/docs/search/category-pages) | | Keep filter selections in clean URLs | [URLs and redirects](/docs/search/urls) | | Check facet and value count limits | [Errors and limits](/docs/search/errors-and-limits) | # Scheduled feeds Pull your shop's catalog export URL automatically on a schedule with conditional ETag checks, authentication and deletion safeguards. If your shop already serves its catalog at a URL (such as a Google Merchant Center feed or OrbCatalog's `/feeds/orbsearch.ndjson`), configure it as a **Catalog source**. The control plane polls it on a schedule and indexes only when bytes change. ## Configure a catalog source <Tab value="Panel"> Open _Catalog → Imports_ and click **Add a feed URL** on the **Catalog source** card: - Enter the **Feed URL** and optional **Sign-in** (**None**, **User and password**, or **Token in a header**). - Choose how often to **Fetch** and whether changes **Publish at once** or **Keep as a draft to review**. - Click **Save** (triggers an immediate first fetch). Use **Fetch now** any time between runs, or **Remove** to stop polling. </Tab> <Tab value="API"> Configure the source with `PUT /api/v1/catalog-source`: ```sh curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ $api/catalog-source \ -d '{ "url": "https://shop.example/feeds/export.xml", "interval_minutes": 60, "on_change": "publish", "authentication": { "kind": "header", "name": "X-Api-Key", "value": "secret-token" } }' ``` Supported `interval_minutes` values: `10`, `30`, `60`, `180`, `360`, `720` (04:00 & 16:00) or `1440` (04:00) in `ORBSEARCH_FEED_TIMEZONE` (`Europe/Berlin` by default). Set `"on_change": "draft"` to review changes before publishing. For HTTP Basic auth, pass `{ "kind": "basic", "username": "...", "password": "..." }`. Trigger an immediate fetch, inspect recent runs or remove the source: ```sh curl -s -X POST -H "Authorization: Bearer $key" $api/catalog-source/fetch >/dev/null curl -s -H "Authorization: Bearer $key" $api/catalog-source | jq -c '.fetches[0] | {result, failure, message}' curl -s -X DELETE -H "Authorization: Bearer $key" $api/catalog-source >/dev/null ``` </Tab> Credentials are encrypted at rest with `APP_KEY`, sent only to the feed's own host and never returned by `GET`. Deleting a source stops future fetches while keeping past imports intact. ## Fetch outcomes Every fetch sends `If-None-Match` and `If-Modified-Since` and records one of five results: | Result | What happened | | ----------- | ------------------------------------------------------------------------------------- | | `unchanged` | Server returned `304` or identical bytes; no Index run queued. | | `published` | Feed changed and queued an Index run (`trigger: "fetch"`). | | `drafted` | Feed changed and waits as a draft (`on_change: "draft"`). | | `held_back` | Auto-publish paused because ≥ 50 % of live products would be removed; waits as draft. | | `failed` | Unreachable host, auth error, empty file, > 2 GB or unreadable; live search stays up. | A held-back feed or three consecutive failures flag `needs_attention: true` on the source and surface on the admin/panel overview. ## Private and local feed URLs For SSRF protection, private, loopback and link-local addresses are refused as `address_refused` (including after HTTP redirects). If your feed lives on an internal network, allow it in `.env`: ```dotenv title=".env" ORBSEARCH_FEEDS_FROM_PRIVATE_NETWORKS=true ``` ## With OrbCatalog OrbCatalog serves a native NDJSON feed with `ETag` support at `/feeds/orbsearch.ndjson`. See [Connect the products](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog) to wire both polling and instant offer pushes. ## Customize | You want to | Do this | Default | | -------------------------------------- | ------------------------------------------------------------------- | -------------------------- | | Review changed feeds before going live | Set `"on_change": "draft"` on the catalog source | `"publish"` (auto-publish) | | Change the daily fetch timezone | Set `ORBSEARCH_FEED_TIMEZONE` in `.env` | `Europe/Berlin` | | Push price updates between feed polls | Call `PUT /api/v1/offers` ([Live prices](/docs/search/prices-and-stock)) | Updated on next feed poll | ## Next steps | You want to | Read | | ------------------------------------ | --------------------------------------------------------------------------------- | | Map columns for your feed format | [Importing and mapping](/docs/search/importing) | | Push instant price and stock updates | [Live prices and stock](/docs/search/prices-and-stock) | | Connect OrbSearch to OrbCatalog | [Connect the products](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog) | # Fields and typos Choose which fields each entity type searches, set field priority, tune typo tolerance and protect SKUs from fuzzy matches. OrbSearch searches each [Type](/docs/search/types-and-attributes) across an ordered list of fields and forgives spelling mistakes on longer words while protecting unique identifiers such as SKUs and GTINs. ## Inspect current search settings ```sh curl -s -H "Authorization: Bearer $key" $api/search-settings \ | jq -c '.types[] | select(.type == "product") | .fields.source, [.fields.fields[].field], .typos' ``` Earlier fields in `fields` carry higher ranking priority (so `title` beats `description`). Each setting reports its `source`: `set` (written in `types.json`), `derived` (computed from the catalog) or `built_in`. ## Typo tolerance and exempt identifiers By default, words of **5+ letters** tolerate one typo and **9+ letters** tolerate two (an insertion, deletion, substitution or adjacent transposition; a mismatch on the first letter counts as two). Shorter words match only exact or prefix spellings. ### Protect part numbers and GTINs A single-character typo on a part number finds the wrong product. Any attribute listed under `no_typos` in `types.json` matches exact or prefix terms only: - When `no_typos` is omitted, each Index run inspects identifier attributes automatically. - An identifier is marked `unique` and exempted when at least 90 % of 10+ values belong to a single product. - Shared cross-reference codes (`shared`) or catalogs with too few samples (`few`) remain open to typos unless exempted explicitly. ### Diagnose why a product did not match Use `POST /api/v1/preview/find` (or **Why isn't it here?** in the Playground) when a product contains a word that search missed: ```sh curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ -d '{"request": {"query": "geölt"}, "entity": "product:BETT-FJORD"}' $api/preview/find \ | jq -c '.verdict.held[], .next[0]' ``` `held` names the field holding the word and the exact reason (`not_searched` or `exempt_from_typos`). ## Change searched fields or typo rules <Tab value="Admin / Panel"> Open _Search → Search settings_ (or _Search → Fields & typos_ in the standalone panel) and select a Type: - **Searched fields:** drag fields to reorder priority, or click **Add a field**. - **Typos:** toggle typo tolerance and adjust **One typo from** and **Two typos from**. - **Exempt from typos:** add or remove identifier attributes, or click **Back to the default** to revert to derived settings. </Tab> <Tab value="API"> Update a Type inside a draft with `PATCH /api/v1/imports/{import}/search-settings/{type}` (pass `null` for any key to reset it to derived defaults): ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft/search-settings | jq -r .version) jq -n --arg version "$version" '{version: $version, typos: {enabled: true, one_typo: 4, two_typos: 9}}' \ | curl -s -X PATCH -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/search-settings/product \ | jq -c '.settings.types[] | select(.type == "product") | .typos' ``` </Tab> ## How changes go live | Change | Rollout mode | Visible in draft preview | | ----------------------------- | ----------------------------- | ------------------------ | | Reorder searched fields | **Settings** (within moments) | Once published | | Change typo thresholds | **Settings** (within moments) | Once published | | Add or remove searched fields | **Rebuild** (beside live) | Once published | | Change exempt attributes | **Rebuild** (beside live) | Once published | ## Customize | You want to | Do this | Default | | ---------------------------------- | --------------------------------------------------- | -------------------------------- | | Search a custom attribute | Add `attributes.<code>` to `search` in `types.json` | Derived from catalog text fields | | Turn off typo tolerance completely | Set `typos.enabled: false` on the Type | Enabled (5 / 9 letters) | | Exempt an attribute from typos | Add its code to `no_typos` in `types.json` | Derived for unique identifiers | ## Next steps | You want to | Read | | ------------------------------------ | -------------------------------------------------- | | Map shopper words to catalog words | [Synonyms](/docs/search/synonyms) | | Understand text ranking and fallback | [Query understanding](/docs/search/query-understanding) | | Publish and inspect rollout modes | [Releases](/docs/search/releases) | # Catalog formats Supported catalog export formats (CSV, Excel, Google Merchant Center XML, JSON and OrbSearch JSON Lines) and row rejection rules. OrbSearch detects the format, delimiter and character encoding of your shop's export from its leading bytes. Any supported format may arrive gzipped, up to **2 GB** unpacked. ## Supported formats | Format | Detected by | Details | | -------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------- | | Excel (`.xlsx`) | ZIP header | Reads the first sheet (or `feed.json` sheet name); detects header rows automatically. Legacy `.xls` is not supported. | | Merchant Center XML | Leading `<` | RSS 2.0 `<item>` or Atom `<entry>`; `g:price` maps as column `price`. | | JSON array | Leading `[` | Arbitrary array of objects; nested keys flatten to columns like `dimensions.width`. | | OrbSearch JSON Lines | Leading `{` | One native entity object per line; requires no `feed.json` column mapping. | | CSV, TSV, TXT | Fallback bytes | Comma, semicolon, tab or pipe delimiter (from first 50 rows); UTF-8, UTF-16 or Windows-1252. | Inspect how OrbSearch recognises any file without touching live search: ```sh for file in export.csv export.xlsx export.xml; do draft=$(curl -s -X POST -H "Authorization: Bearer $key" -H 'Content-Type: application/octet-stream' \ --data-binary @tests/fixtures/feeds/home/$file "$api/imports?name=$file" | jq -r .import.id) curl -s -H "Authorization: Bearer $key" $api/imports/$draft/inspection | jq -c '{format: .feed.format, products}' curl -s -X DELETE -H "Authorization: Bearer $key" $api/imports/$draft >/dev/null done ``` ### Pin a format when auto-detection guesses wrong If you send non-OrbSearch JSON objects one per line (starting with `{`), pin `"kind": "json"` in `feed.json` so they are mapped as generic JSON instead of OrbSearch JSON Lines: ```json title="feed.json" { "format": { "kind": "json" } } ``` ## OrbSearch JSON Lines OrbSearch's native NDJSON format holds one [Entity](/docs/search/types-and-attributes) per line (category, product, content, brand or custom type) and needs no mapping: ```json title="catalog.jsonl (three lines, formatted)" {"type":"category","id":"wohnen/sofas","parent":"wohnen","title":{"de":"Sofas","en":"Sofas"},"path":{"de":"/wohnen/sofas","en":"/en/living/sofas"}} {"type":"product","id":"SOFA-ASKA-2","title":{"de":"Aska 2-Sitzer-Sofa aus Samt","en":"Aska two-seater velvet sofa"},"brand":"Halvard","categories":["wohnen/sofas"],"attributes":{"width":"164 cm","upholstery":"Samt"},"varies_by":["color"],"variants":[{"id":"SOFA-ASKA-2-GRAU","attributes":{"color":"Grau"},"price":749.0,"currency":"EUR","availability":"in_stock"},{"id":"SOFA-ASKA-2-SALBEI","attributes":{"color":"Salbei"},"price":749.0,"sale_price":649.0,"currency":"EUR","availability":"in_stock"}]} {"type":"content","id":"guide-samt-pflege","kind":"guide","title":"Samt richtig pflegen","url":"/ratgeber/samt-pflege","body":"Saugen Sie Samt mit einer weichen Bürste in Strichrichtung ab."} ``` Plain strings default to the first locale of your first channel; locale maps (`{ "de": ..., "en": ... }`) supply translations. [OrbCatalog](/docs/catalog) serves this native NDJSON feed automatically at `/feeds/orbsearch.ndjson` ([Connect the products](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog)). ## How broken rows and values are handled - **Broken structural field** (for example a price written as `"249,00 €"` in JSON Lines or `"ab 249 €"` in CSV): that row (and its variants if in one JSON line) is rejected and logged in the [Import report](/docs/search/import-report); every other row still goes live. - **Invalid attribute value** (such as a width written in `kg`): only that attribute value is dropped, while the product remains live. <Callout type="warn"> If zero rows in an export can be indexed, the entire Index run fails and live search keeps the previous catalog untouched. </Callout> ## Customize | You want to | Do this | Default | | ------------------------------------ | -------------------------------------------------------------- | -------------------------------- | | Select a specific Excel worksheet | Set `format.sheet` in `feed.json` | First worksheet | | Override CSV delimiter or encoding | Set `format` options in `feed.json` | Auto-detected from leading bytes | | Map custom export columns and values | Edit `columns` in `feed.json` ([Importing](/docs/search/importing)) | Auto-mapped from headers/values | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------------- | | Inspect and map export columns | [Importing and mapping](/docs/search/importing) | | Read rejected rows and reasons | [Import reports](/docs/search/import-report) | | Pull exports from a URL automatically | [Scheduled feeds](/docs/search/feeds) | | Define Types and attribute parsing | [Types and attributes](/docs/search/types-and-attributes) | # HTTP API Call OrbSearch's Query, Management and Operator HTTP APIs directly, with authentication, conventions and generated OpenAPI 3.1 endpoint tables. OrbSearch exposes three public HTTP API surfaces described in one OpenAPI 3.1 document at <a href="/docs/openapi/search.json">`/openapi/search.json`</a>. | Surface | Default local base URL | Authentication | Used by | | -------------- | ------------------------------ | ------------------------------------- | -------------------------------------- | | Query API | `http://127.0.0.1:7800` | None (public, CORS-open) | Storefronts, browsers, search agents | | Management API | `http://127.0.0.1:8000/api/v1` | Shop Bearer key or Admin staff token | Scripts, CI, OrbCommerce Admin, agents | | Operator API | `http://127.0.0.1:8000/api/v1` | Installation `ORBSEARCH_OPERATOR_KEY` | Multi-shop hosting and provisioning | ## Conventions and authentication - **JSON in, JSON out:** payloads use `application/json` (except raw catalog uploads and `POST /v1/events` beacons); errors return `application/problem+json` ([Errors and limits](/docs/search/errors-and-limits)). Absent fields are omitted rather than `null`. - **Timestamps and IDs:** timestamps use RFC 3339 with offsets. Release IDs and Snapshot IDs are content-addressed hashes; entity references follow `type:id` (such as `product:SOFA-ASKA-2`). - **List pagination:** `GET /api/v1/imports`, `/releases`, `/publishes` and `/index-runs` return newest first (`per_page` defaults to `15`, max `100`, with `data`, `links` and `meta`). - **Shop keys vs Admin staff tokens:** pass `Authorization: Bearer <key>` for scripts, or short-lived EdDSA staff JWTs (`aud: "orbcommerce-staff"`, 15 min) from a trusted OrbCommerce Admin (`roles.search`: `view` for reads/previews, `edit` for writes). - **Internal routes:** `/internal/*` endpoints in OpenAPI are private between the control plane and node (`ORBSEARCH_NODE_KEY`). ## Query API Public, read-only endpoints for search, product pages, URL routing, sitemaps, health checks and browser click/view events. | Method | Path | What it does | | --- | --- | --- | | `GET` | `/health` | Whether the Query API is up | | `GET` | `/ready` | Whether this node serves searches, and what it serves | | `POST` | `/v1/search` | Search, browse a category or complete a query | | `GET` | `/v1/search` | Search with the request in the URL | | `POST` | `/v1/card` | Resolve one known listing option | | `GET` | `/v1/product` | One product as its page shows it | | `GET` | `/v1/resolve` | What page one of the merchant's URLs is | | `GET` | `/v1/robots` | The robots.txt lines that keep crawlers off filter states | | `GET` | `/v1/sitemap` | The listing pages search engines may index, for the sitemap | | `POST` | `/v1/events` | Report clicks on and views of an answer's hits and banners | ## Management API Authenticated per-shop routes for catalog ingestion, drafts, merchandising, releases, previews and insights. ### Catalog, feeds and live pushes | Method | Path | What it does | | --- | --- | --- | | `PUT` | `/api/v1/catalog` | Replace the catalog | | `GET` | `/api/v1/catalog-source` | Show the feed the catalog is fetched from, with its latest fetches | | `PUT` | `/api/v1/catalog-source` | Fetch the catalog from a feed URL on a schedule | | `DELETE` | `/api/v1/catalog-source` | Stop fetching the catalog from its feed URL | | `POST` | `/api/v1/catalog-source/fetch` | Fetch the catalog source now | | `PUT` | `/api/v1/offers` | Change prices and stock without sending the catalog | | `PUT` | `/api/v1/products` | Change or remove products without sending the catalog | | `GET` | `/api/v1/categories` | Show the category tree of what is live | ### Imports and working drafts | Method | Path | What it does | | --- | --- | --- | | `GET` | `/api/v1/imports` | List the imports, newest first | | `POST` | `/api/v1/imports` | Start an import: keep an export without making it live | | `GET` | `/api/v1/imports/{import}` | Show an import with its files and its run | | `PATCH` | `/api/v1/imports/{import}` | Change the release files an import is read with | | `DELETE` | `/api/v1/imports/{import}` | Discard an import that has not gone live | | `GET` | `/api/v1/imports/{import}/inspection` | Show what the import makes of its export | | `GET` | `/api/v1/imports/{import}/suggestions` | Show where a decision model would send the export's columns | | `GET` | `/api/v1/imports/{import}/changes` | Show what making an import live changes | | `POST` | `/api/v1/imports/{import}/publish` | Make an import live, or go back to an earlier one | | `GET` | `/api/v1/imports/{import}/publication` | Show how publishing the import would go live, before it does | | `GET` | `/api/v1/imports/{import}/review` | Show what an import changes for shoppers: its entries, the top queries it answers differently and its tests | | `GET` | `/api/v1/drafts/working` | Show the draft that is open | | `POST` | `/api/v1/drafts` | Start a draft from what is live, or answer the one that is open | ### Rules, synonyms, settings, pages and media | Method | Path | What it does | | --- | --- | --- | | `GET` | `/api/v1/rules` | List the live rules in order, each with its state and its conflicts | | `GET` | `/api/v1/imports/{import}/rules` | List a draft's rules in order, each with its state and its conflicts | | `POST` | `/api/v1/imports/{import}/rules` | Add a rule to a draft | | `PATCH` | `/api/v1/imports/{import}/rules/{rule}` | Change one rule of a draft | | `DELETE` | `/api/v1/imports/{import}/rules/{rule}` | Remove one rule from a draft | | `PUT` | `/api/v1/imports/{import}/rules/{rule}/position` | Move one rule of a draft to another place in the order | | `GET` | `/api/v1/synonyms` | List the live synonyms of every language | | `GET` | `/api/v1/imports/{import}/synonyms` | List a draft's synonyms of every language | | `POST` | `/api/v1/imports/{import}/synonyms` | Add synonym entries to a draft, one or many at once | | `PATCH` | `/api/v1/imports/{import}/synonyms/{synonym}` | Change one synonym entry of a draft | | `DELETE` | `/api/v1/imports/{import}/synonyms/{synonym}` | Remove one synonym entry from a draft | | `POST` | `/api/v1/imports/{import}/synonyms/check` | Say what an entry's words find today and what adding it to a draft would clash with | | `POST` | `/api/v1/synonyms/check` | Say what an entry's words find today and what adding it to the live synonyms would clash with | | `GET` | `/api/v1/search-settings` | Show how each type is searched now: its fields, typo settings and exempt attributes | | `GET` | `/api/v1/imports/{import}/search-settings` | Show how each type of a draft is searched | | `PATCH` | `/api/v1/imports/{import}/search-settings/{type}` | Change how one type of a draft is searched | | `POST` | `/api/v1/media` | Upload an image for a banner and get its address | | `POST` | `/api/v1/pages/settings` | Show what a page shows and where each setting comes from | | `POST` | `/api/v1/imports/{import}/pages/settings` | Show what a page of a draft shows and where each setting comes from | | `PATCH` | `/api/v1/imports/{import}/pages/settings` | Change the facets or the sorting of one page of a draft | ### Releases, publish history and index runs | Method | Path | What it does | | --- | --- | --- | | `GET` | `/api/v1/releases` | List the releases, newest first | | `POST` | `/api/v1/releases` | Store a release | | `GET` | `/api/v1/releases/{release}` | Show a release with its files | | `POST` | `/api/v1/releases/{release}/publish` | Publish a release, or roll back to an earlier one | | `GET` | `/api/v1/releases/{release}/publication` | Show how publishing the release would go live, before it does | | `GET` | `/api/v1/publishes` | List who published what and why, newest first | | `GET` | `/api/v1/index-runs` | List the index runs, newest first | | `POST` | `/api/v1/index-runs` | Index the current catalog with the published release again | | `GET` | `/api/v1/index-runs/{index_run}` | Show an index run with its report | | `GET` | `/api/v1/live` | Show what searches read now | ### Previews and diagnostics | Method | Path | What it does | | --- | --- | --- | | `POST` | `/api/v1/preview/search` | Search as a shopper would, in any context and at any time, with the trace | | `POST` | `/api/v1/preview/page` | Open one of the shop's URLs as a shopper would, in any context and at any time | | `POST` | `/api/v1/preview/urls` | Show what a draft makes of the shop's URLs before it is published | | `POST` | `/api/v1/preview/compare` | Say why one hit of a preview sits above another | | `POST` | `/api/v1/preview/find` | Say why a product is not on a preview's page, or where it is | ### Insights and storage | Method | Path | What it does | | --- | --- | --- | | `GET` | `/api/v1/storage` | Show what the storage keeps and the disk it takes | | `PATCH` | `/api/v1/storage` | Change how many earlier catalogs are kept | | `GET` | `/api/v1/insights` | Show what shoppers searched and clicked, what found nothing and the filters they chose | | `GET` | `/api/v1/insights/campaigns` | Show the views and clicks of each sponsored products' campaign | ## Operator API Installation-wide multi-shop provisioning authenticated with `ORBSEARCH_OPERATOR_KEY` (never accepted on shop management routes). | Method | Path | What it does | | --- | --- | --- | | `GET` | `/api/v1/shops` | List the shops, oldest first | | `POST` | `/api/v1/shops` | Create a shop with its first secret key and its node's database role | | `GET` | `/api/v1/shops/{shop}` | Show a shop with its keys and people | | `PATCH` | `/api/v1/shops/{shop}` | Rename a shop, or set the admin whose staff works in it | | `DELETE` | `/api/v1/shops/{shop}` | Delete a shop and everything it owns | | `POST` | `/api/v1/shops/{shop}/keys` | Give a shop another secret key | | `DELETE` | `/api/v1/shops/{shop}/keys/{key}` | Revoke one of a shop's secret keys | | `GET` | `/api/v1/shops/{shop}/usage` | Show a shop's searches, entities and index runs per day | | `POST` | `/api/v1/shops/{shop}/users` | Let a person work in a shop | | `DELETE` | `/api/v1/shops/{shop}/users/{user}` | Take a person out of a shop | | `POST` | `/api/v1/shops/{shop}/users/{user}/login-link` | Make a link that signs a person in once and opens their shop | ## Generate typed clients from OpenAPI Download <a href="/docs/openapi/search.json">`/openapi/search.json`</a> (`contracts/openapi.json` in the OrbSearch repository) to generate clients in any language. Note two details when generating: 1. Point the generated client's base URL at your production proxy instead of the local Compose `servers` defaults. 2. Add the `Authorization: Bearer <key>` header on Management and Operator requests (the spec declares no security scheme). ## Next steps | You want to | Read | | ------------------------------------ | ---------------------------------------------- | | Look up error statuses and hard caps | [Errors and limits](/docs/search/errors-and-limits) | | Browse all 14 JSON release files | [Release files](/docs/search/release-files) | | Use the official TypeScript SDK | [TypeScript client](/docs/search/client) | | Configure multi-shop auth and TLS | [Self-hosting](/docs/search/self-hosting) | # Import reports Inspect what every Index run indexed, rejected or derived, and track run states from queued to succeeded or failed. Every [Index run](/docs/search/concepts#index-run) writes a structured report detailing accepted entities, rejected rows, dropped attribute values and every derived setting with its evidence. ## Read the latest run report <Tab value="Admin / Panel"> Open _Search → Releases_ and expand **Index runs** to view runs newest first with their state, indexed entity counts and rejected counts. Click **Report** on any run to inspect grouped rejections (row number, entity ID, column/pointer and reason). </Tab> <Tab value="API"> Fetch runs newest first with `GET /api/v1/index-runs` (or one run by ID at `GET /api/v1/index-runs/{index_run}`): ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs \ | jq -c '.data[0] | {state} + (.report | {rows, entities, rejected})' ``` </Tab> ## Inspect rejections, derived settings and ungrouped values ### Rejected rows and dropped values Row rejections are grouped by error `code` with up to 10 concrete examples each (naming `row`, `id`, `pointer` or `column` and `message`): ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs \ | jq -c '.data[0].report.rejections[] | {code, count}, (.examples[] | {row, id, pointer, message})' ``` Attribute values that fail parsing (while keeping their entity live) appear separately under `report.values.rejected`. ### Derived settings and new option values Whenever a Release omits a file (or parts of `categories.json` / `types.json`), the run explains each derived decision under `report.defaults.reasons`: ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs \ | jq -c '.data[0].report.defaults.reasons[] | {setting, file, reason}' ``` Option values present in your catalog but not listed in `attributes.json` appear under `report.values.derived` (with `ungrouped` counts for colours that matched no colour group automatically): ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs \ | jq -c '.data[0].report.values | {new, ungrouped}, (.derived[] | {attribute, label, groups})' ``` ## Index run states | State | Meaning | | ------------ | ----------------------------------------------------------------------------- | | `queued` | Waiting for the indexer to pick it up. | | `running` | Compiling indexes beside live ones (`progress` tracks completion). | | `succeeded` | Swapped live atomically; searches now read this Snapshot and Release. | | `failed` | Stopped with `error` explaining why; live search remains on the previous run. | | `superseded` | Replaced by a newer run before going live. | <Callout type="info"> A failed run never disrupts live search. The last `succeeded` run continues serving traffic until a valid run completes. </Callout> ## Customize | You want to | Do this | Default | | ---------------------------------- | ------------------------------------------------------------------------- | ------------------------------- | | Preview rejections before indexing | Create an [Import](/docs/search/importing) and check `/inspection` | Reported after indexing | | Assign groups to ungrouped colours | Declare them in `attributes.json` ([Types](/docs/search/types-and-attributes)) | Auto-grouped by colour words | | Trigger a manual rebuild | Call `POST /api/v1/index-runs` (or **Rebuild index**) | Runs on catalog/release publish | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------------- | | Fix column mappings before publishing | [Importing and mapping](/docs/search/importing) | | Define attribute labels and groups | [Types and attributes](/docs/search/types-and-attributes) | | Publish and roll back Releases | [Releases](/docs/search/releases) | # Importing and mapping Inspect an export in a draft, map custom columns and availability labels into feed.json, review diffs and publish safely. Uploading an export as an **Import** keeps it in a draft so you can inspect every column mapping, fix rejected values and compare product counts before anything goes live. ## Inspect an export and fix mappings Upload the export to `POST /api/v1/imports` and read its inspection: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" -H 'Content-Type: text/csv' \ --data-binary @tests/fixtures/feeds/home/export.csv "$api/imports?name=export.csv" | jq -r .import.id) curl -s -H "Authorization: Bearer $key" $api/imports/$draft/inspection | jq -c '{products, rejected}, (.rejections[], .values.rejections[] | {column, count, value: .examples[0].value})' ``` The inspection lists every column, where OrbSearch proposes to send it, why, and every row or value that failed to parse (for example `"in Kürze lieferbar"` in a stock column). <Tab value="Panel"> Open _Catalog → Imports_ and drop your file onto the page (or click **Choose a file**): 1. Review **Products**, **Variants**, **Categories**, **Rows** and **Problems** alongside live product tile previews. 2. Click a value problem (such as `"in Kürze lieferbar"`) and map it to **Backorder**. 3. Open an unmapped column (such as **Verkäufe 30 Tage**) and assign it to `sales_30d` under **Ranking signals**. 4. Click **Review and go live** to inspect **New**, **Gone** and **Staying** products, then **Go live** (or **Discard**). </Tab> <Tab value="API"> Take the inspection's proposed `mapping`, adjust the columns you want, write `feed.json` into the draft with its `version`, review diffs and publish: ```sh version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) curl -s -H "Authorization: Bearer $key" $api/imports/$draft/inspection \ | jq --arg version "$version" '{version: $version, files: {"feed.json": (.mapping | .columns.Lieferstatus = {to: "availability", values: {"in Kürze lieferbar": "backorder"}} | .columns["Verkäufe 30 Tage"] = "signals.sales_30d")}}' \ | curl -s -X PATCH -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft >/dev/null # Compare with live catalog before publishing curl -s -H "Authorization: Bearer $key" $api/imports/$draft/changes | jq -c '.products, .attributes' ``` Publish with `POST $api/imports/$draft/publish` (`{ "version": "..." }`), or discard with `DELETE $api/imports/$draft`. </Tab> ### Deletion safeguard If an Import removes **50 % or more** of your live products, publishing pauses until you confirm the exact removal count (`removing` in the publish body). ## Write `feed.json` explicitly Once `feed.json` is part of your Release, OrbSearch uses your exact column map and reports any new unmapped column rather than guessing: ```json title="feed.json" { "columns": { "Vater": "group", "Kategorie": { "to": "categories", "levels": " > " }, "Lieferstatus": { "to": "availability", "values": { "in Kürze lieferbar": "backorder" } }, "Breite (cm)": { "to": "attributes.width", "unit": "cm" }, "Name EN": { "to": "title", "locale": "en" }, "Verkäufe 30 Tage": "signals.sales_30d" } } ``` ### Optional AI column suggestions When `AI_GATEWAY_API_KEY` is configured in `.env`, the Query API asks `typesafe-ai/jev` via Vercel AI Gateway once per export using column names and sample rows. Suggestions at ≥ 98 % confidence fill guessed columns automatically; lower-confidence suggestions appear under **AI suggests** (`GET /api/v1/imports/{import}/suggestions`). Without the key, nothing leaves your server. ## Inspect locally from the CLI Inspect any local export against a folder of release files without running Docker: ```sh cargo run -p orbsearch -- feed inspect tests/fixtures/feeds/home/export.csv --release tests/fixtures/home ``` Pass `--write` to save the generated `feed.json`, or `--json` for machine-readable output. ## Automated direct upload (`PUT /api/v1/catalog`) CI jobs and scripts that already trust their export send it straight to `PUT /api/v1/catalog`, queueing an Index run against the published Release's `feed.json`: ```sh curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: text/csv' \ --data-binary @tests/fixtures/feeds/home/export.csv $api/catalog | jq -r .next ``` <Callout type="warn"> `PUT /api/v1/catalog` replaces the whole catalog immediately with no 50 % deletion guard. Use [Imports](/docs/search/importing) or [Scheduled feeds](/docs/search/feeds) when you want the deletion safeguard. </Callout> ## Customize | You want to | Do this | Default | | -------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------- | | Pull exports automatically from a URL | Configure a [Scheduled feed](/docs/search/feeds) | Manual upload or API push | | Fix bad product values permanently | Add `fill`/`set` rules in [Overlays](/docs/search/overlays) | Values imported as written | | Push price or product diffs in seconds | Use [Live prices](/docs/search/prices-and-stock) or [Live products](/docs/search/live-products) | Full catalog replace | ## Next steps | You want to | Read | | --------------------------------- | --------------------------------------- | | Read rejected rows after indexing | [Import reports](/docs/search/import-report) | | Fetch your export on a schedule | [Scheduled feeds](/docs/search/feeds) | | Check every supported file format | [Catalog formats](/docs/search/formats) | | Publish and roll back Releases | [Releases](/docs/search/releases) | # OrbSearch OrbSearch understands shopper queries, applies your merchandising rules and explains every result. What it does, what it leaves to you and where to start. OrbSearch is the search and discovery layer of a shop. Meilisearch handles retrieval; OrbSearch understands the query, applies your merchandising rules and explains every result. A search is a single unauthenticated call to the Query API (shown here against the engine's German example store): ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa' \ | jq -c '.resolution, [.sections[] | select(.type == "product") | .hits[].entity]' ``` `"Sofa"` resolves to the category `wohnen/sofas` and `"graues"` to the colour grey, returning only the matching grey sofas. Follow the [Quickstart](/docs/search/quickstart) to run this locally in minutes. ## What OrbSearch does - **Understands query intent.** Parses categories, units, option spellings and colour groups directly from your attributes (`"weiss"` matches `"Weiß"`). - **Explains every result.** Pass `debug=1` for a [step-by-step trace](/docs/search/search#the-trace) naming the exact Release and Snapshot that answered. - **Imports your existing exports.** Accepts CSV, Excel, Google Merchant Center XML or JSON and derives attributes, facets and sorting automatically ([Your own catalog](/docs/search/your-own-catalog)). - **Publishes configuration atomically.** Synonyms, rules and facets ship together as a [Release](/docs/search/releases); rolling back means publishing an earlier Release again. - **Groups results by entity type.** Returns separate sections for categories, products, content and brands, with category pages automatically including descendant products. - **Ships storefront packages.** `@orbsearch/react` (built on `@orbsearch/client`) provides the search box, listing pages, filters and product pages. ## What OrbSearch leaves to you | OrbSearch does not | Who handles it | | ------------------------------- | ------------------------------------------------------------------------------------------------ | | Decide checkout prices or stock | Your checkout, such as [OrbCart](/docs/cart). Search displays offers; checkout remains authoritative. | | Own product master data | Your shop's export or [OrbCatalog's](/docs/catalog) NDJSON feed. | | Track orders or conversions | Your analytics or checkout. Storefronts report [clicks and views](/docs/search/clicks-and-views). | | Host the search engine for you | You run one Docker Compose stack on your own server ([Self-hosting](/docs/search/self-hosting)). | See [Project status](/docs/search/status) for current limits. ## Change what you need Everything in OrbSearch adapts at three levels, from configuration to custom storefront components. [Extend OrbSearch](/docs/search/extend) maps every extension point. | Depth | You | Example | | --------- | --------------------------------------------- | --------------------------------------------------------------------------------------------- | | Configure | Edit drafts in the admin, panel or API. | [Synonyms](/docs/search/synonyms), [Rules](/docs/search/rules), [Pages and filters](/docs/search/pages). | | Compose | Restyle and arrange `@orbsearch/react` parts. | [Theming](/docs/search/theming) tokens, `data-slot` rules and custom `ProductTile` layouts. | | Replace | Swap any part with your own UI component. | [Custom facet renderers](/docs/search/extend#build-a-component-of-your-own) and your own `BuyBox`. | In the shared OrbCommerce Admin, _Search_ holds Insights, Synonyms, Rules, Search settings, Filters & sorting and Releases. ## With OrbCatalog OrbSearch works with any shop's export. When paired with [OrbCatalog](/docs/catalog), OrbSearch polls Catalog's NDJSON feed every 10 to 1,440 minutes while Catalog pushes price and sale updates in seconds. See [Connect the products](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog). ## Next steps | You want to | Read | | ------------------------- | --------------------------------------------- | | Try OrbSearch locally | [Quickstart](/docs/search/quickstart) | | Import your own export | [Your own catalog](/docs/search/your-own-catalog) | | Understand the engine | [Concepts](/docs/search/concepts) | | Build a search storefront | [Build a storefront](/docs/search/your-storefront) | | Look up every HTTP route | [HTTP API](/docs/search/http-api) | | Check current limits | [Project status](/docs/search/status) | # Insights Track top queries, zero-result searches, click-through rates, filter usage and sponsored campaigns from a privacy-first search log. Because every search passes through the Query API, Insights delivers your core metrics with zero extra storefront wiring: total searches, top queries, zero-result queries, filter adoption and response latencies. Adding [clicks and views](/docs/search/clicks-and-views) unlocks click-through, zero-click queries and sponsored campaign reports. ## Fetch search and campaign reports Read search metrics over any UTC date range (defaults to the last 30 days, `shopper` traffic, top 20 rows): ```sh curl -s -H "Authorization: Bearer $key" "$api/insights?from=2026-10-01&to=2026-10-09&limit=5" \ | jq '{searches, no_results, click_through, no_click, average_position, top: [.queries[].query]}' ``` Read sponsored campaign totals as JSON or download a brand-ready CSV with `Accept: text/csv`: ```sh curl -s -H "Authorization: Bearer $key" "$api/insights/campaigns?from=2026-10-01&to=2026-10-31" \ | jq '.campaigns[] | {campaign, served, views, click_through}' ``` In the OrbCommerce Admin or panel, _Search → Insights_ presents both **Searches** and **Campaigns** over today, 7, 30 or 90 days, with one-click shortcuts from zero-result rows to **Add a synonym**, start a **Rule** or inspect in the **Playground**. ## How metrics are defined The control plane rolls raw logs up once per minute into daily UTC summaries. Raw search and event partitions are retained for **60 days** and then dropped; daily roll-ups stay indefinitely. | Metric | Definition | | ------------------ | ---------------------------------------------------------------------------------- | | `searches` | Page-1 searches with query text (category pages and autocomplete counted apart). | | `no_results` | Searches with zero hits and no redirect, as a share of `searches`. | | `click_through` | Searches drawing at least one click within 48 hours, as a share of `searches`. | | `no_click` | Searches that returned hits yet drew zero clicks (excludes redirects and 0 hits). | | `average_position` | Mean 1-based position of clicked hits in the listed section across pages. | | `took_ms` | Daily `p50`, `p95` and `p99` Query API response times on search pages. | | Campaign metrics | `served` (answers placing the ad), `views` (unique `query_id`s seen) and `clicks`. | Every report also includes `left_out` showing excluded bot/test/bench traffic, rare queries, masked PII queries, late or unmatched events, and any unrecorded rows if the log buffer ever overflowed. ## Off-path logging, bots and privacy ### Zero impact on search latency The Query API logs asynchronously after sending the response via an in-memory buffer of 10,000 rows, flushing up to 500 rows per second with an insert-only Postgres role. Previews and `count_only` calls are never logged. ### Personal data - **No cookies or device storage:** `@orbsearch/client` generates an in-memory `page_view` ID per page load. - **PII masking before insert:** emails (`linkify`) and international or channel-country phone numbers (`libphonenumber`) are replaced with `[email]` and `[phone]`, and masked queries never appear in reports. - **k-anonymity threshold:** a query's text appears in reports only once at least **two distinct page views** searched it on the same UTC day (and never if longer than 200 characters). ### Filtering bots, tests and benchmarks The Query API classifies known spiders via `uap-core` (forward the shopper's `User-Agent` when calling from a server). Pass `traffic: "test"` or `"bench"` on automated requests so shopper reports stay clean. ## Customize | You want to | Do this | Default | | ------------------------------------ | ------------------------------------------------------------------- | -------------------------------- | | Exclude automated tests from metrics | Pass `traffic: "test"` or `"bench"` to `createSearch()` | `"shopper"` | | Mask national phone numbers cleanly | List market ISO codes in `channels.json` `countries` | International phone formats only | | Turn off client event reporting | Pass `report: false` ([Clicks and views](/docs/search/clicks-and-views)) | Enabled in browsers | ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------------------ | | Wire click and view tracking | [Clicks and views](/docs/search/clicks-and-views) | | Set up sponsored product campaigns | [Sponsored products](/docs/search/sponsored-products) | | Fix zero-result queries with synonyms | [Synonyms](/docs/search/synonyms) | # Live product changes Push created, edited or discontinued products into live search within seconds via PUT /api/v1/products with monotonic sequences. When your shop or PIM knows exactly which products changed, push only those entities through `PUT /api/v1/products`. Updated and deleted items appear in live search within seconds without running a full catalog reindex. ## Push changed and removed entities Send complete entities (matching the [OrbSearch JSON Lines](/docs/search/formats#orbsearch-json-lines) schema) in `products` and removed IDs in `gone`, each with a monotonically increasing integer `sequence`: ```sh curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ $api/products -d '{ "products": [ { "type": "product", "id": "LEUCHTE-KUGEL", "sequence": 48211, "title": { "de": "Kugel Pendelleuchte, mundgeblasen" }, "categories": ["leuchten/pendelleuchten"], "varies_by": ["color"], "variants": [ { "id": "LEUCHTE-KUGEL-KLAR", "attributes": { "color": "Klarglas" }, "price": 149.0, "availability": "in_stock" } ] } ], "gone": [{ "id": "LEUCHTE-BOGEN", "sequence": 48212 }] }' ``` - Each entry returns a row status in order (kept or rejected with its catalog error code such as `unknown_type` or `unknown_channel`). - Kept changes advance the shared `revision` counter visible in `trace.live.changes` and `GET /api/v1/live`. - Non-product entities (such as categories) can also be pushed in `products`; push affected products too if their breadcrumbs or denormalised fields need updating. ## Sequence precedence rules Because webhooks and queues can deliver events out of order or twice, OrbSearch compares `sequence` per entity and always keeps the highest value: | Incoming event | Result | | --------------------------------------- | ------------------------------------------ | | Push with higher `sequence` than stored | Updates or deletes the entity. | | Push with equal or lower `sequence` | Ignored cleanly (still answered as kept). | | Catalog line without `sequence` | Loses to any push sent after that catalog. | | Newer catalog snapshot | Supersedes pushes sent before it started. | Offer updates sent **before** a product push are assumed to be reflected in the pushed entity; offer updates sent **after** layer on top. If a later Release removes an attribute referenced by a previously pushed product, that push is rejected during the new Release's Index run and falls back to the catalog's own line. ## Limits - **200 changes per call** (`products` and `gone` combined; `422` if larger). - **One write per second** (debounced together with `PUT /api/v1/offers`). - **Live catalog required first** (`409` before the first full catalog is live). - Every pushed item must include an integer `sequence`; items without one are rejected. ## Customize | You want to | Do this | Default | | ---------------------------------- | --------------------------------------------------------------------- | ------------------------ | | Update only prices or availability | Call `PUT /api/v1/offers` ([Live prices](/docs/search/prices-and-stock)) | Whole-entity replacement | | Replace the entire catalog at once | Upload via `PUT /api/v1/catalog` or a [Scheduled feed](/docs/search/feeds) | Incremental push | ## Next steps | You want to | Read | | --------------------------------- | ------------------------------------------------------- | | Push fast price and stock updates | [Live prices and stock](/docs/search/prices-and-stock) | | Check the entity JSON format | [Catalog formats](/docs/search/formats#orbsearch-json-lines) | | Schedule full catalog refreshes | [Scheduled feeds](/docs/search/feeds) | # No results Recover automatically when a query's detected filters match nothing, tell shoppers what was left out and fix gaps with synonyms. When a query resolves to a category or filters that match zero products (such as `"gelbes Sofa"` in a shop with no yellow sofas), OrbSearch relaxes detected constraints step by step instead of showing an empty page. ## See relaxation in action ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=gelbes%20Sofa' \ | jq -c '.relaxed, (.resolution | del(.left_out)), .resolution.left_out, [.sections[] | select(.type == "product") | .hits[].entity]' ``` `relaxed: true` signals that the search stepped back. `resolution.left_out` lists every constraint that was dropped, with localised labels so you can tell the shopper honestly what was omitted. ## The relaxation ladder Each step runs one additional Meilisearch query and stops as soon as hits appear: | Step | What it drops | What it searches | | ---- | ------------------------------- | ------------------------------------------------ | | 1 | Filters detected from the query | Keeps the detected category and leftover text. | | 2 | Detected category as well | Searches the full query text across the catalog. | A query that detected only a category jumps straight to step 2. Relaxed searches never trigger a page redirect. Inspect each step in the trace: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=rotes%20Regal%20Eiche&debug=1' \ | jq -c '(.trace.steps[] | select(.step == "relax")), [.sections[] | select(.type == "product") | .hits[].entity]' ``` ## Tell the shopper what was left out Build a clear notice from `resolution.left_out`: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=gelbes%20Sofa' \ | jq -r '.resolution.left_out[] | "without \(.label) \(.labels[])"' ``` `@orbsearch/react`'s `<ListingPage>` displays this notice automatically above the relaxed results. When nothing matches at all (such as `"Fahrrad"` in a furniture store), the response returns empty sections without `relaxed`, and `<NoResults>` or `<NoMatches>` offers concrete next steps (clearing filters, tips or department links). ## Close zero-result gaps over time Check _Insights → Found nothing_ in the admin or panel to see the queries returning zero results most often: - **Different word for something you sell** (like `"couch"` for `"sofa"`): add a [Synonym](/docs/search/synonyms). - **Measurement or condition phrase** (like `"bis 220 cm"`): add a [Pattern](/docs/search/patterns). - **Single-product vocabulary** (like `"Balkonteppich"` for one outdoor rug): add per-product `keywords` in [Overlays](/docs/search/overlays#five-things-an-overlay-can-do). ## Customize | You want to | Do this | Default | | --------------------------------------- | ---------------------------------------------------------- | -------------------------- | | Show recovery links on empty pages | Pass `departments`, `popular` and `tip` to `<ListingPage>` | Link back to all products | | Map zero-result terms to catalog words | Add entries in [Synonyms](/docs/search/synonyms) | Literal catalog vocabulary | | Redirect a zero-result query to a guide | Add a redirect [Rule](/docs/search/rules) | Empty sections | ## Next steps | You want to | Read | | ------------------------------------- | --------------------------------- | | Find your top zero-result queries | [Insights](/docs/search/insights) | | Teach OrbSearch shopper words | [Synonyms](/docs/search/synonyms) | | Teach OrbSearch measurement phrases | [Patterns](/docs/search/patterns) | | Style `<NoResults>` and `<NoMatches>` | [React components](/docs/search/react) | # Overlays Add badges, fill missing attributes, attach product keywords or hide items in overlays.json without modifying your catalog export. An **Overlay** in `overlays.json` enriches or corrects catalog data during indexing without touching your shop's export. Because overlays live in your [Release](/docs/search/releases), they survive every future catalog upload. ## Add product badges ```json title="overlays.json" { "overlays": [ { "id": "bestseller-sofa-aska-2", "target": { "type": "product", "id": "SOFA-ASKA-2" }, "badges": { "de": ["Bestseller"], "en": ["Best seller"] }, "note": "Top seller over the last 30 days" } ] } ``` Badges appear on `GET /v1/product` and on search hits when the Type's `result` includes `"badges"`: ```sh curl -s 'http://127.0.0.1:7800/v1/product?id=SOFA-ASKA-2&locale=en' | jq -c '.product | {id, badges}' ``` ## Five things an overlay can do Target either a single entity (`{ "type": "product", "id": "..." }`) or a filtered set (`{ "type": "product", "where": { ... } }`). | Field | Effect | Example | | ---------- | ------------------------------------------------------------------------ | -------------------------------------------- | | `badges` | Adds localised badges shown on tiles and product pages. | `{ "de": ["Neu"], "en": ["New"] }` | | `fill` | Writes attribute values only where the export left them empty. | `{ "attributes": { "room": "Wohnzimmer" } }` | | `set` | Overwrites export values (including variant values) on every run. | `{ "attributes": { "room": "Wohnzimmer" } }` | | `keywords` | Adds search terms to matching products alone (unlike global synonyms). | `{ "de": ["Balkonteppich"] }` | | `hide` | Removes matching entities from every channel, search and product lookup. | `true` | <Callout type="warn"> Prefer `fill` over `set` when your export is missing data. `set` keeps overwriting the export even after your PIM fixes the source value. </Callout> ## Expire an overlay automatically (`until`) Add an RFC 3339 `until` timestamp to expire a badge or override automatically; OrbSearch triggers a rebuild at that moment: ```json title="overlays.json (excerpt)" { "id": "neu-stuhl-riga", "target": { "type": "product", "id": "STUHL-RIGA" }, "badges": { "de": ["Neu"], "en": ["New"] }, "until": "2026-12-01T00:00:00+01:00" } ``` An overlay whose target leaves the catalog stays dormant and applies again if the product returns. ## How overlay changes go live Overlays modify compiled index documents, so any change to `overlays.json` rolls out via a background **Rebuild** while live search keeps answering ([Releases](/docs/search/releases#how-a-publish-goes-live)). ## Customize | You want to | Do this | Default | | --------------------------------------- | ------------------------------------------------------- | ------------------------------- | | Hide a product on specific queries only | Write a `hide` [Rule](/docs/search/rules) | Global hide across all channels | | Hide a product in one market only | Use `assortment` in [Channels](/docs/search/channels) | Hidden in every channel | | Add search terms across all products | Add a [Synonym](/docs/search/synonyms) instead of `keywords` | Per-target keywords only | ## Next steps | You want to | Read | | ---------------------------------- | ------------------------------------------ | | Hide or promote products per query | [Rules](/docs/search/rules) | | Fix column mappings at import time | [Importing and mapping](/docs/search/importing) | | Publish and inspect rebuild runs | [Releases](/docs/search/releases) | # Pages and filters Configure facets, displays, facet groups, sort orders and pinned category grids per page with category-tree inheritance. Sofa pages filter by width and seats; lamp pages filter by light source and colour temperature. `categories.json` configures every page's [Facets](/docs/search/facets) and [Sorting](/docs/search/sorting), with child categories inheriting from their nearest configured ancestor. ## Lay out pages in `categories.json` ```json title="categories.json" { "default": { "facets": ["category", { "field": "price", "display": "histogram" }, "style", "on_sale"] }, "nodes": [ { "category": "wohnen/sofas", "facets": [ "width", { "field": "seats", "kind": "list", "display": "buttons" }, "color", "upholstery", "price" ], "sort": { "default": "price_asc", "options": ["relevance", "price_asc", "price_desc"] } }, { "category": "leuchten", "facets": ["room", "light_source", "material", "color", "price"] } ] } ``` Inspect where any category's settings originate (`origin`): ```sh curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ -d '{"category": "leuchten/stehleuchten"}' $api/pages/settings \ | jq -c '.facets | .origin, [.facets[].field]' ``` `leuchten/stehleuchten` inherits facets from `leuchten`. Facets, facet groups, default sort and sort options each inherit independently, so overriding only `sort` keeps the parent's facets intact. Omitted parts of `categories.json` derive automatically from your catalog on every Index run (categories with 24+ products carrying distinct attributes get their own derived node). ## Configure facet kinds, displays and groups Pass either a bare field code (uses its `default` or natural kind) or an object specifying `kind`, `display`, `buckets` or `custom_display`: ```json title="categories.json (facet examples)" [ { "field": "seats", "kind": "list", "display": "buttons" }, { "field": "price", "display": "histogram" }, { "field": "color_temperature", "kind": "buckets", "buckets": [ { "to": 3300, "label": { "de": "Warmweiß", "en": "Warm white" } }, { "from": 3300, "to": 5300, "label": { "de": "Neutralweiß", "en": "Neutral white" } }, { "from": 5300, "label": { "de": "Tageslichtweiß", "en": "Daylight" } } ] } ] ``` Bundle related facets under a shared heading with `groups` (set `"display": "finder"` with `"display": "select"` facets to render side-by-side dropdowns): ```json title="categories.json (node excerpt)" { "category": "wohnen/sofas", "groups": [ { "group": "measures", "label": { "de": "Maße", "en": "Measures" }, "facets": ["width", "seat_height"] } ] } ``` ## Pin a category's top grid A category's pinned grid is a [Rule](/docs/search/rules) that pins up to 100 products when no search query is typed (`"query": { "empty": true }`): ```json title="rules.json" { "id": "grid-of-sofas", "description": "Grid of Sofas", "when": { "category": { "is": "wohnen/sofas" }, "query": { "empty": true } }, "then": { "pin": [ { "entity": "product:SOFA-NIKO-SCHLAF", "position": 1 }, { "entity": "product:SOFA-VIDAR-ECK", "position": 2 } ] } } ``` ## Edit a page's layout <Tab value="Admin / Panel"> Open _Search → Filters & sorting_ (or _Merchandising → Filters & sorting_), select the **Search page** or any category in the tree, and edit: - **Filters:** drag to reorder, click **Add a filter**, or open a filter's settings to pick its **Type**, **Look** and **Options**. - **Sorting:** set **Starts with** and the list under **Shoppers can choose**. - **Grid:** click **Pin a product** and drag tiles to arrange the category's opening positions. - **Inheritance:** click **Write my own** to fork inherited settings, or **Reset** to hand them back. </Tab> <Tab value="API"> Read a page's draft settings and `addable` fields with `POST $api/imports/$draft/pages/settings`, then update with `PATCH`: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ -d '{"category": "wohnen/sofas"}' $api/imports/$draft/pages/settings \ | jq '{version, category: "wohnen/sofas", facets: (["on_sale"] + [.settings.facets.facets[] | if .shown_as_default then .field else .shown end])}' \ | curl -s -X PATCH -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/pages/settings \ | jq -c '.settings.facets | .origin, [.facets[].field]' ``` Pass `null` for `facets` or `sort` to reset the category back to inheritance (omit `category` to edit `default`). </Tab> ## How page changes go live | Change | Rollout mode | | ----------------------------------------------------------------------- | ------------------------- | | Facet order, labels, groups, sorting, display styles (except histogram) | **Switch** (instant) | | New field/kind/buckets no other page counts, enabling price histogram | **Rebuild** (beside live) | ## Customize | You want to | Do this | Default | | -------------------------------------- | ------------------------------------------------------ | ------------------------------- | | Render a custom facet UI component | Set `custom_display` on the facet in `categories.json` | Built-in display for the kind | | Exclude a category from search engines | Set `"index": false` on its `categories.json` node | Indexable when non-empty | | Pin hero items on a category page | Use the category's Grid or a `query.empty` pin Rule | Sorted by category default sort | ## Next steps | You want to | Read | | ------------------------------------ | -------------------------------------- | | Read facets and filters in responses | [Facets and filters](/docs/search/facets) | | Place banners on category pages | [Banners and teasers](/docs/search/banners) | | Register custom facet displays | [Extend OrbSearch](/docs/search/extend) | | Publish and preview page layouts | [Releases](/docs/search/releases) | # Patterns Turn shopper phrases with numbers, units or conditions such as "bis 220 cm" into structured filters. A shopper searching `"Sofa bis 220 cm"` (sofa up to 220 cm) wants sofas that fit their wall. Patterns in `patterns.json` match phrases like these during [Query understanding](/docs/search/query-understanding) and convert them into structured filters. ## See a pattern resolve ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=Sofa%20bis%20220%20cm&debug=1' \ | jq -c '(.trace.steps[] | select(.step == "resolve") | .detections[] | select(.pattern) | {words, as, pattern}), [.sections[] | select(.type == "product") | .hits[].entity]' ``` The pattern `width-at-most` converts `"bis 220 cm"` into `{ "width": { "lte": 220 } }`, filtering out wider corner sofas automatically. ## Write a pattern in `patterns.json` `patterns.json` is edited via the Management API or Git (no admin form edits it): ```json title="patterns.json" { "patterns": [ { "id": "width-at-most", "phrases": { "de": ["bis {width} cm", "unter {width} cm", "{width} cm breit"], "en": ["up to {width} cm", "under {width} cm"] }, "captures": "at_most" } ] } ``` - **Placeholders** such as `{width}` capture numbers in the attribute's unit, or capture `price`, `delivery_days`, `rating`, or any option attribute by code, label or alias. - **`phrases`** maps each locale to a list of case-insensitive phrases (or takes a single list for all locales). - **`filter`** adds fixed fields alongside or without a placeholder, such as `"filter": { "shape": "round" }` on a diameter pattern or `"on_sale": true` for `"im Angebot"`. ### How `captures` builds filters | `captures` | Example phrase | Filter produced | | ------------------- | ------------------- | -------------------------------------------- | | `"exact"` (default) | `"3-sitzer"` | `{ "seats": 3 }` | | `"at_most"` | `"bis 220 cm"` | `{ "width": { "lte": 220 } }` | | `"at_least"` | `"ab 200 cm"` | `{ "width": { "gte": 200 } }` | | `{ "within": 5 }` | `"durchmesser 120"` | `{ "diameter": { "gte": 115, "lte": 125 } }` | ## Built-in patterns Two patterns are enabled automatically: - **`quantity`** reads any number with a unit (such as `"3000 Kelvin"`) and filters the single attribute measuring that unit. Bare numbers without a bound match within ±5 %. - **`price`** reads currency amounts (such as `"unter 1000 €"`) in the channel's currency. Bound words (`"bis"`, `"unter"`, `"under"`, `"between"`, `"from"`) ship for German and English. Add other languages under `built_in.amount_words`, or disable a built-in pattern with `"built_in": { "quantity": false }`: ```json title="patterns.json" { "built_in": { "amount_words": { "fr": { "at_most": ["moins de", "au maximum"], "at_least": ["à partir de", "plus de"], "between": ["entre"], "and": ["et"], "to": ["à"] } } } } ``` When phrases overlap, the longer phrase wins; on equal spans, your custom pattern beats a built-in one, and an exact option label or alias beats any pattern. ## Disambiguate shared units When several attributes share a unit (width, depth and height in `cm`), the built-in `quantity` pattern refuses to guess and records why under `resolve.kept`: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=Regal%2080%20cm&debug=1' \ | jq -rc '(.trace.steps[] | select(.step == "resolve") | .kept[].reason)' ``` Add an explicit pattern (for example `"{width} cm"` with `{ "within": 5 }`) to tell OrbSearch which attribute a bare centimetre value means in your shop. ## How pattern changes go live Only the Query API reads `patterns.json`. Publishing a draft that edits only `patterns.json` is an instant **Switch** with zero reindexing ([Releases](/docs/search/releases#how-a-publish-goes-live)). ## Customize | You want to | Do this | Default | | ---------------------------------------- | ------------------------------------------------------- | ---------------------------- | | Add bound words for another language | Set `built_in.amount_words.<locale>` in `patterns.json` | German and English built in | | Turn off automatic unit or price parsing | Set `"built_in": { "quantity": false, "price": false }` | Both enabled | | Match an attribute-only phrase | Omit placeholders and set `filter` on the pattern | Requires placeholder capture | ## Next steps | You want to | Read | | ----------------------------------- | ---------------------------------------------------- | | Map plain shopper synonyms | [Synonyms](/docs/search/synonyms) | | Inspect all resolution sources | [Query understanding](/docs/search/query-understanding) | | Declare units on attributes | [Types and attributes](/docs/search/types-and-attributes) | | Preview and publish `patterns.json` | [Releases](/docs/search/releases) | # Live prices and stock Push price, sale, unit price, delivery and availability updates into live search within seconds via PUT /api/v1/offers. Your full catalog may sync once an hour or once a night while prices and stock move all day. `PUT /api/v1/offers` patches offers directly into live indexes within seconds, without queueing a full Index run. ## Push an offer update Send one object per changing product (or variant) and channel. Only named fields are replaced; omitted fields stay untouched: ```sh changed=$(curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ $api/offers -d '{ "offers": [ { "product": "LEUCHTE-KUGEL", "variant": "LEUCHTE-KUGEL-KLAR", "channel": "de", "price": 129 }, { "product": "LEUCHTE-KUGEL", "variant": "LEUCHTE-KUGEL-RAUCH", "channel": "de", "sale_price": 139, "sale_window": { "from": "2026-11-27T00:00:00+01:00", "until": "2026-11-30T00:00:00+01:00" } }, { "product": "LEUCHTE-KUGEL", "variant": "LEUCHTE-KUGEL-KLAR", "channel": "de", "availability": "out_of_stock", "stock": 0 } ] }') revision=$(jq .revision <<< "$changed") jq -c '.rows[]' <<< "$changed" ``` - Every accepted batch increments `revision` (shared with [Live product changes](/docs/search/live-products)). - Products with variants must name `variant`; unknown products or missing variant IDs are rejected per row while valid rows still apply. - The indexer debounces bursts to **one write per second**, recompiles the affected documents and updates live indexes. - Every search and product trace reports the active revision under `trace.live.changes` (and `GET /api/v1/live`). ### Sales and unit prices - Pass `"end_sale": true` to end an active sale immediately. - A `sale_window` starting or ending automatically triggers a rebuild at the boundary. - For goods sold by weight, volume, length or area, send `unit_price` (for example `{ "price": 19.9, "per": "kg" }`) and `sale_unit_price` alongside prices. OrbSearch displays them verbatim and never calculates unit prices itself. - Checkout remains authoritative for final prices and stock ([OrbCart](/docs/cart)). ## Interaction with the next catalog upload | Event after `PUT /api/v1/offers` | What happens to the pushed offer | | --------------------------------------- | ------------------------------------------------------- | | Catalog upload that started before push | Push applies on top so in-flight uploads never regress. | | Identical catalog uploaded again | Push stays active. | | Release rebuild or publish | Push stays active. | | Newer catalog snapshot uploaded later | Newer catalog supersedes earlier offer pushes. | <Callout type="warn"> Always keep your scheduled catalog export up to date as well. Any new catalog snapshot replaces offer pushes recorded before it began. </Callout> ## Limits - **1,000 offers per call** (`422` if exceeded; chunk larger syncs into sequential calls of 1,000). - **Live catalog required first** (`409` if no catalog has gone live yet). - Catalog-wide derived statistics (dictionary counts and derived price buckets) refresh on the next Index run. ## Customize | You want to | Do this | Default | | ------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------ | | Push whole product additions/removals | Call `PUT /api/v1/products` ([Live products](/docs/search/live-products)) | Next full catalog upload | | Auto-push offers from OrbCatalog | Set `ORBSEARCH_URL` and `ORBSEARCH_KEY` ([Connect](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog)) | Feed poll only | | Display unit prices on React tiles | Include `unit_price` in `types.json` `result` | Included by default | ## Next steps | You want to | Read | | --------------------------------- | --------------------------------------------------------------------------------- | | Push changed or removed products | [Live product changes](/docs/search/live-products) | | Connect OrbCatalog instant pushes | [Connect the products](/docs/run/connect-the-products#connect-orbsearch-to-orbcatalog) | | Check write rate and batch limits | [Errors and limits](/docs/search/errors-and-limits) | # Product pages Fetch a single product by ID or URL with its variants, colour swatches, localised details, badges and alternates. `GET /v1/product` returns everything a product page renders: title, media, categories, offer summary, labelled details with units, badges, signals and variants. Offers and badges come from the same compiled index as listing tiles, so tiles and product pages never disagree. ## Fetch a product by ID ```sh curl -s 'http://127.0.0.1:7800/v1/product?id=SOFA-ASKA-2' \ | jq -c '.product | .title, .badges, .signals, .offer, (.details[] | select(.attribute == "width"))' ``` `product.offer` summarises the variants in the requested channel: it picks the lowest active price among variants with the best availability and sums stock across them. `details` follow the order in `types.json` and include localised labels and units (such as `Breite`, `164 cm`). ## Read variants and swatches Each variant carries the attributes that vary per SKU alongside its own offer: ```sh curl -s 'http://127.0.0.1:7800/v1/product?id=SOFA-ASKA-2' \ | jq -c '.product.variants[] | {id, details: [.details[] | {label, values, swatch}], offer: (.offer | {price, sale_price, stock} | del(..|nulls))}' ``` Single-value colour details carry the exact `swatch` used in the colour facet (either the value's own swatch or its colour group's). Attributes shared across every variant sold in the channel stay in `product.details`. ## Fetch by URL and read alternates Look up a product by its path in the matching locale to get `alternates` for language switchers and `hreflang`: ```sh curl -s 'http://127.0.0.1:7800/v1/product?url=/en/p/aska-two-seater-sofa&locale=en' \ | jq -c '.product | {id, title, url, alternates, badges}' ``` URLs match exactly as stored in the catalog: case differences or extra trailing slashes return `404`. For storefronts routing every path through `/v1/resolve`, a single call returns `product` along with `status`, `canonical` and `robots`: ```sh curl -s -G http://127.0.0.1:7800/v1/resolve --data-urlencode 'url=/p/aska-2-sitzer-sofa' \ | jq -c '{type, status, canonical, robots, product: .product.id}' ``` ## Missing products vs engine outages | Status | Meaning | Storefront action | | ------ | ---------------------------------------------------------- | --------------------------------------------------------- | | `404` | The channel does not sell a live product with that ID/URL. | Render your 404 page (`client.product()` returns `null`). | | `503` | No index run is live or Meilisearch is unreachable. | Return 503 so crawlers do not deindex live products. | ## Customize | You want to | Do this | Default | | -------------------------------------- | ----------------------------------------------------------- | --------------------------- | | Control which details appear and order | Edit `details` in `types.json` | All non-empty attributes | | Add badges without editing the export | Add an entry in [Overlays](/docs/search/overlays) | None | | Replace the buy box in React | Pass `buyBox` to `<ProductPage>` ([Extend](/docs/search/extend)) | Built-in `BuyBox` component | ## Next steps | You want to | Read | | ------------------------------------ | ---------------------------------- | | Route products and categories by URL | [URLs and redirects](/docs/search/urls) | | Configure variant axes and offers | [Variants](/docs/search/variants) | | Render `<ProductPage>` in React | [React components](/docs/search/react) | | Add badges or correct product data | [Overlays](/docs/search/overlays) | # Query understanding OrbSearch resolves categories, attributes, synonyms and numeric patterns from shopper queries before searching leftover words. When a shopper types `"graues Sofa bis 220 cm"` (grey sofa up to 220 cm), they are describing a filtered category, not five unrelated keywords. OrbSearch resolves structured intent first and searches only the words left over. One search passes through five stages in order. First, Resolve extracts categories, attributes, synonyms and numeric patterns from the query text. Second, Rules and Sort evaluate pins, boosts, buries, hides, redirects and sort order. Third, Search sends one query to Meilisearch. Fourth, Rank and Facets apply relevance, business scores and variant matching. If zero hits return on a resolved query, Relax drops detected filters and then the category before retrying. Finally, Answer returns sections, facets and the optional debug trace. ## Read what the query resolved Every search answer includes `resolution` with the detected `category`, `filters`, leftover `text` and whether the query resolved completely (`complete`): ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa%20bis%20220%20cm' \ | jq -c '.resolution, [.sections[] | select(.type == "product") | .hits[].entity]' ``` Here `"Sofa"` resolves to `wohnen/sofas`, `"graues"` to colour `grey` and `"bis 220 cm"` to `width <= 220`. Because no text remains, the answer returns only matching grey sofas up to 220 cm and includes a `redirect` to that filtered page ([URLs and redirects](/docs/search/urls)). ## Where detections come from Pass `debug=1` to see which dictionary entry matched each span of words: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa%20bis%20220%20cm&debug=1' \ | jq -c '.trace.steps[] | select(.step == "resolve") | .detections[] | {words, entry, pattern}' ``` OrbSearch draws detections from four sources: | Source | Example | Configured in | | ------------- | ------------------------------- | ---------------------------------------------- | | Catalog words | Category titles, brands, labels | Derived from your catalog (`detect_in_query`) | | Aliases | `"gray"` for `grey` | `values[].aliases` in `attributes.json` | | Synonyms | `"couch"` → `"sofa"` | [Synonyms](/docs/search/synonyms) (`synonyms.json`) | | Patterns | `"bis 220 cm"`, `"3-sitzer"` | [Patterns](/docs/search/patterns) (`patterns.json`) | Only attributes with `detect_in_query: true` match in queries. If a word matches two incompatible entries, it stays plain text and the trace explains why under `resolve.kept`. ## Let shoppers dismiss a detection If a shopper removes a query-detected filter chip, send it back in `dismissed` on `POST /v1/search`. Those words stay plain text instead of resolving again: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{ "query": "graues Sofa", "dismissed": [{ "field": "color", "value": "grey" }] }' \ | jq -c '.resolution' ``` Omit `value` (for example `{ "field": "width" }`) to dismiss every detection for that field. On URLs resolved via `/v1/resolve`, dismissed detections travel in `ignore` (such as `/suche?q=graues+Sofa&ignore=color:grey`). <Callout type="info"> Rule-applied filters belong to the merchant and cannot be dismissed. Shopper-chosen filters are removed from `filters` directly. </Callout> ## How leftover text matches Words that stay as text are matched rarest first. When no product contains every word, common words give way before rare ones: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=Lund%20Samt&debug=1' \ | jq -r '.trace.steps[] | select(.step == "rank") | .sections[] | select(.type == "product") | .hits[] | .entity, (.why[] | select(.because.kind == "text") | .sentence)' ``` No product matches both `"Lund"` (1 product) and `"Samt"` (3 products), so the search returns the Lund sofa instead of every velvet item. Products matching all words still rank ahead of partial matches. Secondary sections drop trailing words instead. ## Language support Your catalog's own titles, brands, labels and aliases resolve in every locale you provide: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=grey%20sofa%20up%20to%20220%20cm&locale=en' \ | jq -c '.resolution' ``` Built-in inflections, colour words and price/quantity bounds cover German and English. For other languages, add [Synonyms](/docs/search/synonyms) and `amount_words` in [Patterns](/docs/search/patterns#built-in-patterns). ## Customize | You want to | Do this | Default | | ---------------------------------- | ------------------------------------------------- | ----------------------------------------- | | Detect an attribute in queries | Set `detect_in_query: true` in `attributes.json` | Derived for colour, brand and key options | | Map shopper terms to catalog words | Add entries in [Synonyms](/docs/search/synonyms) | Catalog words and aliases only | | Parse custom measurement phrases | Add phrases in [Patterns](/docs/search/patterns) | Built-in `quantity` and `price` | | Force what a word resolves to | Write a [Rule](/docs/search/rules) with `then.resolve` | Dictionary resolution | ## Next steps | You want to | Read | | -------------------------------------- | -------------------------------------------- | | Handle resolved queries with zero hits | [No results](/docs/search/no-results) | | Teach OrbSearch shopper vocabulary | [Synonyms](/docs/search/synonyms) | | Turn phrases with numbers into filters | [Patterns](/docs/search/patterns) | | Control searched fields and typos | [Fields and typos](/docs/search/fields-and-typos) | # Quickstart Run OrbSearch locally with Docker Compose, load the example furniture store and inspect why a search returns what it returns. Go from a fresh clone of OrbSearch to a search that explains every decision. You need **Docker**, `make`, `curl` and [jq](https://jqlang.org), and every command runs from the OrbSearch repository root. The engine's example store sells furniture in German, so its queries are German: `"graues Sofa"` means grey sofa. ## Run the stack and search ### Start the stack ```sh make .env docker compose up --detach --wait ``` `make .env` copies `.env.example` and fills every empty secret. The first start builds the images from source and takes a few minutes. The Query API answers immediately, telling you nothing is indexed yet (`503`): ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa' | jq .detail ``` ### Save the management key Searching needs no key, while changing configuration or uploading a catalog does. A fresh stack starts with one shop whose first key sits in `.env`: ```sh key=$(sed -n 's/^ORBSEARCH_MANAGEMENT_KEY=//p' .env) api=http://127.0.0.1:8000/api/v1 ``` Other OrbSearch guides reuse `$key` and `$api`. ### Publish a Release A [Release](/docs/search/concepts#release) holds your search configuration as JSON files, one per area (such as `synonyms.json`). Store the example store's files and publish them: ```sh id=$(jq -n '{files: [inputs | {(input_filename | split("/") | last): .}] | add}' tests/fixtures/home/*.json \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- $api/releases \ | jq -r .id) curl -s -X POST -H "Authorization: Bearer $key" $api/releases/$id/publish | jq -r .next ``` The Release is now active and waits for a catalog before building indexes. ### Upload the catalog The example catalog holds products, categories and guides as JSON Lines. Upload it and wait for its [Index run](/docs/search/concepts#index-run) to finish: ```sh run=$(curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: application/x-ndjson' \ --data-binary @tests/fixtures/home/catalog.jsonl $api/catalog | jq -r .run.id) until curl -s -H "Authorization: Bearer $key" $api/index-runs/$run \ | jq -e '.state | IN("queued", "running") | not' >/dev/null; do sleep 1; done curl -s -H "Authorization: Bearer $key" $api/index-runs/$run \ | jq '{state, rejected: [.report.rejections[]?.examples[] | {id, message}]}' ``` The run leaves out one row on purpose: the rug `TEPPICH-SILO` writes a price as text. Every other product goes live. ### Run a search Search the store for `"graues Sofa"`: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa' \ | jq -c '.resolution, [.sections[] | select(.type == "product") | .hits[].entity]' ``` `"Sofa"` resolves to category `wohnen/sofas` and `"graues"` to colour `grey`. The answer lists only the two matching grey sofas. ### Read the trace Add `debug=1` to see why each product sits where it sits: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa&debug=1' \ | jq -r '.trace.steps[] | select(.step == "rank") | .sections[] | select(.type == "product") | .hits[0] | .entity, .why[].sentence' ``` Every [Trace](/docs/search/concepts#trace) records each step in order: query resolution, rules, sort, engine call, facet counts and ranking reasons. ### Open the panel Open `http://localhost:8000` and create the owner account: the first visitor becomes the owner. Its **Playground** shows any search or URL as shoppers see it, with ranking reasons beside each hit. ## Stop or reset the stack Stop the containers while keeping Postgres, snapshots and indexes: ```sh docker compose down ``` Delete all volumes to start again from an empty database: ```sh docker compose down --volumes ``` ## Troubleshooting ### A port is already in use `docker compose up` stops if another program holds ports `8000`, `7800`, `7700` or `5432`. Override the port in `.env` and start again: ```dotenv title=".env" CONTROL_PORT=8001 APP_URL=http://localhost:8001 ``` See [Environment variables](/docs/search/environment#networking-ports-and-versions) for every port variable. ### Search returns 503 or finds nothing Check the latest index runs to see whether a run failed or never started: ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs | jq -c '.data[] | {id, state, error}' ``` No run means either the Release is not published or no catalog has been uploaded yet. ## Next steps | You want to | Read | | ------------------------------------- | --------------------------------------------- | | Upload your shop's own CSV or XML | [Your own catalog](/docs/search/your-own-catalog) | | Understand Releases and Snapshots | [Concepts](/docs/search/concepts) | | Explore search parameters and answers | [Search and browse](/docs/search/search) | | Wire a React storefront | [Build a storefront](/docs/search/your-storefront) | # Ranking Combine catalog signals such as sales, ratings and freshness into a business score, tune boost strengths and order result sections. Text relevance comes first (more matched words, fewer typos, earlier searched fields), followed by any sort the shopper picked. Whenever hits tie (and on every category page with no query text), the **business score** configured in `ranking.json` decides the order. ## Configure business signals and weights ```json title="ranking.json" { "signals": [ { "code": "sales_30d", "direction": "higher_is_better", "normalize": "percentile" }, { "code": "rating", "direction": "higher_is_better", "normalize": { "damped": { "count_signal": "rating_count", "prior_count": 10 } } }, { "code": "released_at", "direction": "newer_is_better", "normalize": { "half_life_days": 180 } } ], "weights": { "product": { "sales_30d": 0.5, "rating": 0.3, "released_at": 0.2 } } } ``` | Normalisation | How it scores each product | | ---------------- | ------------------------------------------------------------------------------------------ | | `percentile` | Ranks products across the catalog from `0` to `1` (top seller approaches `1`). | | `damped` | Pulls ratings with few votes toward the catalog mean (`prior_count` sets the half-weight). | | `half_life_days` | Decays dates exponentially (newest items start near `1`, halving each `half_life_days`). | Products supply raw values under `signals` in your catalog export (or mapped via `feed.json`). Missing signals score `0`, except damped ratings with zero votes which take the catalog mean. ## Inspect why a product ranks where it does Pass `debug=1` to read every hit's raw signals and plain-English ranking reasons in the `rank` trace step: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas&debug=1' \ | jq -r '.trace.steps[] | select(.step == "rank") | .sections[] | select(.type == "product") | .hits[] | "\(.entity) " + ([.signals | sort_by(.signal)[] | "\(.signal) \(.value)"] | join(", "))' ``` In the Playground, click **Why here?** on any tile to read the same breakdown, or compare two positions directly with `POST /api/v1/preview/compare`. ## Tune boost and bury multipliers Rule `boost` and `bury` strengths map to score multipliers in `ranking.json`. These are the defaults: ```json title="ranking.json" { "strengths": { "boost": { "slight": 1.5, "medium": 2, "strong": 4 }, "bury": { "slight": 0.67, "medium": 0.5, "strong": 0.25 } } } ``` ## Order result sections `sections` in `ranking.json` sets the display order of entity types on search and autocomplete answers: ```json title="ranking.json" { "sections": ["category", "product", "content"] } ``` Any type omitted from `sections` follows in `types.json` order. Individual [Rules](/docs/search/rules) can override section order for specific queries (such as placing buying guides first when a query starts with `"wie"`). ## How ranking changes go live | Change in `ranking.json` | Rollout mode | | -------------------------------------- | ------------------------------------------------ | | `signals` or `weights` | **Rebuild** (new indexes built beside live ones) | | `strengths`, `sections` or sort labels | **Switch** (instant) | <Callout type="warn"> Because business scores are baked into compiled documents during indexing, new signal weights take effect once the draft publishes, not inside a preview. </Callout> ## Customize | You want to | Do this | Default | | ------------------------------------- | -------------------------------------------------------------------------- | ------------------------ | | Map an export column to a signal | Map it to `signals.<code>` in `feed.json` ([Importing](/docs/search/importing)) | Imported as an attribute | | Override ranking for specific queries | Write a pin, boost or bury [Rule](/docs/search/rules) | Global business score | | Add shopper-selectable sort orders | Declare `sorts` in `ranking.json` ([Sorting](/docs/search/sorting)) | `relevance` only | ## Next steps | You want to | Read | | ------------------------------------ | ------------------------------------------ | | Pin, boost or bury specific products | [Rules](/docs/search/rules) | | Define sort dropdown options | [Sorting](/docs/search/sorting) | | Map CSV columns to ranking signals | [Importing and mapping](/docs/search/importing) | | Publish ranking changes safely | [Releases](/docs/search/releases) | # React components Ready-to-use search box, listing pages, product pages, facet displays and composable primitives for React 19. `@orbsearch/react` provides accessible search, listing and product components for **React 19.3+** on top of `@orbsearch/client`. Start with `<ListingPage>` and `<ProductPage>`, then restyle or swap individual parts as your design grows. ## Render listings and product pages ```tsx title="app/page.tsx" import { createSearch, isListing, type PageResponse } from "@orbsearch/client"; import { ListingPage, ProductPage, StorefrontProvider, listingView } from "@orbsearch/react"; import type { ReactNode } from "react"; const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); export function Storefront({ children }: { children: ReactNode }) { return ( <StorefrontProvider search={search} locale="de"> {children} </StorefrontProvider> ); } export function Page({ page, path }: { page: PageResponse; path: string }) { if (isListing(page)) { return <ListingPage listing={listingView(page, { path, locale: "de" })} />; } if (page.product) { return ( <ProductPage product={page.product} trail={[{ title: page.product.title, href: path }]} /> ); } return null; } ``` ### Page-level props - **`ListingPage`** accepts `listing`, `filters` (`"bar"` default or `"sidebar"`), `tile`, `banner`, `sorts`, `sectionTitle`, `departments`, `tip` and `busy` (dim images while your router navigates). Enrich the view from `listingView()` with shop-specific `{ ...view, trail, categories, popular }`. - **`ProductPage`** accepts `product`, `trail`, optional `variant` (read via `variantAt(product, url)?.id`), `more` (related product rail) and custom `buyBox`. ### Optimistic choices on slow connections Every filter toggle, chip removal and sort choice updates UI state immediately and chains onto pending choices before the server responds. Pass your router's `navigate` to `StorefrontProvider` so newer navigations cancel older in-flight ones. ## Composable parts and hooks Every building block exports independently so you can assemble custom layouts: | Group | Exported components | | ------------ | -------------------------------------------------------------------------------------------------- | | Search box | `SearchBox`, `SuggestionItem`, `SuggestionText`, `SuggestionSponsoredLabel` | | Listing | `ListingToolbar`, `CategoryLinks`, `SectionLinks`, `AppliedFilters`, `SortSelect` | | Products | `ProductResults`, `ProductGrid`, `ProductTile`, `ProductRail`, `Banner` | | Filters | `FilterBar`, `FilterPanel`, `FilterSheet`, `FacetList`, `FacetFilter`, `GroupFilter`, `LateFacets` | | Empty states | `NoMatches`, `NoResults` | | Product page | `ProductGallery`, `BuyBox`, `ProductInfo`, `Breadcrumb`, `Price`, `Rating`, `ProductImage` | Hooks underneath: `useListing`, `useFacet`, `useFilters`, `useLiveFilters`, `useLoadWhenOpen`, `useTile`, `useReport` and `useAnnouncement`. `Price` displays unit prices (`data-slot="price-unit"`) automatically whenever `unit_price` is returned. ## Swap elements, mark ads and load late facets ### Change an element with `render` Override an underlying element or class name while preserving ARIA semantics using Base UI's `render` prop: ```tsx elements import { ProductTile } from "@orbsearch/react"; <ProductTile.Price render={(props) => <p {...props} className="shop-price" />} />; ``` ### Sponsored ad labels Sponsored hits automatically prefix their tile heading with `messages.sponsored` (`"Anzeige"` in German, `"Sponsored"` in English). Restyle or reposition the label while keeping ads clearly disclosed: ```tsx elements import { ProductTile } from "@orbsearch/react"; <ProductTile.Title label={<ProductTile.SponsoredLabel className="shop-ad" />} />; ``` ### Built-in facet displays `facetDisplays` maps display names (`list`, `stars`, `images`, `swatch`, `grades`, `buttons`, `select`, `range`, `slider`, `histogram`, `hierarchy`, `toggle`) and `groupDisplays` maps `finder`. Custom displays passed via `<StorefrontProvider displays={{ ... }}>` take precedence over built-ins ([Extend OrbSearch](/docs/search/extend#build-a-component-of-your-own)). ### Facets that load when opened Wrap custom facet lists in `<LateFacets>` so deferred facets (past the first 30) and truncated lists (past 50 values) fetch on demand when opened: ```tsx title="app/facets.tsx" import { FacetList, LateFacets, useListing, type ListingView } from "@orbsearch/react"; export function Facets({ listing }: { listing: ListingView }) { const page = useListing(listing); return ( <LateFacets request={{ ...page.count, filters: page.filters }}> <FacetList facets={listing.facets} value={page.value} onChange={page.apply} /> </LateFacets> ); } ``` ## Localised copy and responsive images German (`de`) and English copy are built in. Override strings via `messages` and wire responsive image widths via `images`: ```tsx title="app/storefront.tsx" import type { Search } from "@orbsearch/client"; import { messagesFor, StorefrontProvider, type ImageHost } from "@orbsearch/react"; import type { ReactNode } from "react"; const messages = { ...messagesFor("de"), searchPlaceholder: "Sofas, Teppiche, Leuchten" }; const images: ImageHost = { widths: [320, 640, 1024], url: (src, width) => `${src}?w=${width}` }; export function Storefront({ search, children }: { search: Search; children: ReactNode }) { return ( <StorefrontProvider search={search} locale="de" messages={messages} images={images}> {children} </StorefrontProvider> ); } ``` ## Customize | You want to | Do this | Default | | ------------------------------------ | --------------------------------------------------------------------------------- | ---------------------- | | Restyle colours, radii or typography | Override `--orb-*` tokens ([Theming](/docs/search/theming)) | Neutral WCAG AA theme | | Compose a custom product tile | Pass `tile={ShopTile}` built from `ProductTile.*` parts | Built-in `ProductTile` | | Own and modify the buy box source | Copy via shadcn registry ([Extend](/docs/search/extend#build-a-component-of-your-own)) | Built-in `BuyBox` | ## Next steps | You want to | Read | | ------------------------------------- | -------------------------------------- | | Step-by-step theming & custom parts | [Extend OrbSearch](/docs/search/extend) | | Copy standalone facet & sheet recipes | [Storefront recipes](/docs/search/recipes) | | Check WCAG 2.2 AA behaviour | [Accessibility](/docs/search/accessibility) | | Use the framework-free client | [TypeScript client](/docs/search/client) | # Storefront recipes Copyable React recipes for mounting a single FacetFilter, a mobile FilterSheet and a custom filter dialog with live counts. Complete, copyable components built on `@orbsearch/client` and `@orbsearch/react`. Each assumes `<StorefrontProvider>` from [Build a storefront](/docs/search/your-storefront) sits above it in your tree. ## Mount a single facet in your own layout Use `<FacetFilter>` with `withField()` to render one facet (such as `color`) anywhere on your page: ```tsx title="app/color-filter.tsx" import type { FacetResult } from "@orbsearch/client"; import { FacetFilter, withField, type Filters } from "@orbsearch/react"; type Props = { facets: readonly FacetResult[]; filters: Filters; apply: (filters: Filters) => void; }; export function ColorFilter({ facets, filters, apply }: Props) { const colors = facets.find((facet) => facet.field === "color"); if (colors === undefined) return null; return ( <FacetFilter facet={colors} value={filters.color} onChange={(color) => apply(withField(filters, "color", color))} /> ); } ``` `withField()` updates the field immutably and removes its key when cleared. If the facet specifies a `custom_display`, `<FacetFilter>` renders your registered display from `<StorefrontProvider displays={...}>`. ## Render filters in a mobile sheet `<ListingPage filters="sidebar" />` switches automatically from a desktop sidebar to a modal sheet below `64rem`. In a custom layout, mount `<FilterSheet>` directly with `useListing()`: ```tsx title="app/phone-filters.tsx" import { FilterSheet, useListing, type ListingView } from "@orbsearch/react"; export function PhoneFilters({ listing }: { listing: ListingView }) { const page = useListing(listing); return ( <FilterSheet facets={listing.facets} value={page.value} onApply={page.apply} total={listing.total} count={page.count} chosen={page.chosen} /> ); } ``` Inside the sheet, selections stage locally and update the "Show N results" count via `count_only` until the shopper confirms. `Escape` or closing discards pending edits. ## Build your own filter dialog with live counts When you already have a modal or drawer system, use `useFilters()` to stage pending filter changes and fetch live result counts automatically: ```tsx title="app/filter-dialog.tsx" import { FacetList, useFilters, useStorefront, type ListingState, type ListingView, } from "@orbsearch/react"; type Props = { listing: ListingView; page: ListingState; close: () => void }; export function FilterDialog({ listing, page, close }: Props) { const { messages } = useStorefront(); const filters = useFilters({ value: page.value, total: listing.total, count: page.count, onApply: page.apply, }); return ( <form onSubmit={(event) => { event.preventDefault(); filters.apply(); close(); }} > <FacetList facets={listing.facets} value={filters.pending} onChange={filters.change} /> <button type="submit" aria-busy={filters.counting}> {messages.filters.showResults(filters.total)} </button> </form> ); } ``` Call `filters.start()` whenever your dialog reopens to reset pending choices to the currently applied filters. ## Next steps | You want to | Read | | ------------------------------------ | ---------------------------------- | | Customise tokens, tiles and displays | [Extend OrbSearch](/docs/search/extend) | | Explore all React parts and hooks | [React components](/docs/search/react) | | Style controls and slots | [Theming](/docs/search/theming) | # Release files Reference of all fourteen optional JSON release files, their rollout impact, key fields and catalog entity schemas. An OrbSearch [Release](/docs/search/releases) holds up to fourteen optional JSON files. Omit any file you want OrbSearch to derive automatically from your catalog; write a file to own that area explicitly. ## The fourteen release files | File | Configures | Rollout mode | Guide | | ----------------- | --------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------- | | `types.json` | Entity types, searched fields, result fields, details, listing grain, typos | Settings / Rebuild | [Types and attributes](/docs/search/types-and-attributes) | | `attributes.json` | Attribute types, units, options, aliases, colour groups, slugs | Rebuild | [Types and attributes](/docs/search/types-and-attributes) | | `channels.json` | Markets, locales, currencies, phone-masking countries, assortments, context | Rebuild | [Channels](/docs/search/channels) | | `categories.json` | Default and per-category facets, displays, buckets, groups, sort orders | Switch / Rebuild | [Pages and filters](/docs/search/pages) | | `synonyms.json` | Per-locale `groups`, `one_way` entries and `never` edit guards | Settings | [Synonyms](/docs/search/synonyms) | | `patterns.json` | Custom query capture phrases, fixed filters and `amount_words` | Switch | [Patterns](/docs/search/patterns) | | `rules.json` | Pins, sponsored pins, boosts, buries, hides, filters, redirects, banners | Switch | [Rules](/docs/search/rules) | | `ranking.json` | Business signals, weights, boost/bury strengths, section order, sorts | Switch / Rebuild | [Ranking](/docs/search/ranking) | | `overlays.json` | Badges, `fill`/`set` attribute fixes, product keywords, global hides | Rebuild | [Overlays](/docs/search/overlays) | | `routes.json` | Search page paths, parameter names/aliases, filter pages, `min_products` | Switch / Rebuild | [URLs and redirects](/docs/search/urls) | | `redirects.json` | Exact and regex legacy redirects (`301`/`302`/`410`) and kept params | Switch | [URLs and redirects](/docs/search/urls#legacy-redirects-redirectsjson) | | `feed.json` | Export format pin, Excel sheet name and column-to-field mappings | Rebuild | [Importing and mapping](/docs/search/importing) | | `tests.json` | Automated search regression tests checked before publish | None (review only) | [Releases](/docs/search/releases#validation-and-search-tests) | | `relations.json` | Declared entity relations (validated on write; not read by search today) | Switch | [Project status](/docs/search/status) | ### Rollout mode notes - **`types.json`:** changing searched-field order or typo thresholds applies as **Settings**; adding/removing searched fields, exempt attributes or changing `listing` triggers a **Rebuild**. - **`categories.json`:** ordering, labels, groups, sorts and non-histogram displays apply via **Switch**; adding a new counted field/kind/buckets or enabling a price histogram triggers a **Rebuild**. - **`ranking.json`:** strengths, section order and sort labels apply via **Switch**; changing `signals` or `weights` triggers a **Rebuild**. - **`routes.json`:** changing `filter_pages.combinations` or `min_products` triggers a **Rebuild** to recount sitemap filter pages; other route edits apply via **Switch**. ## Catalog entity schema (`entity.json`) Native OrbSearch JSON Lines files and `PUT /api/v1/products` payloads follow `contracts/schema/entity.json`: | Field | Used on | Purpose | | ----------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `type`, `id` | Every entity | Entity type (matching `types.json`) and merchant ID (`type:id`). | | `title`, `url` | Every entity | Plain string or per-locale map (`{ "de": ..., "en": ... }`). | | `parent`, `path` | Categories | Parent category ID and localised category path. | | `categories`, `brand` | Products | Assigned category IDs and brand name/ID. | | `attributes` | Products / variants | Raw values parsed according to `attributes.json`. | | `varies_by`, `variants` | Products / services | Variant axes and SKU array (each with `id`, `attributes`, offer fields). | | `offers` | Multi-channel SKUs | Per-channel `{ channel, price, sale_price, sale_window, unit_price, availability, stock, delivery_days }`. | | `channels` | Unpriced entities | Explicit channel membership without offers ([Types](/docs/search/types-and-attributes#discoverable-without-a-price-channels)). | | `signals` | Ranked entities | Numeric/date signals read by `ranking.json` (`sales_30d`, `rating`, `released_at`). | | `sequence` | Live product pushes | Monotonic integer guarding out-of-order updates ([Live products](/docs/search/live-products)). | ## JSON Schemas for editor validation Every release file and catalog file has a generated JSON Schema in the OrbSearch repository under `contracts/schema/<name>.json`. Add `"$schema"` to any JSON file for live validation and completion in your editor: ```json title="synonyms.json" { "$schema": "../../../contracts/schema/synonyms.json", "synonyms": { "de": { "groups": [["sofa", "couch"]] } } } ``` OrbSearch preserves `$schema` keys verbatim when storing releases. ## Next steps | You want to | Read | | ------------------------------------ | ---------------------------------- | | Store, validate and publish Releases | [Releases](/docs/search/releases) | | Inspect supported catalog formats | [Catalog formats](/docs/search/formats) | | Check API routes and OpenAPI spec | [HTTP API](/docs/search/http-api) | # Releases Edit search configuration in a draft, preview and test changes, publish via Switch, Settings or Rebuild, and roll back in one call. A [Release](/docs/search/concepts#release) is an immutable, content-addressed bundle of up to fourteen JSON files defining your shop's search configuration. Every search answer names the exact `release` and `snapshot` that answered, matching `GET /api/v1/live`. Configuration edits start in a Draft created from the live catalog or a new export. Before publishing, OrbSearch validates every file and cross-reference, previews pages and runs saved queries and search tests. Publishing takes one of three paths depending on what changed: an instant Switch for Query API rules and layouts, a Settings update in moments for synonyms and typos, or a background Rebuild beside live indexes for catalog, attribute or signal changes. Once live, rolling back republishes any earlier Release ID. ## Store or inspect a Release Store a folder of JSON files as a Release without changing live search (`201` if new, `200` if identical files were already stored): ```sh jq -n '{files: [inputs | {(input_filename | split("/") | last): .}] | add}' tests/fixtures/home/*.json \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- $api/releases | jq -r .id ``` Every Release file is optional. Any omitted file (and omitted parts of `categories.json` or `types.json` `no_typos`) is derived automatically from your catalog during each Index run. See [Release files](/docs/search/release-files) for the full 14-file reference and JSON Schema `$schema` paths. ## Work in a draft Changes made in the admin, panel or API accumulate in a single working [Draft](/docs/search/concepts#draft) until you publish or discard it. <Tab value="Admin / Panel"> Your first edit on _Synonyms_, _Search settings_, _Filters & sorting_, _Banners_, _Rules_ or _URLs & SEO_ opens the working draft and displays the draft bar across every screen: - **Change count** summarises added, modified and removed entries against live search. - **Discard** drops the draft after confirmation. - **Review and publish** opens the diff, broken search tests, top-query impact and rollout mode before **Go live**. </Tab> <Tab value="API"> Start (or fetch) the working draft on the live catalog (`POST $api/drafts` or `GET $api/drafts/working`), patch files with optimistic locking (`version`), inspect the rollout plan and review impact, then publish or discard: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) # Inspect rollout mode and review impact before publishing curl -s -H "Authorization: Bearer $key" $api/imports/$draft/publication | jq -r .course.sentence curl -s -H "Authorization: Bearer $key" $api/imports/$draft/review | jq -c '{files: [.changes.files[].file], broken}' # Publish with the reviewed version (or DELETE $api/imports/$draft to discard) jq -n --arg version "$version" '{ version: $version }' \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/publish | jq -r .next ``` Sending a stale `version` returns `409` with the current draft so concurrent edits never silently overwrite each other. </Tab> ## Preview before publishing Preview any search or storefront URL against draft files (and at a future `time` for scheduled rules) with `POST /api/v1/preview/page` or `POST /api/v1/preview/search`: ```sh curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq '{url: "/wohnen/sofas", files}' \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- $api/preview/page \ | jq -r '.results.trace.steps[] | select(.step == "sort") | .reason' ``` <Callout type="warn"> Previews query the live Meilisearch indexes. Changes that modify compiled index documents or engine settings (new pins, typo rules, new attributes or ranking weights) show in the preview trace, while their hit movement appears once published. </Callout> ## How a publish goes live OrbSearch picks the smallest rollout mode your diff requires: | Mode | Triggered by | Speed & impact | | ------------ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | | **Switch** | Rules, page layouts, patterns, routes, redirects, sort labels, section order | Instant (sub-second on Query API). | | **Settings** | Synonyms, searched-field order, typo thresholds | Moments (applied to live engine). | | **Rebuild** | Catalog, searched fields, attributes, channels, overlays, `feed.json`, signals, new counted facets | Background rebuild beside live indexes; atomic swap. | A rebuild also runs automatically when a sale window or overlay `until` passes. ## Roll back and audit history Rolling back publishes an earlier Release against the current catalog using the same three rollout modes: ```sh previous=$(curl -s -H "Authorization: Bearer $key" $api/releases \ | jq -r '.data[] | select(.role == "previous") | .id') curl -s -X POST -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ -d '{ "reason": "Restore previous sofa pins" }' $api/releases/$previous/publish | jq -r .next ``` Every publish and rollback appends an immutable row to `GET /api/v1/publishes` naming `author` (panel user, OrbCommerce Admin staff name, named API key or scheduled fetch), `release_id`, `reason` (up to 500 characters) and `rollback`. To revert both configuration and catalog together, republish the earlier Import ([Importing and mapping](/docs/search/importing)). ## Validation and search tests Every write validates all schemas and cross-file references whole, returning `422` with exact `file`, `pointer` and `message` for each violation. Add regression assertions in `tests.json` describing expected redirects, resolved filters, applied rules, section order or top hits: ```json title="tests.json" { "tests": [ { "id": "three-seater-in-grey", "request": { "query": "3-sitzer grau" }, "expect": { "resolved": { "filters": { "color": "grey", "seats": 3 } } } } ] } ``` `GET /api/v1/imports/{import}/review` runs every test in the draft plus up to 50 top queries from the last 30 days. Publishing a draft that breaks a passing test requires a non-empty `reason` (in both the admin/panel and API). ## Customize | You want to | Do this | Default | | ------------------------------------- | ------------------------------------------------------------------ | ------------------------------ | | Keep configuration in Git | Download/commit JSON files and deploy via `POST /api/v1/releases` | Edited in admin/panel drafts | | Get editor autocomplete on JSON files | Add `"$schema"` pointing to `contracts/schema/<file>.json` | Plain JSON validation on write | | Guard key queries against regressions | Add assertions in `tests.json` (or **Keep as test** in Playground) | No tests | ## Next steps | You want to | Read | | ------------------------------------ | ------------------------------------------- | | Browse all 14 release files | [Release files](/docs/search/release-files) | | Read index run states and rejections | [Import reports](/docs/search/import-report) | | Check publish & review API routes | [HTTP API](/docs/search/http-api#management-api) | # Rules Pin, boost, bury, hide, filter or redirect search and category results in strict priority order, with schedules and trace explanations. A [Rule](/docs/search/concepts#rule) changes what a search or category page returns whenever its condition (`when`) holds. Rules live in `rules.json` in priority order: when two rules collide, the higher rule wins. ## Inspect live rules ```sh curl -s -H "Authorization: Bearer $key" $api/rules \ | jq -c '.rules[] | {id, state: .state.id, summary}' ``` Here is a rule that pins one sofa bed to position 1 on every search containing `"sofa"`: ```json title="rules.json" { "id": "niko-leads-every-sofa-search", "description": "Niko leads every sofa search", "when": { "query": { "contains": "sofa" } }, "then": { "pin": [{ "entity": "product:SOFA-NIKO-SCHLAF", "position": 1 }] } } ``` ## Available effects (`then`) | Effect | What it does | Example | | --------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | `pin` | Fixes an entity at a 1-based position (while it meets active filters). | `{ "entity": "product:SOFA-NIKO-SCHLAF", "position": 1 }` | | `boost` / `bury` | Weights matching products up or down (`slight`, `medium`, `strong`). | `{ "where": { "availability": "out_of_stock" }, "strength": "strong" }` | | `hide` | Removes entities from matching answers; always beats `pin`. | `{ "entity": "product:TEPPICH-MARE" }` | | `filter` | Narrows hits with `source: "rule"` (cannot be dismissed by shoppers). | `{ "where": { "availability": "in_stock" } }` | | `redirect` | Sends the shopper to an entity or URL; cannot mix with shaping effects. | `{ "to": "content:guide-samt-pflege" }` | | `place` | Places [banners and teasers](/docs/search/banners) in `top`, `grid` or `bottom`. | `{ "slot": "top", "banner": { ... } }` | | `resolve` / `rewrite` | Overrides query resolution or strips words before search runs. | Forces a word's meaning or drops noise words | | `sections` | Reorders result sections (for example putting guides above products). | `["content", "product", "category"]` | ## Conditions (`when`) and schedules All keys in `when` must match (omit `when` to match every request). Combine sub-conditions with `any`, `all` and `not` up to 3 levels deep. - **`query`**: `is`, `contains` (whole words), `starts_with` or `empty`. Matches typed words literally (`"couch"` does not trigger `"sofa"`). - **`category`**: `is` (exact category) or `within` (category and all descendants). - **`on`**: surface (`search`, `category_page`, `autocomplete`). - **`resolved`**, **`channel`**, **`locale`**, **`context`**: match resolved intent or market context. Add `schedule` to run a rule only inside a time window (`from` inclusive, `until` exclusive; either bound may be omitted): ```json title="rules.json (excerpt)" { "schedule": { "from": "2026-11-23T00:00:00+01:00", "until": "2026-11-30T00:00:00+01:00" } } ``` Live requests evaluate schedules against server arrival time. Pass `time` to `POST /api/v1/preview/page` or `/preview/search` to preview a future campaign before it starts. ## Rule precedence and conflicts Rules evaluate in three phases: `resolve`/`rewrite`, then the highest `redirect`, then shaping effects (`pin`, `boost`, `bury`, `hide`, `filter`, `place`, `sections`). | Collision | Winner | | ------------------------------------------------------ | ------------------------------------------------------------------- | | Two rules redirect, resolve one term or order sections | Higher rule wins. | | Two rules pin the same product or weight one target | Higher rule's position or strength wins. | | Two pins request the same slot | Higher rule takes it; lower rule shifts to the next free slot. | | A `hide` and a `pin` target the same product | `hide` always wins, regardless of order. | | A `redirect` and shaping rules | `redirect` ends planning; lower shaping rules report `not_applied`. | | Multiple `filter`, `hide` or `rewrite` effects | All apply together. | Inspect rule outcomes in any response's trace (`debug=1`): each rule reports `applied`, `partly_applied`, `not_applied`, `not_matched` or `inactive` with its exact reason. ## Add a rule <Tab value="Admin / Panel"> Open _Search → Rules_ (or _Merchandising → Rules_) and click **New rule**: 1. Set **Applies to** (for example searches containing `sofa`, or a category page). 2. Add one or more effects under **Then** (pin, boost, bury, hide, filter or redirect). 3. Optionally set **Starts** and **Ends** for a campaign window. 4. Click **Save** and drag handles to adjust priority; conflict badges highlight collisions immediately. 5. Click **Review and publish** in the draft bar. </Tab> <Tab value="API"> Create a rule at the top of a draft (or at a specific `position`) and preview it before publishing: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) jq -n --arg version "$version" '{version: $version, name: "Niko leads sofa searches", fields: { when: {trigger: {kind: "query", matching: "contains", phrases: ["sofa"]}}, then: {pin: [{entity: "product:SOFA-NIKO-SCHLAF", position: 1}]}}}' \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/rules \ | jq -c '.rules.rules[] | {id, state: .state.id, conflicts}' ``` Move a rule with `PUT $api/imports/$draft/rules/{rule}/position`. For conditions the form schema cannot express, write `rules.json` via `PATCH $api/imports/$draft`. </Tab> <Callout type="warn"> Previews query the live index. New or edited pins, boosts and buries appear in the preview trace immediately, but move product hits only after the draft publishes. Hides, filters, redirects and banners move hits in preview right away. </Callout> ## Limits A single request activates at most **4 boost/bury targets**, **100 pins**, **100 hidden IDs** and **96 engine rule keys** per section (excess rules are skipped in rule order and noted in the trace). Pins require a type listed one tile per product. See [Errors and limits](/docs/search/errors-and-limits) for every limit. ## Customize | You want to | Do this | Default | | ------------------------------------ | ----------------------------------------------------------------------- | -------------------------------- | | Sell a pinned slot to a brand | Add `sponsored: { campaign }` ([Sponsored](/docs/search/sponsored-products)) | Organic pin | | Place banners above or inside a grid | Use `then.place` ([Banners and teasers](/docs/search/banners)) | None | | Adjust boost/bury multipliers | Edit `strengths` in [Ranking](/docs/search/ranking) | `1.5× / 2× / 4×` and reciprocals | ## Next steps | You want to | Read | | --------------------------------- | ------------------------------------------------ | | Sell sponsored placements | [Sponsored products](/docs/search/sponsored-products) | | Place banners and teasers | [Banners and teasers](/docs/search/banners) | | Preview, test and publish rules | [Releases](/docs/search/releases) | | Check rule caps and engine limits | [Errors and limits](/docs/search/errors-and-limits) | # Search and browse Query search, category pages and autocomplete through one endpoint, with complete listing cards, pagination and traces. The Query API serves every search, category page and autocomplete box from `/v1/search` on port `7800`. No API key is needed, so browsers and storefront servers call it directly. ## Make a search request `GET /v1/search` accepts plain parameters in the URL: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa' \ | jq -c '[.sections[] | select(.type == "product") | .hits[].entity]' ``` Use `POST /v1/search` with a JSON body when you pass `filters`, `dismissed`, `facets` or `context`: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{ "query": "sofa", "filters": { "color": ["grey"] } }' \ | jq -c '.filters[] | {where, source}' ``` Set `on` to tell rules which surface made the call: `search` (default), `category_page` ([Category pages](/docs/search/category-pages)) or `autocomplete` ([Autocomplete](/docs/search/autocomplete)). ## Sections and hits An answer contains one [Section](/docs/search/concepts#section) per entity type, ordered by `ranking.json`. `listed` names the primary section: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa&per_page=2' \ | jq -c '.listed, (.sections[] | {type, total, hits: [.hits[].entity]})' ``` | Part | Behaviour | | ------------------ | --------------------------------------------------------------------------------------------------------- | | Listed section | Pages through results (`page`, `per_page`) and carries [Facets](/docs/search/facets). | | Secondary sections | Returned only when text was typed (`search` or `autocomplete`); up to 6 hits, unpaged. | | Each hit | Carries `entity`, optional matched `variant` and localised `fields` from `types.json`. | | Metadata | Names `release`, `snapshot`, `query_id` (for [events](/docs/search/clicks-and-views)) and optional `redirect`. | ## Complete listing cards Pass `cards: true` to receive a typed `card` on every listed hit without calling your catalog for extra product details: ```ts title="app/cards.ts" import { createSearch, listedSection } from "@orbsearch/client/server"; const search = createSearch({ endpoint: "http://127.0.0.1:7800" }); const answer = await search.query("sofa", { cards: true }); const cards = listedSection(answer)?.hits.flatMap((hit) => (hit.card ? [hit.card] : [])); const page = await search.resolve("/suche?q=sofa", { cards: true }); ``` `resolve()` returns the same cards in `page.results` alongside redirects, canonical URLs and robots headers (`results: false` skips search results). - **`card.item`** holds one representative's image, URL, variant and complete offer (price, unit price, separate refundable deposit and availability) in the request's channel. - **`card.previews`** holds up to four eligible variant groups (grouped by the first variation axis by default, or `previews` in `types.json`). An explicit variant `media: []` shows no image rather than borrowing another variant's photo. - **`card.choices`** counts all eligible buyable items before the four-preview cap. Only `selection.kind: "variant"` authorises direct add-to-cart for that exact variant; OrbCart still validates every purchase. Cards add one bounded engine round per displayed page, reported in the `cards` trace step. ## Pagination and totals `page` starts at `1` and `per_page` defaults to `24` (maximum `100`). Every section reports both `total` and `reachable`: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa&per_page=2&page=2' \ | jq -c '.sections[] | select(.type == "product") | {total, reachable, hits: [.hits[].entity]}' ``` `reachable` equals `total` up to `1,000`, the deepest hit pagination reaches. Variant filters and ranges are evaluated before tiles are counted and paged. <Callout type="warn"> Pages past `reachable` return no hits. Stop pagination at `reachable` and prompt shoppers to narrow with filters. </Callout> ## Count without hits Filter sheets with a "Show N results" button need only the total. Send `"count_only": true` to omit hits, secondary sections and unrequested facets: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{ "query": "sofa", "filters": { "color": ["grey"] }, "count_only": true }' \ | jq -c '.sections' ``` Include `facets: ["brand"]` alongside `count_only: true` to count specific facets on demand. ## Channel, locale and context Requests default to the Release's first [Channel](/docs/search/channels) and its first locale. Pass `channel`, `locale` and declared `context` keys to switch markets or target rules: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=sofa&locale=en&per_page=2' \ | jq -c '[.sections[] | select(.type == "product") | .hits[].fields.title]' ``` Titles, facet labels, URLs and prices all follow the requested channel and locale. ## The trace Pass `debug=1` (or `"debug": true`) to inspect every stage of the request in order: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa&debug=1' \ | jq -c '[.trace.steps[].step]' ``` The trace records query resolution, rule evaluation, sort choice, Meilisearch queries, facet counting, ranking reasons, optional card resolution and any relaxation steps. `timings` reports total Query API duration and Meilisearch's share. ## Troubleshooting | Status | Cause | Fix | | ------ | ------------------------------------------------------------ | --------------------------------------------------------- | | `400` | Unknown `sort`, `channel`, `locale`, filter field or context | Read `violations[].pointer` and send only declared codes. | | `503` | No live index run yet, or Meilisearch is unreachable | Publish a Release with a catalog, or check `GET /ready`. | An unknown `category` on `/v1/search` is not an error: it returns an empty product section. ## Customize | You want to | Do this | Default | | ----------------------------------- | ---------------------------------------------- | ---------------------------------- | | Change default returned fields | Edit `result` in `types.json` | Built-in title, URL, image, prices | | Reorder sections in search answers | Set `sections` in `ranking.json` or via a Rule | `types.json` declaration order | | Group card previews on another axis | Set `previews` in `types.json` | First declared variation axis | | Add custom rule targeting keys | Declare `context` values in `channels.json` | None declared | ## Next steps | You want to | Read | | ---------------------------------- | -------------------------------------------------- | | See how queries resolve to filters | [Query understanding](/docs/search/query-understanding) | | Filter and count facets | [Facets and filters](/docs/search/facets) | | Call the API from TypeScript | [TypeScript client](/docs/search/client) | | Check all Query API routes | [HTTP API](/docs/search/http-api#query-api) | # Self-hosting Deploy OrbSearch in production with Docker Compose, TLS, multi-shop nodes, OrbCommerce Admin trust, R2 storage, backups and zero-downtime upgrades. OrbSearch runs as a single Docker Compose stack (`compose.yaml` at the root of the OrbSearch repository) configured via one `.env` file behind your TLS reverse proxy. ## Services in the stack | Service | Image | Host port (default) | Volume | Role | | ------------- | --------------------------------- | ------------------- | -------------------- | ----------------------------------------------------------------------- | | `orbsearch` | `ghcr.io/xreal/orbsearch` | `127.0.0.1:7800` | `node` | Query API (`orbsearch serve`), called by storefronts and control plane. | | `indexer` | `ghcr.io/xreal/orbsearch` | None | `node` | Compiles Snapshots and Releases into Meilisearch (`orbsearch index`). | | `control` | `ghcr.io/xreal/orbsearch-control` | `127.0.0.1:8000` | `snapshots`, `media` | Control plane: Management API, panel and scheduled feed fetcher. | | `postgres` | `postgres:18.6-trixie` | `127.0.0.1:5432` | `postgres` | Shops, users, releases, imports, runs and search logs. | | `roles` | `postgres:18.6-trixie` | None | None | One-shot ensuring role `control` has `CREATEROLE`. | | `meilisearch` | `getmeili/meilisearch:v1.56.1` | `127.0.0.1:7700` | `meilisearch` | Disposable compiled search indexes only. | ## Start or run a released version ### Generate `.env` ```sh make .env ``` Copies `.env.example` to `.env` and fills every empty secret (`APP_KEY`, database passwords, Meilisearch keys, `ORBSEARCH_MANAGEMENT_KEY` and `ORBSEARCH_NODE_KEY`). Re-run after upgrades to add new keys without altering existing values. ### Pull released images or build from source To pull pre-built amd64/arm64 images instead of compiling, check out the release tag, set `ORBSEARCH_VERSION=0.1.0` in `.env` (or `edge` for `main`), sign in to GHCR if images are still private, and start: ```sh git checkout v0.1.0 docker compose pull docker compose up --no-build --detach --wait ``` Without `ORBSEARCH_VERSION`, run `docker compose up --build --detach --wait`. ### Create the owner account before exposing the panel Open `http://localhost:8000` (via `ssh -L 8000:127.0.0.1:8000 <server>` on a remote host) and register the first account before pointing your public proxy at port `8000`. Sign-up closes automatically after the first account. <Callout type="warn"> Docker Compose names its volumes after the checkout folder. Renaming the folder creates empty volumes. </Callout> ## TLS, proxy and security Put Caddy or nginx in front of `127.0.0.1:7800` (public Query API, e.g. `https://search.example.com`) and `127.0.0.1:8000` (panel and Management API, e.g. `https://panel.example.com`). Keep Postgres and Meilisearch bound to `127.0.0.1` only. - Set `APP_URL=https://panel.example.com` and list your proxy IPs in `TRUSTED_PROXIES` (never `*`). - **Rate-limit the Query API at the proxy:** storefront routes are unauthenticated and CORS-open. - **Node key isolation:** `/internal/*` endpoints on port `7800` require `Authorization: Bearer <ORBSEARCH_NODE_KEY>`. - **Least-privilege engine key:** only `indexer` holds `MEILI_MASTER_KEY`; `orbsearch` holds the search-only `MEILI_SEARCH_KEY` derived via HMAC. - **No CORS on Management API:** only scripts, agents and the panel call `/api/v1/*`. ## Multi-shop hosting and OrbCommerce Admin One control plane hosts multiple isolated shops (each in its own Postgres schema `shop_<slug>` with its own database role `<db>_shop_<slug>`). ### Manage shops via CLI or Operator API ```sh # Create a shop and print its secret key, node key and DB role password (shown once) docker compose exec control php artisan shops:create acme-tires "Acme Tires" \ http://orbsearch-acme-tires:7800 --member=you@agency.test # Rotate a shop's management key or node key, or update a moved node's address docker compose exec control php artisan shops:rotate-key shop docker compose exec control php artisan shops:rotate-node-key acme-tires docker compose exec control php artisan shops:address acme-tires https://search-acme.example.com ``` For automated provisioning, set `ORBSEARCH_OPERATOR_KEY` and call the [Operator API](/docs/search/http-api#operator-api) (`POST /api/v1/shops`, `/users`, `/login-link`, `/usage`, `DELETE /api/v1/shops/{shop}`). Leave `ORBSEARCH_MANAGEMENT_KEY` unset on operator-managed installations to disable default shop creation and public sign-up. Each additional shop needs its own node (`orbsearch`, `indexer`, `meilisearch`) with `ORBSEARCH_SHOP`, `ORBSEARCH_NODE`, `DATABASE_URL`, `ORBSEARCH_NODE_KEY`, `MEILISEARCH_URL`, `ORBSEARCH_CONTROL_PLANE_URL` and `ORBSEARCH_SNAPSHOT_CACHE` (see the `second-shop` profile in `compose.yaml`). ### Trust OrbCommerce Admin staff tokens A shop can accept short-lived EdDSA staff JWTs (`aud: "orbcommerce-staff"`, 15-minute TTL) from one OrbCommerce Admin instead of storing a static key: - Set `ORBSEARCH_STAFF_ISSUER` in `.env` before first migration for the default shop, or update any shop via `PATCH /api/v1/shops/{shop}` with `{ "staff_issuer": "https://admin.acme.example" }`. - The control plane verifies tokens against `<staff_issuer>/api/auth/jwks` (cached 10 minutes, auto-refreshed on unknown `kid`) and enforces `roles.search` (`view` vs `edit`, or `owner: true`). - For local dev where the admin runs on `http://localhost:8789`, proxy `http://localhost:8789` inside the `control` container to `host.docker.internal:8789` via `CADDY_EXTRA_CONFIG`. ## High availability: multiple node copies Run two or more copies of a shop's node (same `ORBSEARCH_SHOP`, `DATABASE_URL` and `ORBSEARCH_NODE_KEY`, unique `ORBSEARCH_NODE`, own `meilisearch` and volume; see `second-copy` in `compose.yaml`) behind a load balancer probing `GET /ready`. - **Synchronised publishes:** every live copy builds the run locally; the last copy to finish flips the run live so shoppers paging across copies never see mixed releases. A copy silent for 20 seconds is excluded automatically. - **Self-healing readiness:** `GET /ready` returns `200` only when the copy serves the live run, holds recent change revisions and Meilisearch answers; otherwise it returns `503` with `reasons` so the load balancer drains it automatically. If Meilisearch loses its volume, the running indexer detects and rebuilds it automatically. - **Rolling upgrades:** remove one copy from the load balancer, upgrade it, wait for `GET /ready` to return `200`, restore it, then move to the next copy. ### Postgres connections and memory - **Direct Postgres connections required:** nodes use `LISTEN/NOTIFY`, so connect directly (port `5432`, never transaction-pooled PgBouncer). Each node holds at most **7 connections** (3 Query API, 4 Indexer). - **Meilisearch memory:** set `MEILI_MAX_INDEXING_MEMORY` below your container memory limit (Meilisearch defaults to 2/3 of host RAM). ## Storage, media, backups and upgrades ### Data inventory and R2 object storage | Data | Default location | Back up? | Object storage option | | ------------ | ----------------- | -------- | --------------------------------------------------------------------------------------------------- | | Postgres DB | `postgres` volume | Yes | Managed Postgres (direct port for nodes) | | Snapshots | `snapshots` vol | Yes | `ORBSEARCH_SNAPSHOT_DISK=s3` + `AWS_*` (e.g. Cloudflare R2; 5-min signed downloads) | | Banner media | `media` volume | Yes | `ORBSEARCH_MEDIA_DISK=s3`, `ORBSEARCH_MEDIA_BUCKET`, `ORBSEARCH_MEDIA_URL` (separate public bucket) | | `.env` | Host filesystem | Yes | Secrets manager | | Meilisearch | `meilisearch` vol | No | Derived data; rebuilt from live Snapshot + Release | | Node cache | `node` volume | No | Local cache of fetched snapshots | Cleanup runs every 5 minutes, retaining live/active snapshots plus the newest `5` historical live snapshots (configurable via `PATCH /api/v1/storage` `{ "kept_snapshots": N }`) and dropping unreferenced media after 24 hours. ### Backup and restore Pause `control` briefly so cleanup cannot delete a snapshot mid-dump (live search continues uninterrupted): ```sh docker compose exec --no-TTY postgres pg_dumpall --username=postgres --roles-only > roles.sql docker compose stop control docker compose exec --no-TTY postgres pg_dump --username=postgres --format=custom orbsearch > orbsearch.dump docker compose cp control:/app/storage/app/snapshots/. ./snapshots docker compose cp control:/app/storage/app/media/. ./media docker compose start control ``` Restore `roles.sql` and `orbsearch.dump` into fresh volumes with the backed-up `.env`, copy `./snapshots` and `./media` into `control` (`chown -R www-data:www-data`), start the full stack, and rebuild Meilisearch with `POST $api/index-runs`. <Callout type="warn"> Never run `docker compose down --volumes` in production: it deletes `postgres`, `snapshots` and `media`. When upgrading Meilisearch across major versions, stop one copy, recreate only its `meilisearch` volume and let the indexer rebuild. </Callout> ## Next steps | You want to | Read | | -------------------------------------- | -------------------------------------------- | | Look up every `.env` variable | [Environment variables](/docs/search/environment) | | Inspect Operator and Management routes | [HTTP API](/docs/search/http-api) | | Check current hosting limits | [Project status](/docs/search/status) | # Sorting Render sort controls from the search response, apply a shopper's sort choice and configure default sort orders per category. Every listing response returns `sorts`, the exact list of sort options available on that page in the request's locale. ## Read and apply a sort order Fetch the available sorts for a category page: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas' | jq -c '.sorts[]' ``` Each entry carries a `code`, a localised `label`, and `default: true` on the page's starting order. Pass `sort` only when the shopper chooses something other than the default: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas&sort=price_asc' \ | jq -r '.sections[] | select(.type == "product") | .hits[] | "\(.entity) \(.fields.sale_price // .fields.price)"' ``` Price sorting compares what the shopper pays, so active sale prices take effect automatically. Leaving `sort` off URLs when the default is active avoids duplicate URLs. Sending an unknown sort code returns `400` listing valid codes. ## How a page picks its default sort | Situation | Starting sort order | | ----------------------- | --------------------------------------------------------------------------------------- | | Search with typed words | Always `relevance` unless the shopper picks another sort. | | Category page (no text) | Nearest `categories.json` node's `sort.default`, else `default.sort`, else `relevance`. | | Shopper chooses a sort | Shopper's `sort` parameter always wins. | Inspect why a response picked its sort in the `sort` trace step: ```sh curl -s 'http://127.0.0.1:7800/v1/search?on=category_page&category=wohnen/sofas&debug=1' \ | jq -r '.trace.steps[] | select(.step == "sort") | .reason' ``` ## Define sort orders in your Release `relevance` is built in. Define additional orders in `ranking.json` by field and direction: ```json title="ranking.json" { "sorts": [ { "code": "price_asc", "label": { "de": "Preis aufsteigend", "en": "Price: low to high" }, "by": "price", "direction": "asc" } ] } ``` Then choose which orders a page starts with and offers in `categories.json`: ```json title="categories.json" { "nodes": [ { "category": "wohnen/sofas", "sort": { "default": "price_asc", "options": ["relevance", "price_asc", "price_desc"] } } ] } ``` Every page's `sort.default` must appear inside its `sort.options`; drafts that omit it are rejected with `422`. Products missing a value for the sort field always appear after products that have one. ## Customize | You want to | Do this | Default | | --------------------------------- | --------------------------------------------------- | ---------------------------- | | Change a category's default sort | Set `sort.default` on its node in `categories.json` | Inherited, or `relevance` | | Add a new sort option | Define it under `sorts` in `ranking.json` | `relevance` only | | Override sorts in `<ListingPage>` | Pass the `sorts` prop on `@orbsearch/react` | Uses response's `sorts` list | ## Next steps | You want to | Read | | ----------------------------------- | ------------------------------------ | | Lay out category sorts in the admin | [Pages and filters](/docs/search/pages) | | Configure relevance business scores | [Ranking](/docs/search/ranking) | | Narrow listings with facets | [Facets and filters](/docs/search/facets) | # Sponsored products Sell pinned product placements to brands, label every ad cleanly on the storefront and export campaign view and click reports. A sponsored product is a [Rule](/docs/search/rules) pin tagged with a `campaign` name. A brand pays for a top slot over a schedule, OrbSearch marks the hit as sponsored, and Insights counts views and clicks per campaign. ## Define a sponsored pin ```json title="rules.json" { "id": "halvard-autumn", "description": "Halvard pays for position 1 in sofa searches", "when": { "query": { "contains": "sofa" } }, "then": { "pin": [ { "entity": "product:SOFA-VIDAR-ECK", "position": 1, "sponsored": { "campaign": "Halvard autumn" } } ] } } ``` The campaign name (up to 200 characters) groups views and clicks in the campaign report. Combine with `schedule` to start and end the campaign automatically. ## Label ads and report campaign events Every sponsored hit arrives with `sponsored: { "campaign": "Halvard autumn" }`. Your storefront must both disclose the ad clearly and include `campaign` in view/click events: - **`@orbsearch/react`** does both automatically: tile headings open with `"Anzeige"` or `"Sponsored"` (`messages.sponsored`), and event reporting includes `campaign`. - **Custom storefronts** must render an explicit ad label and call `search.report.click({ query_id, entity, position, campaign })` and `search.report.watch(...)` ([Clicks and views](/docs/search/clicks-and-views)). ## Add a sponsored product <Tab value="Admin / Panel"> 1. Open _Search → Rules_ and click **New rule**. 2. Set the trigger under **Applies to** (for example searches containing `sofa`). 3. Choose **Add an effect → Pin products** and pick the product. 4. Enable **Sponsored**, enter the campaign name, optionally set a schedule, then **Save** and **Publish**. </Tab> <Tab value="API"> ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) jq -n --arg version "$version" '{version: $version, id: "halvard-autumn", name: "Halvard pays for position 1 in sofa searches", fields: {when: {trigger: {kind: "query", matching: "contains", phrases: ["sofa"]}}, then: {pin: [{entity: "product:SOFA-VIDAR-ECK", position: 1, sponsored: {campaign: "Halvard autumn"}}]}}}' \ | curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/rules \ | jq -r '.rules.rules[0].summary' ``` Note that `sponsored` appears on live hits once published; draft previews query live indexes and show the pin in the trace only. </Tab> ## Precedence and safeguards - **Deduplicated:** a sponsored product appears once at its pinned slot and never repeats later in the grid. - **Filter-respecting:** a sponsored product shows only if it matches the page's category and all shopper/rule filters. - **Hide and higher unpaid pins win:** a `hide` removes it; a higher rule's unpaid pin of the same product takes the slot as an organic hit (no ad tag). - **Pin limit:** counts toward the 100-pin limit per section. Rules with sponsored pins never appear as category Grids. ## Export campaign reports Fetch campaign totals via `GET /api/v1/insights/campaigns` (or open _Search → Insights → Campaigns_ and click **Download CSV**): ```sh curl -s -H "Authorization: Bearer $key" -H 'Accept: text/csv' \ "$api/insights/campaigns?from=2026-10-01&to=2026-10-31" ``` The CSV includes `campaign`, `from`, `to`, `days`, `served`, `views`, `clicks` and `click_through` (leading formula characters are escaped automatically). ## Customize | You want to | Do this | Default | | ----------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------- | | Style or move the ad label in React | Style `[data-slot="tile-sponsored"]` or place `<ProductTile.SponsoredLabel />` | Inside `<ProductTile.Title>` | | Change the ad disclosure text | Override `messages.sponsored` on `StorefrontProvider` | `"Anzeige"` (`de`) / `"Sponsored"` | | Schedule campaign start and end | Add `schedule: { from, until }` on the rule | Active until disabled/removed | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------------- | | Read campaign metrics and attribution | [Insights](/docs/search/insights) | | Report views and clicks from code | [Clicks and views](/docs/search/clicks-and-views) | | Review rule conflict resolution | [Rules](/docs/search/rules#rule-precedence-and-conflicts) | # Project status What OrbSearch does today, its known pre-release limitations and its licensing. OrbSearch is pre-release and has not shipped its first public version yet. Every current limitation is listed plainly below so nothing surprises you in production. ## Hosting and packaging - **Pre-release packages and images:** `@orbsearch/client` and `@orbsearch/react` are not on npm yet (they live as TypeScript source in the workspace or vendored tarballs). Container images on GHCR are currently private; Compose builds from source by default. - **Single-node Compose default:** the default Compose stack runs one node for the first shop. Additional shops created via CLI or Operator API need their own node services (`orbsearch`, `indexer`, `meilisearch`) before they can serve queries ([Self-hosting](/docs/search/self-hosting#multi-shop-hosting-and-orbcommerce-admin)). - **No invitations or custom panel roles:** standalone panel sign-up creates only the owner; additional shops use `shops:create --member` or the Operator API. Role-based `view`/`edit` access works via OrbCommerce Admin staff tokens. - **Single-machine Postgres/control plane:** Compose runs one Postgres and one control plane without built-in replication; high-availability horizontal copies apply to search nodes ([Copies of a node](/docs/search/self-hosting#high-availability-multiple-node-copies)). - **Managed cloud:** a managed EU OrbSearch Cloud offering is planned for the future; today you self-host with Docker Compose. ## Admin and panel editing - **Supported in UI:** synonyms, searched fields & typos, per-page filters, sorting and category grids, rules, banners, import mapping, insights and releases. - **API / Git only:** `channels.json`, `attributes.json`, `ranking.json`, `patterns.json`, `routes.json`, `redirects.json`, `overlays.json`, `relations.json` and `tests.json` are managed via the Management API or Git ([Release files](/docs/search/release-files)). - **Complex rules in UI:** rules with conditions the form cannot express can still be renamed, toggled on/off or reordered in the UI, and edited in full via `rules.json`. ## Search, insights and APIs - **Built-in language knowledge:** catalog words resolve in any language, while built-in inflections, colour groups, price/quantity bounds and import heuristics ship for **German and English** only. Add missing terms via [Synonyms](/docs/search/synonyms) and `built_in.amount_words` in [Patterns](/docs/search/patterns). - **Validated but unused fields:** `categories.json` `where` smart-category selectors and `relations.json` are validated on store but not applied at query time; `synonyms.json` `never` guards edits only. - **Cross-channel counts:** autocomplete suggestions and `GET /v1/sitemap` category/brand counts aggregate across channels. - **Upper-bound facet counts:** multi-variant products under combined filters can produce `upper_bound: true` facet counts (hits themselves always evaluate variants strictly). - **Clicks and views only:** Insights tracks search queries, views and clicks (not cart adds or revenue); queries appear in reports once searched by at least two page views on the same UTC day. - **Problem types:** RFC 9457 `type` is always `about:blank`; branch on HTTP `status`. - **No MCP server yet:** merchant agents use the Management HTTP API; browser agents use WebMCP via `registerAgentTools` ([AI agents](/docs/search/agents)). ## License The OrbSearch engine and control plane are licensed under **AGPL-3.0-or-later**. The contract crate, `@orbsearch/client` and `@orbsearch/react` are licensed under **MIT**. ## Next steps | You want to | Read | | ---------------------------------- | ---------------------------------------------- | | Run OrbSearch locally | [Quickstart](/docs/search/quickstart) | | Check every enforced numeric limit | [Errors and limits](/docs/search/errors-and-limits) | | Deploy in production | [Self-hosting](/docs/search/self-hosting) | # Synonyms Map shopper vocabulary to your catalog's terms with synonym groups, one-way entries and never-merge guards. Shoppers search `"couch"` when your catalog says `"sofa"`. Synonyms connect those words in both text matching and [Query understanding](/docs/search/query-understanding), per language, with no condition or schedule. ## Read the live synonym dictionary ```sh curl -s -H "Authorization: Bearer $key" $api/synonyms \ | jq -r '.dictionaries[] | select(.locale == "de") | .entries[] | select(.id | IN("de/groups/0", "de/one_way/2", "de/never/0")) | "\(.id) \(.summary)"' ``` | Kind | Behaviour | Example | | --------- | ----------------------------------------------------------------------------------- | ---------------------------------------- | | `group` | Every word finds every other word in the group. | `sofa, couch` | | `one_way` | First word finds the target words, not the reverse. | `läufer` → `teppich` (runner finds rugs) | | `never` | Blocks accidental edits merging look-alike words; never changes live search itself. | `sessel` ≠ `sofa` | ## Synonyms power query understanding too A synonym inherits whatever its partner names in your catalog, including compound words ending in a synonym: ```sh for q in couch tischlampe; do curl -s "http://127.0.0.1:7800/v1/search?query=$q&debug=1" \ | jq -r '.trace.steps[] | select(.step == "resolve") | .detections[].entry' done ``` `"couch"` resolves to category `wohnen/sofas`, and `"Tischlampe"` (table lamp) resolves through `"lampe"` → `"leuchte"` to category `leuchten`. Every trace detection names the exact entry ID (such as `de/groups/0`). ## Add or edit a synonym Edits go into a [Draft](/docs/search/releases#work-in-a-draft) and go live within moments as engine settings, without reindexing. <Tab value="Admin / Panel"> Open _Search → Synonyms_ and select a language. Type `kanapee, sofa` into the top bar to preview live hit counts and conflicts before saving: - If a word already belongs to a group, choose **Add "kanapee" there** to extend the existing group (a word belongs to one group at most). - Toggle **One way** when the first term should expand without reversing. - A `never` guard blocks the save unless you confirm **Add anyway**. - Press **Review and publish** in the draft bar to take changes live. </Tab> <Tab value="API"> Start a draft (`POST $api/drafts` on the live catalog, or from an import), then add or patch an entry using its `version`: ```sh draft=$(curl -s -X POST -H "Authorization: Bearer $key" $api/drafts | jq -r .id) version=$(curl -s -H "Authorization: Bearer $key" $api/imports/$draft | jq -r .version) jq -n --arg version "$version" '{version: $version, entry: {kind: "group", words: ["sofa", "couch", "kanapee"]}}' \ | curl -s -X PATCH -H "Authorization: Bearer $key" -H 'Content-Type: application/json' -d @- \ $api/imports/$draft/synonyms/de/groups/0 \ | jq -r '.synonyms.dictionaries[] | select(.locale == "de") | .entries[0].summary' ``` Preview with `POST $api/preview/page`, inspect the rollout plan with `GET $api/imports/$draft/publication`, then publish (`POST $api/imports/$draft/publish`) or discard (`DELETE $api/imports/$draft`). Use `POST $api/synonyms/check` (live) or `POST $api/imports/$draft/synonyms/check` (draft) to test up to `50` words for hit counts and clashes without writing. </Tab> ## Good to know - **Case and umlaut folding:** `"Weiß"`, `"weiss"` and `"WEISS"` are treated as one word. - **Regional fallback:** `de-CH` reads the `de` dictionary if it has no dictionary of its own. - **Preview caveat:** Draft previews evaluate query resolution (such as category redirects) immediately, while Meilisearch text synonyms update once published. - **`never` guards:** Refused edits can be overridden with `"despite_never": true` on `POST`/`PATCH`. - **Batch limit:** Up to `1,000` synonym entries per API write. ## Customize | You want to | Do this | Default | | ------------------------------------- | -------------------------------------------------------------------------- | ----------------------------- | | Add a word to one single product only | Use `keywords` in [Overlays](/docs/search/overlays) | Dictionary applies store-wide | | Match phrases with numbers or units | Define a rule in [Patterns](/docs/search/patterns) | Word-level matching | | Map attribute value spellings | Add `aliases` in `attributes.json` ([Types](/docs/search/types-and-attributes)) | Exact label matching | ## Next steps | You want to | Read | | ----------------------------------- | -------------------------------------------------- | | Parse measurement and price phrases | [Patterns](/docs/search/patterns) | | See how synonyms feed resolution | [Query understanding](/docs/search/query-understanding) | | Preview and publish a draft | [Releases](/docs/search/releases) | | Find zero-result terms to map | [Insights](/docs/search/insights) | # Theming Reference every --orb-* CSS token, WCAG 2.2 AA contrast pair, data-slot selector and Tailwind v4 setup for @orbsearch/react. `@orbsearch/react` styles every component through `--orb-*` CSS custom properties and stable `data-slot` attributes. Import the base stylesheet once and load your theme after it: ```css title="app/app.css" @import "@orbsearch/react/orbsearch.css"; @import "./theme.css"; ``` ## Design tokens (`--orb-*`) Every variable begins with `--orb-`. Subsequent names in each row share that prefix: | Tokens | Controls | | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `--orb-color-ground`, `surface`, `well` | Page ground, panels/popovers, photo frame well | | `--orb-color-ink`, `ink-muted`, `line`, `line-strong` | Primary text, secondary text, borders, control outlines | | `--orb-color-accent`, `on-accent`, `accent-soft` | Action colour, text on accent, active/selected surface tint | | `--orb-color-hover`, `sale`, `rating`, `focus`, `scrim` | Row hover, sale prices, rating stars, focus rings, modal backdrop | | `--orb-font-sans`, `font-display`, `display-weight`, `tracking-display` | Body and display typography | | `--orb-text-display`, `text-display-sm` | Page heading sizes | | `--orb-radius-control`, `radius-card`, `radius-sheet`, `radius-row` | Radii for inputs/buttons, tiles/popovers, filter sheets, facet rows | | `--orb-shadow-pop` | Popover shadow | | `--orb-spacing-target`, `spacing-gutter` | Minimum touch target (`2.75rem`), mobile side gutter | | `--orb-container-shop`, `aspect-media` | Max page width, product image aspect ratio | | `--orb-tile-columns`, `tile-columns-md`, `tile-columns-xl` | Grid columns: `2`, `3` from `48rem`, `4` from `80rem` | | `--orb-grade-width`, `grade-step`, `grade-shape`, `grade-tip` | Energy/efficiency grade badge dimensions | | `--orb-swatch-count` | Swatch hit count position (`beside` or `on`) | | `--orb-ease-out-soft`, `motion-fast`, `motion-base`, `motion-wait` | Easing, press/popover (`140 ms`), sheet/grid (`220 ms`), dim delay (`150 ms`) | ## Contrast pairs (WCAG 2.2 AA) The default palette satisfies WCAG 2.2 AA across these pairs. When overriding a colour token, update its paired tokens together: - **Text (≥ 4.5:1):** `ink`, `ink-muted`, `sale` and `accent` on `ground`, `surface`, `well` and `accent-soft`. - **Controls and marks (≥ 3:1):** `line-strong`, `rating` and `focus` on `ground` and `surface`. <Callout type="warn"> Keep both sides of a pair in sync when defining dark themes or brand overrides so text and focus rings preserve WCAG 2.2 AA contrast. </Callout> ## Slots and state attributes Target specific parts cleanly with `data-slot` and state attributes instead of brittle class names: | Attribute | Values / examples | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `data-slot` | `search-input`, `suggestions`, `product-tile`, `tile-price`, `price-unit`, `price-now`, `rating`, `facet`, `filter-chip`, `sheet`, `load-more`, `tile-sponsored`, `suggestion-sponsored` | | `data-field` / `data-kind` | On `facet` (for example `[data-slot="facet"][data-field="color"]`), `banner` (`banner`/`teaser`) or suggestion | | `data-sold-out` | Present on sold-out `product-tile` elements | | `data-source` | On `filter-chip`: `shopper`, `query` or `rule` | | `data-placement` | On `banner`: `top`, `grid` or `bottom` | ## Plain CSS vs Tailwind v4 - **Plain CSS or unprefixed Tailwind:** import `@orbsearch/react/orbsearch.css` once (or inside a CSS `@layer orbsearch` if you manage cascade layers yourself) and follow it with your token overrides. - **Prefixed Tailwind v4 (`orb:`):** compile the component utilities directly with your own Tailwind build: ```css title="app/app.css" @import "tailwindcss/theme.css" prefix(orb); @import "@orbsearch/react/theme.css"; @import "tailwindcss/preflight.css" layer(base); @import "tailwindcss/utilities.css" source(none); @source "../"; @source "../../../packages/react/src"; ``` ## Customize | You want to | Do this | Default | | -------------------------------------- | --------------------------------------------------------------------------- | ------------------------ | | Add dark mode | Override `--orb-color-*` under `[data-theme="dark"]` | Light neutral palette | | Change grid columns on desktop | Set `--orb-tile-columns-xl: 5` | `4` columns from `80rem` | | Style sold-out tile prices differently | Target `[data-slot="product-tile"][data-sold-out] [data-slot="tile-price"]` | Standard ink | ## Next steps | You want to | Read | | ------------------------------------- | -------------------------------------- | | Follow the 4-step customisation guide | [Extend OrbSearch](/docs/search/extend) | | Inspect every React part and prop | [React components](/docs/search/react) | | Verify focus rings and reduced motion | [Accessibility](/docs/search/accessibility) | # Types and attributes Declare entity types, attribute value parsing, multi-dimension quantities, colour groups and stable localised slugs. Every catalog entity has one **Type** (`types.json`) and a set of **Attributes** (`attributes.json`). Together they define which fields are searched, how raw catalog strings turn into typed filter values, and which slugs appear in URLs. ## Configure entity Types (`types.json`) Built-in types are `product`, `service`, `category`, `content` and `brand`. You can also declare custom types with `capabilities` (`variants`, `offers`, `tree`): ```json title="types.json" { "types": [ { "type": "product", "search": ["title", "brand", "keywords", "attributes.color", "description"], "result": ["title", "url", "image", "price", "sale_price", "badges", "signals.rating"], "details": ["color", "material", "upholstery", "width", "seats"] }, { "type": "category", "search": ["title", "keywords", "description"], "result": ["title", "url", "path"] } ] } ``` - **`search`** sets searched fields in priority order ([Fields and typos](/docs/search/fields-and-typos)). - **`result`** lists fields returned on each search hit (including `badges` and `signals.*`). - **`details`** sets the attribute order on [Product pages](/docs/search/product-pages). ### Discoverable without a price (`channels`) Entities of types with `offers` (such as `service` or bookable appointments) can be made discoverable without fake prices or stock by listing `channels` directly on the entity: ```json title="catalog.jsonl (formatted)" { "type": "service", "id": "appointment", "title": "Appointment", "url": "/appointments", "channels": ["de"], "variants": [{ "id": "standard" }] } ``` `channels` grants discoverability in those declared channels (subject to channel `assortment`) without fabricating prices or availability. Only include published entities in the feed. ## Configure Attributes (`attributes.json`) ```json title="attributes.json" { "attributes": [ { "code": "color", "type": "option", "label": { "de": "Farbe", "en": "Color" }, "level": "variant", "values": [ { "code": "sage", "label": { "de": "Salbei", "en": "Sage" }, "aliases": ["salbei", "salbeigrün", "sage green"], "group": "green", "swatch": "#9CAF92" } ], "groups": [ { "code": "green", "label": { "de": "Grün", "en": "Green" }, "aliases": ["grün", "grünes"] } ], "color_groups": true, "filterable": true, "detect_in_query": true }, { "code": "width", "type": "quantity", "label": { "de": "Breite", "en": "Width" }, "unit": "cm", "filterable": true } ] } ``` ### Value parsing by attribute `type` | `type` | Catalog examples | Parsed value | Facet kinds | | ------------ | --------------------------- | -------------------------------------- | -------------------------- | | `option` | `"Grau"`, `"salbeigrün"` | Canonical option code (`grey`, `sage`) | `list`, `swatch` | | `quantity` | `"164 cm"`, `"6 ft"`, `164` | Converted to `unit` (`cm`, `km`, ...) | `range`, `buckets`, `list` | | `number` | `2`, `"1,5"` | Numeric `2`, `1.5` | `range`, `list` | | `boolean` | `true`, `"ja"`, `"nein"` | `true` / `false` | `toggle` | | `text` | Free text | Searchable text | Not filterable | | `identifier` | GTIN, SKU, model number | Exact / prefix match (`no_typos`) | Not filterable | `date` and `range` types are also supported. Unparseable attribute values are dropped without rejecting the entity and logged in the [Import report](/docs/search/import-report). ### Multi-dimension quantities (`units`) When one attribute holds values across dimensions (such as package sizes in both volume and mass), declare `units` instead of `unit` with one canonical unit per dimension: ```json title="attributes.json (excerpt)" { "code": "pack", "type": "quantity", "level": "variant", "units": ["ml", "g"], "filterable": true } ``` - Every value must carry a unit (`"400 ml"`, `"1 l"` → `"1000 ml"`, `"150 g"`); bare numbers like `150` are rejected. - Facets appear as unit-bearing `list` choices rather than a shared numeric slider. - Filters accept equivalent units (`{ "pack": "0.15 kg" }`) and single-dimension ranges (`{ "pack": { "gte": "400 ml", "lte": "1 l" } }`). Cross-dimension comparisons and shared sorts are refused. ## Spellings, colour groups and slugs Option matching folds case, accents and `ß` (`"Weiß"` and `"weiss"` match identically). Unknown spellings become derived option values automatically and appear in `GET /api/v1/live` under `report.values.derived`; with `"color_groups": true`, German and English colour words auto-assign to colour groups. ### Slugs Every option value stores a per-locale `slug` used in [filter page URLs](/docs/search/urls#configure-routes-and-filter-pages): ```json title="attributes.json (value excerpt)" { "code": "green", "label": { "de": "Grün", "en": "Green" }, "slug": { "de": "gruen", "en": "green" } } ``` - Generated once using CLDR transliteration (`Grün` → `gruen`, `Größe` → `groesse`). - Renaming a label preserves the existing slug; changing a slug moves the old one into `slug_aliases` so existing URLs redirect cleanly. - Duplicate slugs receive numeric suffixes (`gruen-2`). ## Customize | You want to | Do this | Default | | ---------------------------------------- | ---------------------------------------------------- | ---------------------------------- | | Allow per-variant attribute values | Set `"level": "variant"` on the attribute | `"product"` (shared across SKUs) | | Enable automatic query filter detection | Set `"detect_in_query": true` on the attribute | Derived for colour and key options | | List tiles per colour instead of product | Set `"listing": { "axis": "color" }` in `types.json` | `"product"` (one tile per product) | ## Next steps | You want to | Read | | -------------------------------------- | --------------------------------------- | | Model variants and listing granularity | [Variants](/docs/search/variants) | | Configure markets and locales | [Channels](/docs/search/channels) | | Inspect derived values after indexing | [Import reports](/docs/search/import-report) | # URLs and redirects Route your own category, filter, search and product URLs through /v1/resolve with canonical 301s, redirects, robots.txt and sitemaps. OrbSearch never forces a URL scheme. Category and product paths come from your catalog, while `routes.json` and `redirects.json` configure search paths, filter pages and legacy redirects. ## Resolve any storefront URL Ask `GET /v1/resolve` before rendering a page. It identifies the URL, supplies HTTP `status`, `robots`, `canonical`, `title`, `h1`, `alternates` and (unless `results=0`) the full listing or product data in one call: ```sh curl -s -G http://127.0.0.1:7800/v1/resolve \ --data-urlencode 'url=/wohnen/sofas?farbe=grey&width.lte=220' -d results=0 \ | jq -c '{type, status, robots, title, entity}, .breadcrumbs, .request.filters' ``` Every listing state has one canonical spelling (parameters sorted alphabetically, renamed via `routes.json`). Any non-canonical spelling returns `status: 301` with `location`, preserving unknown parameters such as `utm_source`. | `type` | `status` | What it carries | | ----------- | ----------- | ---------------------------------------------------------------------------------------- | | `category` | `200`/`404` | Listing `request`, `results`, `breadcrumbs`; `404` if empty indexable or past last page. | | `brand` | `200`/`404` | Brand listing `request` and `results`. | | `search` | `200` | Search listing (always `noindex,follow`); `302` redirect if query resolves to a page. | | `product` | `200` | Full `product` payload matching `GET /v1/product`. | | `redirect` | `301`/`302` | Final `location` (redirect chains are collapsed into a single hop). | | `gone` | `410` | URL explicitly removed in `redirects.json`. | | `not_found` | `404` | Unknown path. | ## Configure routes and filter pages `routes.json` names your search page per locale, renames URL query parameters (keeping internal codes as aliases) and turns selected filter combinations into clean, crawlable paths: ```json title="routes.json" { "search": { "de": "/suche", "en": "/en/search" }, "parameters": { "brand": { "name": "marke", "aliases": ["brand"] }, "color": { "name": "farbe", "aliases": ["color"] } }, "filter_pages": { "facets": ["brand", "color"], "combinations": [ { "facets": ["color"], "title": { "de": "{category} in {color}", "en": "{color} {category}" } }, { "facets": ["brand"], "title": { "de": "{category} von {brand}", "en": "{brand} {category}" } }, { "facets": ["brand", "color"], "title": { "de": "{category} von {brand} in {color}" } } ] } } ``` | Selection on `wohnen/sofas` | Canonical URL | | --------------------------- | ------------------------------------------- | | Brand Halvard | `/wohnen/sofas/marke--halvard` | | Colour grey | `/wohnen/sofas/farbe--grau` | | Halvard + grey | `/wohnen/sofas/marke--halvard/farbe--grau` | | Grey or anthracite | `/wohnen/sofas?farbe=anthracite&farbe=grey` | Every facet value returned by `/v1/resolve` carries its ready-to-link `url` so shoppers land on the canonical URL without a `301` hop. ### Indexability and titles Filter pages with at least `min_products` hits (`4` by default) return `index,follow` and their own `canonical`. Fewer hits return `noindex,follow`, and zero hits return `404`. Set `index: false` on a `categories.json` node to keep a category and its descendants out of search engines. <Tab value="Panel"> Open _Catalog → URLs & SEO_ to manage **Filter pages**, attribute **Slugs** and preview `robots.txt`. The header URL tester opens a side-by-side sheet showing status, robots, canonical, title and whether publishing moves any indexed URLs. </Tab> <Tab value="API"> Write `routes.json`, `categories.json` and `attributes.json` in a draft via `PATCH /api/v1/imports/{import}`. Preview any single URL with `POST /api/v1/preview/page`, and inspect all generated filter pages and moved indexed URLs with `POST /api/v1/preview/urls`. </Tab> ## Legacy redirects (`redirects.json`) Carry over old shop URLs in `redirects.json`. Entries stay in memory and cost zero engine calls: ```json title="redirects.json" { "redirects": [ { "from": "/sofas.html", "to": "category:wohnen/sofas" }, { "from": "/index.php", "query": { "cat": "12" }, "to": "category:wohnen" }, { "from": "/old-search", "url": "/suche", "keep": ["sort"] }, { "from": "/outlet-2019", "status": 410 }, { "pattern": "^/kategorie/(.+?)/?$", "url": "/wohnen/$1" } ] } ``` Exact matches run before regex `pattern` rules (up to `500` patterns), and chains collapse to their final destination. `keep` forwards selected query parameters; redirects to your local search path also forward `q` unless the target already sets it. ## Serve a catch-all storefront route Place a catch-all route after your shop's own routes (such as checkout): ```tsx title="app/routes/page.tsx" import { createSearch, locationOf } from "@orbsearch/client/server"; import { data, redirect, type LoaderFunctionArgs, type MetaFunction } from "react-router"; const ORIGIN = "https://shop.example"; export async function loader({ request }: LoaderFunctionArgs) { const url = new URL(request.url); const userAgent = request.headers.get("user-agent"); const search = createSearch({ endpoint: "https://search.shop.example", ...(userAgent && { userAgent }), }); const page = await search.resolve( url.pathname + url.search, { locale: "de" }, { signal: request.signal }, ); const location = locationOf(page); if (location !== null) throw redirect(location, page.status); if (page.type === "gone" || page.type === "not_found") throw data(null, { status: page.status }); return data(page, { status: page.status }); } export const meta: MetaFunction<typeof loader> = ({ loaderData: page }) => [ ...(page?.title ? [{ title: page.title }] : []), ...(page?.description ? [{ name: "description", content: page.description }] : []), ...(page?.robots ? [{ name: "robots", content: page.robots }] : []), ...(page?.canonical ? [{ tagName: "link", rel: "canonical", href: ORIGIN + page.canonical }] : []), ...(page?.alternates ?? []).map(({ locale, url }) => ({ tagName: "link", rel: "alternate", hrefLang: locale, href: ORIGIN + url, })), ]; ``` `locationOf(page)` percent-encodes non-ASCII paths (such as `/möbel`) for the `Location` header. ## Robots and sitemaps - **`GET /v1/robots`** returns `Disallow` lines keeping crawlers off unindexed filter parameters, sorts and `/suche`, while leaving filter page paths and `?page=N` crawlable. - **`GET /v1/sitemap`** returns up to `50,000` indexable URLs per page (`?page=2` for more): categories, brands and filter pages meeting `min_products`. Prefix each path with your origin when writing `sitemap.xml`. ```sh curl -s http://127.0.0.1:7800/v1/robots | jq -r '.lines[:5][]' curl -s http://127.0.0.1:7800/v1/sitemap | jq -c '{pages, urls: (.urls | length)}, .urls[0]' ``` ### Current limits - OrbSearch returns paths only; prepend your storefront origin for `canonical`, `alternates` and `sitemap.xml`. - Product URLs match exact case and trailing slash as imported. - Sitemaps count category and brand presence across channels. ## Customize | You want to | Do this | Default | | -------------------------------------- | --------------------------------------------------------- | ---------------------------- | | Rename URL parameters per language | Set `parameters` in `routes.json` | Attribute/field code | | Put one facet before the category path | Configure `filter_pages.before_category` in `routes.json` | Segments after category path | | Adjust filter page indexing threshold | Set `filter_pages.min_products` in `routes.json` | `4` products | | Keep trailing slashes on every URL | Set `trailing_slash` in `routes.json` | No trailing slash | ## Next steps | You want to | Read | | ------------------------------------- | ---------------------------------------------------------- | | Wire the full storefront app | [Build a storefront](/docs/search/your-storefront) | | Manage attribute value slugs | [Types and attributes](/docs/search/types-and-attributes#slugs) | | Preview URL changes before publishing | [Releases](/docs/search/releases) | # Variants Model products with multiple SKUs, match filters to exact variants and choose per-product, per-variant or per-axis listing tiles. A **Variant** is one buyable SKU of a product (such as a sofa in grey or sage) carrying its own options, price, stock and optional images or URL. ## Structure variants in the catalog ```json title="catalog.jsonl (formatted)" { "type": "product", "id": "SOFA-ASKA-2", "title": { "de": "Aska 2-Sitzer-Sofa aus Samt", "en": "Aska two-seater velvet sofa" }, "categories": ["wohnen/sofas"], "attributes": { "seats": 2, "width": "164 cm", "upholstery": "Samt" }, "varies_by": ["color"], "variants": [ { "id": "SOFA-ASKA-2-GRAU", "attributes": { "color": "Grau" }, "price": 749.0, "availability": "in_stock", "stock": 12 }, { "id": "SOFA-ASKA-2-SALBEI", "attributes": { "color": "Salbei" }, "price": 749.0, "sale_price": 649.0, "availability": "in_stock", "stock": 4 } ] } ``` `varies_by` names the attributes that distinguish variants (no two variants may share identical axis values). In flat CSV/XML exports, map a parent ID column to `group` in `feed.json` to assemble variants automatically ([Importing and mapping](/docs/search/importing)). Mark attributes that differ per SKU with `"level": "variant"` in `attributes.json` (omitting `attributes.json` derives this automatically). ## How filters pick the matching variant When a shopper filters by a variant-level attribute or offer range, OrbSearch matches all criteria on the same variant before counting and paginating, and returns that variant's ID, media and offer on the tile: ```sh curl -s http://127.0.0.1:7800/v1/search -H 'Content-Type: application/json' \ -d '{"on": "category_page", "category": "wohnen/sofas", "filters": {"color": "green"}}' \ | jq -c '.sections[] | select(.type == "product") | .hits[] | {entity, variant, color: .fields["attributes.color"]}' ``` - Under `"color": "grey"`, the Aska sofa shows its grey photo and `749 €` price, never the `649 €` sale price that applies only to sage. - When multiple variants match the active filters, the active sort order picks the representative variant shown on the tile. - Without variant-level filters, a product tile omits `variant` and displays the product-level offer summary. ## Listing granularity: product, variant or axis Control what each grid tile represents via `listing` in `types.json` (changing `listing` triggers a **Rebuild**): ```json title="types.json" { "types": [{ "type": "product", "listing": { "axis": "color" } }] } ``` | `listing` value | Tiles created | | --------------------- | -------------------------------------------------------------------- | | `"product"` (default) | One tile per product; pins and deduplication operate per product. | | `"variant"` | One tile per SKU with that SKU's exact offer, URL and media. | | `{ "axis": "color" }` | One tile per value of one variant-level option, quantity or boolean. | Products that do not vary along the chosen axis stay a single tile. Note that [Rule pins](/docs/search/rules#limits) require `"listing": "product"`. ## Customize | You want to | Do this | Default | | ------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------ | | Show one tile per colour | Set `"listing": { "axis": "color" }` in `types.json` | `"product"` | | Return swatch previews on cards | Pass `cards: true` ([Search and browse](/docs/search/search#complete-listing-cards)) | Single representative hit | | Update one variant's price in seconds | Call `PUT /api/v1/offers` ([Live prices](/docs/search/prices-and-stock)) | Updated on next catalog upload | ## Next steps | You want to | Read | | ------------------------------------- | ------------------------------------------------------------------- | | Render variant pickers on PDPs | [Product pages](/docs/search/product-pages) | | Push live price and stock changes | [Live prices and stock](/docs/search/prices-and-stock) | | Understand variant facet upper bounds | [Facets and filters](/docs/search/facets#upper-bounds-on-variant-facets) | # Your own catalog Upload your shop's existing CSV, Excel, Merchant Center XML or JSON export and search it without writing configuration first. OrbSearch indexes the export your shop already produces: CSV, Excel (`.xlsx`), Google Merchant Center XML or JSON. With an empty Release, it derives channels, attributes, facets and sorting directly from your data. These steps reuse `$key` and `$api` from the [Quickstart](/docs/search/quickstart#save-the-management-key) and send a German Excel CSV export. ## Index an export with zero configuration ### Publish an empty Release An empty [Release](/docs/search/concepts#release) tells the indexer to derive every missing configuration file from the catalog: ```sh empty=$(curl -s -H "Authorization: Bearer $key" -H 'Content-Type: application/json' \ -d '{"files": {}}' $api/releases | jq -r .id) curl -s -X POST -H "Authorization: Bearer $key" $api/releases/$empty/publish >/dev/null ``` ### Upload the export Send your file as written and wait for its [Index run](/docs/search/concepts#index-run) to complete: ```sh run=$(curl -s -X PUT -H "Authorization: Bearer $key" -H 'Content-Type: text/csv' \ --data-binary @tests/fixtures/feeds/home/export.csv $api/catalog | jq -r .run.id) until curl -s -H "Authorization: Bearer $key" $api/index-runs/$run \ | jq -e '.state | IN("queued", "running") | not' >/dev/null; do sleep 1; done curl -s -H "Authorization: Bearer $key" $api/index-runs/$run | jq -c '{state, entities: .report.entities}' ``` The indexer detects format, encoding and delimiter from the bytes. The `Content-Type` header is informational only. ### Inspect derived settings Every derived setting carries its evidence in the run report. Inspect why the column `Farbe` became the attribute `color`: ```sh curl -s -H "Authorization: Bearer $key" $api/index-runs/$run \ | jq -c '.report.defaults.reasons[] | select(.setting == "color") | .reason' ``` Its values behave like options and vary across a product's variants. Because 97 % of them are colour words, `Grau` and `Hellgrau` join the `grey` group automatically and enable query colour detection. ### Run a search The Quickstart's query works on the CSV export too: ```sh curl -s 'http://127.0.0.1:7800/v1/search?query=graues%20Sofa&debug=1' \ | jq -c '.resolution, [.sections[] | select(.type == "product") | .hits[].entity], .trace.derived' ``` The same two grey sofas return, and `trace.derived` lists the six configuration files derived during the run. ## How defaults and written files meet Write a configuration file only when you want to override a default. Files you include in a Release stay yours, while omitted files continue to derive from each new catalog. | Language detection | Behaviour | | ------------------ | -------------------------------------------------------------------------------- | | German and English | Detected automatically from column names and cell values. | | Suffixed columns | Columns like `Name FR` add that locale automatically. | | Other languages | Declare the locale explicitly in `channels.json` ([Channels](/docs/search/channels)). | ## Customize | You want to | Do this | Default | | ------------------------------------ | --------------------------------------------------------- | --------------------------------- | | Preview and fix column mappings | Create an [Import](/docs/search/importing) before publishing | Columns mapped by name and values | | Own specific attribute labels/groups | Add `attributes.json` to your [Release](/docs/search/releases) | Derived from catalog values | | Fetch the export on a schedule | Configure a [Scheduled feed](/docs/search/feeds) URL | Manual uploads via API or panel | ## Next steps | You want to | Read | | -------------------------------------- | ------------------------------------------ | | Review and fix column mappings | [Importing and mapping](/docs/search/importing) | | Check supported export formats | [Catalog formats](/docs/search/formats) | | Read rejected rows and derived reasons | [Import reports](/docs/search/import-report) | | Take ownership of configuration files | [Releases](/docs/search/releases) | # Build a storefront Build a server-rendered React Router storefront with SearchBox, ListingPage and ProductPage in five steps. Go from an empty folder to a working storefront with instant search, faceted category listings and product pages using `@orbsearch/client` and `@orbsearch/react`. You need the running stack and example catalog from the [Quickstart](/docs/search/quickstart). Because `@orbsearch/client` and `@orbsearch/react` are pre-release and not published to npm yet, the app runs inside the repository's pnpm workspace alongside `apps/demo`. ## Set up the storefront ### Create the app manifest and Vite config Create `apps/shop/package.json` and `apps/shop/vite.config.ts`: ```json title="apps/shop/package.json" { "name": "shop", "private": true, "type": "module", "dependencies": { "@orbsearch/client": "workspace:*", "@orbsearch/react": "workspace:*", "@react-router/node": "catalog:", "isbot": "catalog:", "react": "catalog:", "react-dom": "catalog:", "react-router": "catalog:" }, "devDependencies": { "@react-router/dev": "catalog:", "@types/react": "catalog:", "@types/react-dom": "catalog:", "vite-plus": "catalog:" } } ``` ```ts title="apps/shop/vite.config.ts" skip="React Router Vite config outside docs-samples" import { reactRouter } from "@react-router/dev/vite"; import { defineConfig } from "vite-plus"; export default defineConfig({ plugins: [reactRouter()] }); ``` ### Create one client per page load Every search in one page load shares a `pageView` ID so [Insights](/docs/search/insights) counts unique visits without cookies. Create one client per server request and reuse its `pageView` in the browser: ```ts title="apps/shop/app/search.ts" import { createSearch } from "@orbsearch/client"; const endpoint = "http://127.0.0.1:7800"; export function searchFor(pageView: string, userAgent?: string | null) { return createSearch({ endpoint, pageView, ...(userAgent && { userAgent }) }); } ``` For server-only modules without DOM types, import `createSearch` from `@orbsearch/client/server`. ### Add the catch-all storefront route Place your shop's own routes (such as checkout) first in `routes.ts`, followed by a catch-all route that delegates every other URL to `search.resolve()`: ```ts title="apps/shop/app/routes.ts" skip="React Router route config outside docs-samples" import { route, type RouteConfig } from "@react-router/dev/routes"; export default [route("*", "routes/shop.tsx")] satisfies RouteConfig; ``` ```tsx title="apps/shop/app/routes/shop.tsx" import { createSearch, isListing, locationOf } from "@orbsearch/client"; import { ListingPage, ProductPage, listingView } from "@orbsearch/react"; import { data, redirect, useLoaderData, type LoaderFunctionArgs } from "react-router"; const endpoint = "http://127.0.0.1:7800"; export async function loader({ request }: LoaderFunctionArgs) { const url = new URL(request.url); const pageView = crypto.randomUUID(); const userAgent = request.headers.get("user-agent"); const search = createSearch({ endpoint, pageView, ...(userAgent && { userAgent }) }); const page = await search.resolve( url.pathname + url.search, { locale: "de" }, { signal: request.signal }, ); const init = { status: page.status }; if (isListing(page)) { return data( { kind: "listing" as const, listing: listingView(page, { path: url.pathname, locale: "de" }), pageView, }, init, ); } if (page.product) { return data( { kind: "product" as const, product: page.product, path: url.pathname, pageView }, init, ); } const location = locationOf(page); if (location !== null) throw redirect(location, page.status); throw data(null, init); } export default function Shop() { const shown = useLoaderData<typeof loader>(); if (shown.kind === "product") { return ( <ProductPage product={shown.product} trail={[{ title: shown.product.title, href: shown.path }]} /> ); } return <ListingPage listing={shown.listing} />; } ``` ### Mount `StorefrontProvider` and `SearchBox` in the root layout ```tsx title="apps/shop/app/root.tsx" import { createSearch } from "@orbsearch/client"; import { SearchBox, StorefrontProvider, type ListingView } from "@orbsearch/react"; import "@orbsearch/react/orbsearch.css"; import { useMemo, type ReactNode } from "react"; import { Links, Meta, Outlet, Scripts, useLocation, useNavigate } from "react-router"; const endpoint = "http://127.0.0.1:7800"; export function Layout({ children, pageView, listing, }: { children: ReactNode; pageView?: string; listing?: ListingView; }) { const navigate = useNavigate(); const location = useLocation(); const search = useMemo( () => createSearch({ endpoint, pageView: pageView ?? crypto.randomUUID() }), [pageView], ); return ( <html lang="de"> <head> <meta charSet="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <Meta /> <Links /> </head> <body> <StorefrontProvider search={search} locale="de" navigate={(href, { replace, keepScroll } = {}) => void navigate(href, { ...(replace && { replace }), ...(keepScroll && { preventScrollReset: true }), }) } > <header> <SearchBox action="/suche" query={listing?.from ?? listing?.query ?? ""} at={location.key} /> </header> <main>{children}</main> </StorefrontProvider> <Scripts /> </body> </html> ); } export default function App() { return <Outlet />; } ``` ### Start the dev server ```sh pnpm install pnpm --filter shop dev ``` Open `http://localhost:5173/suche?q=graues%20sofa`. OrbSearch redirects to `/wohnen/sofas/farbe--grau` with grey selected, two grey sofas, the active sofa-sale banner and working filters. ## What this gives you out of the box - **Server-rendered progressive enhancement:** search, filters, sorting and pagination are plain links and `GET` forms underneath. - **Merchant-owned URLs:** categories, filter pages and product pages serve at your catalog and `routes.json` paths with `301`/`410`/`404` status codes. - **Built-in Insights reporting:** tiles, banners and suggestions report views and clicks automatically without cookies ([Clicks and views](/docs/search/clicks-and-views)). ## Customize | You want to | Do this | Default | | ------------------------------------- | ------------------------------------------------------------- | --------------------------- | | Apply your brand colours and fonts | Override `--orb-*` tokens ([Theming](/docs/search/theming)) | Neutral WCAG AA palette | | Switch to a desktop filter sidebar | Pass `filters="sidebar"` to `<ListingPage>` | Horizontal quick-filter bar | | Add custom breadcrumbs or departments | Spread `{ ...view, trail, categories, popular }` on `listing` | Derived from `/v1/resolve` | ## Next steps | You want to | Read | | --------------------------------------- | ------------------------------------- | | Style tokens, slots and custom tiles | [Extend OrbSearch](/docs/search/extend) | | Explore every exported React part | [React components](/docs/search/react) | | Copy standalone facet and sheet recipes | [Storefront recipes](/docs/search/recipes) |