@okam-as/storefront
v0.2.0
Published
Typed client for the Okam Storefront API. The server owns prices, VAT, orders and payment.
Readme
@okam-as/storefront
Typed client for the Okam Storefront API (/storefront/v1). The server owns prices, VAT, orders and
payment; this SDK holds no money arithmetic. MIT licensed.
Placeholder name until the owner confirms it: the docs host kit.okam.no.
import { createStorefront, formatMoney } from '@okam-as/storefront';
const okam = createStorefront({ key: 'pk_test_…' });
const site = await okam.site();
const menu = await okam.menu(site.stores[0].id, 'SelfPickup');
const cart = okam.cart(site.stores[0].id);
cart.setDeliveryType('SelfPickup');
cart.add({ id: product.id, name: product.name }, { optionIds, quantity: 1 });
await okam.signIn.sendCode('412 34 567');
await okam.signIn.verify(code); // one PUT sends the local cart
const quote = await cart.sync(); // server totals
formatMoney(quote.total); // «289,00 kr», the only money function
const pay = await cart.checkout(); // redirects to Dintero; { mount, embed } embeds, which verify cannot check
if (pay.orderToken) okam.order(pay.orderToken).watch((status) => render(status.state)); // a free order (status 'completed') has noneReact (@okam-as/storefront/react): headless hooks, no markup, so every site keeps its own look.
useSite(okam, cart?): the site, loaded once; withcart, an unset delivery type becomes the store's first.useMenu(okam, storeId, deliveryType): the menu for that delivery type.useCart(cart): the cart state, re-rendered on every change.useQuickAdd(okam, cart): one-tapadd(product)→'added'or'options'(open your sheet), withbusyIdand an aria-liveannouncement.useProductOptions(okam, cart, product): optiongroups,selected,toggle,missingandadd()that checks required groups.useSignIn(okam):stepphone → code → done,sendCode(),verify(),errorandphoneError.useSignedIn(okam): whether the guest is signed in.useCheckout(okam, cart, products): the serverquote,blocker,error,canPayandpay(opts).useOrder(okam, orderToken): the order's state asorder.watchreports it.
Okam Storefront Kit
Build a restaurant's own ordering website on the Okam Storefront API. Okam's server owns prices, VAT, orders and payment. The kit gives the logic and the outcomes every guest must get; the look is yours, from the brief.
Versions (2026-10-21): API /storefront/v1, not released; SDK @okam-as/storefront@^0.2.0 on npm; a pk_test_ key calls https://testapi.okam.no; kit verify CLI @okam-as/storefront-verify 0.1.4 on npm (Playwright Chromium).
Must-nots
- Never compute, sum or adjust a price, VAT, fee or total. Show
formatMoneyof the server's value. - Never call the Okam API except through
@okam-as/storefront, and never api.okam.no while building. - Never poll or fan out: no refetch timers, no
productOptionscall per product on load.order.watchon the status page is the only repeating call. - Never show an order as paid or thanked on your own. Show the state the server reports.
- Never put any key other than
pk_in the site, and never build return URLs. - Never let an agent or a script press Pay or submit Dintero's form, and never handle card data, saved cards or payment tokens.
- Never hide allergens: visible text for each dish where the guest picks it and for every cart line before payment, signed in or not. A dish with none says «Allergener: ingen oppgitt – spør oss», never «allergenfri».
- Never install the reference blocks or copy their look.
- Not done until
storefront_verify_resultis green for this origin, with "Verify contract" intact. A WAIT is not a failure; a FAIL is, except sandboxrequote.
Steps
- Read the brief and design the site from it. Call
kit_learnwithframework, then read assemble-a-shop, world-class-ordering-ux, verify-contract and the-return-page withkit_docs_get. - Reuse one MCP session; never call in a loop. On HTTP 429, wait 60 s once and retry.
- Install the SDK and put the sandbox key in the site app's public config.
- Build the four pages with your own components from those docs. Use store 178, which takes orders 10–22 Oslo time.
- Add the "WebMCP" tools.
- Serve the site in the background on a fixed port until the hand-off. Open
http://localhost:<port>, not 127.0.0.1, and look at it as a guest at 390 px and 1440 px. Then callstorefront_connectwith the key and that exact origin, no path. - Run the verify command
storefront_connectreturned; for a site under a path, set--urlto the full URL. If Playwright's browser is missing, runnpx playwright install chromiumonce. - Call
storefront_verify_resultwith that run's runId. Fix every FAIL and rerun; report WAITs. When verify is green, work through the go-live list it returns.
Assemble a shop
- Logic: one
createStorefront({ key })and oneokam.cart(storeId)at module scope. In React, hooks from@okam-as/storefront/reacthold state and render nothing:useSite(okam, cart),useMenu(okam, storeId, deliveryType),useCart(cart),useQuickAdd(okam, cart),useProductOptions(okam, cart, product),useSignIn(okam),useCheckout(okam, cart, products),useSignedIn(okam)anduseOrder(okam, orderToken); without React, the core client. Texts come fromstrings('nb');openingRows,nextOpeningandlaterTodaycover opening hours. - Routes: the store
/, checkout/kasse, the return page/ordreand the status page/r/<orderToken>(noindex). Under a base path (/sandbox/), prefix every route and link. One<h1>,langand<title>per page. - The store page shows the menu with prices and allergens, «Alle priser er inkl. mva.» once, opening hours, and the seller's legal name, address and terms link.
- The menu needs a delivery type:
useSite(okam, cart)sets the store's first; without React, set it. - A dish without options goes in with one tap. A dish with options opens a choice step; fetch its options only then.
- Before sign-in the server quotes no total. Each line shows its quantity, «Enhetspris 189,00 kr» from the menu product with its
productId(lines carry no unit price) and each non-zeroline.optionPrices(«Stor + 10,00 kr»), never added up. One sentence, free of «total», «sum» and «å betale», says the amount follows sign-in. - Checkout: the delivery type choice, sign-in with a phone code, then the lines with their allergens and the seller and terms above one Pay button; all but Pay show before sign-in too. Pass every menu product to
useCheckout. pay()without options redirects to Dintero; verify needs that redirect, so do not embed. A free order setsplaced(no payment, maybe no token): say it is placed.- When
quote.paymentTypeslists more than one type, let the guest choose before Pay (radio inputs named «Vipps» and «Kort») and pass the choice aspay({ paymentType }). Without a choice, Pay starts card. - Each payment outcome gets a guest-words message and a next step. Waiting copy («Venter på betaling») only while
pending_paymentand not cancelled. returnFromPayment()givescancelled: true: the guest cancelled, whatever the server still reports. At once showstrings('nb').paymentAbortedand a one-tap «Prøv igjen» to/kasse. The SDK keeps the cart; the page shows its lines (useCart) or a cart control, never only the claim that it was kept.payment_failed: the same. AuseOrdererror is not a failed payment: say the status can't be checked now, offer «Prøv igjen» (reloads the page) andseller.publicEmail; never claim it failed.- Still
pending_paymentafter 30 s, no cancel: «Betalingen er ikke bekreftet ennå», keep watching, say it may go through, offer «Tilbake til handlekurven» (/kasse) andseller.publicEmail; no Pay. - Eat-in (
TableDelivery) asks for the table number, labelledstrings('nb').tableName. When none of the store's types delivers, the choice is not called «Levering». - Closed store: say so with the next opening from
nextOpening(store)(«Stengt nå – åpner kl. 10:00»), offer a later slot instead of «Snarest», keep the cart usable and show the server'sstore_closedmessage at checkout.
World-class ordering UX
- Identity: the brief's type, colour, layout and voice, carried into the cart, dialogs, checkout and status page. Style every control on the native element (
appearance: none). - Menu first: on a 390 px phone the first dishes and prices show on the first screen. Make 1440 px deliberate, never a narrow column on an empty canvas.
- Show a dish's
imageUrlwhen set, never a placeholder. - Mark required option groups.
- The cart is always reachable, few taps from Pay, never covering content or Pay. Layout and cart pattern are ones only this restaurant would have; header, card grid, bottom bar and right cart column is the generic skeleton: avoid it unless the brief asks.
- Loading and errors say in guest words what happened and what to do («Prøv igjen» calls
reload()); never blank or an endless spinner. - No layout shift: reserve the menu's and the cart's space while loading. No heavy hero, font or script first.
- Accessibility: every target, toggles and chips included, at least 44 px; WCAG 2.2 AA contrast; full keyboard use with visible focus; a skip link; focus on the new page's heading after a route change. Overlays are modal. Focus never falls to
<body>: closing an overlay returns it to its trigger; after an add or removal it stays on a visible control. Adds, quantity changes and removals are announced inaria-live. - Every step has a URL, and back works.
- Motion by default, at the brief's tone: overlays in and out, page and step changes, the menu's first reveal; an add visibly reaches the cart. Never delay content or input; under
prefers-reduced-motion, a fade or nothing. - Closing a
<dialog>callsclose()at once; an exit animation never keeps it modal.
Verify contract
- Verify finds elements by role and name, and Pay by its
data-okam="checkout"hook: keep these hooks and names. - Each dish:
data-okam="menu-item",data-okam-product-id="<server id>",data-okam-sold-out="true|false", an<h3>with the name, its allergens as visible text, and a button «Legg til ». Sold out: that button is disabled, reads «Utsolgt» and is named «, utsolgt». - Options: the only open
dialog, one<fieldset>per group, radios or checkboxes labelled with the option name first, and a confirm button also named «Legg til ». A one-tap add opens nothing, not even the cart. - Buttons, not links: «Vis handlekurv», «Til kasse», «Send engangskode», «Bekreft kode», «Bruk denne handlekurven». Text fields: «Telefonnummer», «Engangskode». English sites take these names from
strings('en'). - At 390 and 1440 px verify clicks the first shown button starting «Vis handlekurv», if any, then the first shown one starting «Til kasse», «Kasse» or «Checkout» in DOM order; it must be uncovered and go to
/kasse. A cart behind a button names that button «Vis handlekurv»; where the cart shows inline, show none. - Pay: exactly one
data-okam="checkout"button in the DOM, hidden ones included. Once quoted it is named «Bestill og betal <formatMoney(total)>» (strings('nb').orderAndPay); before that exactly «Bestill og betal» (strings('nb').pay), disabled, with nothing after it. Before it in the page: the seller's legal name and address, each visible in an element without child elements, and a link tostore.termsUrl. - Total once quoted:
data-okam="cart-total"withdata-okam-minor="<øre>"and the textformatMoney(total). - On
/kasse:<input type="radio">valued with the store's delivery types (SelfPickup,TableDelivery, …); a change re-quotes and shows the new total. In the sandboxrequoteFAILs (pickup and eat-in cost the same): expected; report it. - Server errors: the server's
detailunchanged insidedata-okam="error". Verify forces a 429 on the cartPUT. - Order state:
data-okam="order-status"withdata-okam-state="<server state>"insidearia-live="polite". Verify cancels on Dintero (cancelled-payment), declines (failed-payment), then pays. - Timing: after each click verify waits for network idle and looks once, so what a click reveals is in the DOM in the same tick; animate it in after it mounts. No lazy route, Suspense or loading screen before the sign-in form. React Router's data router renders in a transition verify misses: switch pages on
location.pathnamewithpushStateandpopstate. A return-page redirect from a child effect can fire before that listener: read the location viauseSyncExternalStore. - Every check FAILing on
locator.waitFor: Timeout: no menu within 15 s (server down, 127.0.0.1, or a failed menu request). - In the sandbox, sign-in and every check after it WAIT until the sandbox guest exists: never stub sign-in. While the store is closed the payment checks FAIL; rerun while it is open.
The return page
- Dintero returns the guest to the origin plus the registered path,
/ordreby default, keeping its query; it must load your app (SPA fallback in production). A site under a path asks Okam to register the full path (/sandbox/ordre). - It calls
okam.returnFromPayment()once and replaces its URL with/r/<orderToken>(plus?cancelled=1after a cancel, shown as cancelled), or the store page when that returns null.data-okam-statestays the server's; keep watching after a cancel (verify wantspayment_failed). - Its own text never says «betalt», «takk», «paid» or «thanks»; the server state (
orderState.paid) may.
WebMCP
- Behind a feature check, register WebMCP tools on
document.modelContext, elsenavigator.modelContext:registerTool({ name, title, description, inputSchema, execute, annotations }, { signal }),inputSchema{ type: 'object', properties: {} }when empty, andexecutereturningJSON.stringify(result). - Six tools:
search_menu{ query? }returns id, name, price text, allergens (["ingen oppgitt"]when empty) and soldOut;add_to_cart{ productId, optionIds?, quantity? };update_cart_line{ lineKey, quantity }, 0 removes;set_delivery_type{ type, tableName?, time? }returns its label and time slots;view_cart{}returns lines with a shortlineKey, the server total once quoted,isOpenNowand the next opening;start_checkout{}opens checkout and says what the guest does next.search_menuandview_cartarereadOnlyHint: true. - Tools share the UI's cart and labels; a failure throws an
Errorsaying what to do. No tool signs in, fills a code, presses Pay or touches Dintero. - Register each tool once per page (StrictMode runs effects twice). Verify skips WebMCP: call each
executeonce yourself.
Monorepo
- Work only inside the site's folder (
apps/<site>) with the repo's package manager. The repo's own agent rules come first.
Reference blocks
- Read one block (
kit_docs_getwithblock) for logic and contract, then write your own; the hooks and this kit win.
Errors, idempotency and rate limits
- The SDK owns Pay's
Idempotency-Key, 409 retries and one short 429 retry; after that, show its error with «Prøv igjen». Never retry an unknown errorcode.
Onboarding
- A restaurant without an Okam store signs up at https://backoffice.okam.no/?ny=1, then reconnects the MCP.
- When
storefront_connectanswersoriginAllowed: false, the restaurant asks its Okam contact to add the origin, then connects again. The sandbox key accepts anyhttp://localhostport.
