@zappie/sdk
v0.15.0
Published
Typed, framework-agnostic client for Zappie menus, carts, checkout, auth and events.
Readme
@zappie/sdk
The typed client for Zappie storefronts. Read a store and its menus, keep a cart on the shopper's device, get quoted totals from Zappie and hand payment to Zappie's hosted checkout. It runs in browsers, Node and Cloudflare Workers.
npm install @zappie/sdkUse it
Create a client with your publishable key and the store's slug, then share it with React through ZappieProvider:
import { createZappie } from "@zappie/sdk";
import { ZappieProvider } from "@zappie/sdk/react";
import { type ReactNode, useMemo } from "react";
type StorefrontEnv = { ZAPPIE_KEY: string; ZAPPIE_STORE: string };
export function Storefront({
env,
children,
}: {
env: StorefrontEnv;
children: ReactNode;
}) {
const client = useMemo(
() => createZappie({ key: env.ZAPPIE_KEY, store: env.ZAPPIE_STORE }),
[env.ZAPPIE_KEY, env.ZAPPIE_STORE],
);
return <ZappieProvider client={client}>{children}</ZappieProvider>;
}Any component inside can read the cart. Show Zappie's quoted total once it arrives, and the local subtotal until then:
import { format } from "@zappie/sdk";
import { useCart } from "@zappie/sdk/react";
export function CartTotal() {
const cart = useCart();
const total =
cart.state.status === "quoted" ? cart.state.quote.total : cart.subtotal;
return <span>{total ? format.money(total) : "Add an item"}</span>;
}Prices always come from Zappie. The cart shows a local estimate while it waits, and Zappie quotes the real total before checkout.
Entry points
| Import | For |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| @zappie/sdk | The client, the cart, money formatting and errors |
| @zappie/sdk/react | ZappieProvider and hooks such as useStore, useMenu and useCart |
| @zappie/sdk/checkout | Opening Zappie's hosted checkout and checking it completed |
| @zappie/sdk/checkout-defaults | The phone, address, region and time a signed-in checkout starts from |
| @zappie/sdk/customer and /customer/react | Signed-in customers, their orders and saved addresses |
| @zappie/sdk/in-venue and /in-venue/react | Tables: the scanned table, its menus, the shared bill, and the pages that serve them |
| @zappie/sdk/account | accountsUrl, a link to the shopper's Zappie account on the accounts portal |
| @zappie/sdk/integrations | Public integration IDs and browser keys |
| @zappie/sdk/places | Address search and delivery-zone checks |
| @zappie/sdk/pricing | An item's starting price, its price with given choices, and whether to show it as "From" |
| @zappie/sdk/display | Phone numbers spaced for reading, and what a branch calls an in-person order |
| @zappie/sdk/branches | The nearest branch to a shopper, and each branch's distance from them |
| @zappie/sdk/options | Option group rules: radio or checkbox, the group's limit, its labels and the note limit |
| @zappie/sdk/server | Server-side reads, storefront URLs, verifyWebhook(), menu snapshots and sign-in crypto |
| @zappie/sdk/template and /template/react | Template settings and responsive images for template authors |
| @zappie/sdk/error-pages and /error-pages/react | Zappie's page not found and something went wrong pages, for the site host's fallback |
| @zappie/sdk/site-error and /site-error/react | Your own 404 and error pages: which page, safe words, Try again and the home link |
| @zappie/sdk/site-closed | Your own closed page while the merchant has switched the storefront off |
| @zappie/sdk/navigation-progress | A line along the top of the page while a slow navigation runs, and the pressed state |
| @zappie/sdk/receipts | Receipt PDFs as files, and whether the device can share them |
| @zappie/sdk/testing | A mock client for your tests |
| @zappie/sdk/url | Storefront URL parsing and canonical redirects |
| @zappie/sdk/redirect | Same-origin validation for untrusted redirect targets |
Customer sign-in runs through Zappie's site host, so @zappie/sdk/customer works on sites Zappie hosts. Sign-in for a site you host yourself isn't available yet.
A menu snapshot is the SDK Menu with the facts an edge cache needs: the
store, the branch, the API's menu version and a content hash. Build one with
createMenuSnapshot() or menuSnapshotFromPayload() from @zappie/sdk/server,
and apply a sold-out patch to it with applyAvailability().
@zappie/sdk/server has the pieces that sign-in will be built from. They use Web Crypto only, so they run in Workers and Node 20 or later:
createPkce()andrandomToken()for the code challenge, state and nonce;sealValue()andopenSealedValue()to keep a value in an AES-GCM cookie, with secret rotation;createTokenVerifier()to check a token's signature against the issuer's published keys, and its issuer, audience, expiry and subject.verifyIdToken()also needs the sign-in's nonce and refuses an access token;SessionStoreandcookieSessionStore()to keep a signed-in session in a sealed cookie.
Make each sealing secret at least 32 random bytes, such as a value from randomToken(). Don't use a password or a phrase. The secret is hashed once with no stretching, so anyone holding one sealed value can test guesses offline.
cookieSessionStore() keeps the session in the cookie, not on your server. Signing out clears the cookie in that browser only. It doesn't invalidate a copied cookie, which still opens the session until it expires 30 days after sign-in. To end every session at once, rotate the secret. To end one session from the server, use a store that keeps sessions there.
import { createTokenVerifier } from "@zappie/sdk/server";
const verifier = createTokenVerifier({
issuer: "https://accounts.zappie.ai",
audience: clientId,
});
const claims = await verifier.verifyIdToken(idToken, { nonce });Your storefront draws its own page when a page is missing or fails. siteError
from @zappie/sdk/site-error turns what a route threw into the page to show:
not-found for a 404 or 410 and went-wrong for anything else, a safe heading
and message, Try again, which reloads the address, and a link home. It never
shows the thrown error's text. Pass your own words with copy. Throw a 404 from
your catch-all route to reach the not-found page. SiteErrorPage from
/site-error/react does the same as a render prop.
import { siteError } from "@zappie/sdk/site-error";
import { useLocation, useRouteError } from "react-router";
export function ErrorBoundary() {
const location = useLocation();
const page = siteError(useRouteError(), {
url: location.pathname + location.search,
});
return (
<main>
<h1>{page.title}</h1>
<p>{page.message}</p>
{page.retry && <a href={page.retry.href}>{page.retry.label}</a>}
<a href={page.home.href}>{page.home.label}</a>
</main>
);
}Zappie's own pages in @zappie/sdk/error-pages are for the site host, which
answers with them when a site can't answer at all. A Worker you host yourself
can return platformErrorResponse("went-wrong") when its handler throws.
When the merchant switches the storefront off, the site host asks your Worker
for each page with the closed state. Draw your own closed page in your header
and footer, with no bag, menu or checkout link. siteClosed(request) from
@zappie/sdk/site-closed returns { closed: true, message }, or null while
the store is open. message is the merchant's own words as plain text, or
null. siteClosedCopy(closed, copy) gives the heading and message to show:
the merchant's message when they set one, then your words from copy, then
"Closed for now" and "We're closed for now. Please check back soon." Mark the
page with markClosedPage(response). The host serves only a marked 2xx HTML
page, and it sets the status and cache headers itself. Anything else, such as
a page you didn't mark, gets Zappie's own closed page, so a shopper never sees
your full shop while it is off.
import { markClosedPage, siteClosed } from "@zappie/sdk/site-closed";
export default {
async fetch(request: Request, env: Env) {
if (siteClosed(request)) {
// Render / for every address, so no shop route runs.
const response = await handle(
new Request(new URL("/", request.url), request),
siteContext(env),
);
return response.ok ? markClosedPage(response) : response;
}
return handle(request, siteContext(env));
},
};Your root loader reads the same siteClosed(request) and draws the closed
page instead of the shop. The host asks only for GET and HEAD pages and waits
5 seconds for an answer.
NavigationProgress from @zappie/sdk/navigation-progress draws a thin line
along the top of the page while a navigation runs. It shows only once the
navigation has taken 150 ms (delayMs), so a quick one never flickers, grows
toward the end of the line while it waits, then fills it and fades out. With
reduced motion it is a still line while the navigation runs. Pass your router's
state as active and your brand colour as color. It also dims a link or
button the moment it's pressed, through a rule any of your own styles override.
Pass pressed={false} to leave that out. Import the stylesheet once, after your
theme's. useDelayedActive(active, delayMs) gives the same delay for anything
else that should wait before it shows.
import { NavigationProgress } from "@zappie/sdk/navigation-progress";
import "@zappie/sdk/navigation-progress.css";
import { useNavigation } from "react-router";
export function Shell({ children }: { children: React.ReactNode }) {
const navigation = useNavigation();
return (
<div>
<NavigationProgress
active={navigation.state !== "idle"}
color="var(--z-accent)"
/>
{children}
</div>
);
}Receipts come as PDF files. customer.receipt(orderId) reads an online order's
receipt, and receiptFile(url) from @zappie/sdk/receipts reads any receipt
address, such as a table bill's inVenue.receiptUrl(orderId). Hand the file to
navigator.share where canShareReceipt() says the device can share it, or link
to the address with download.
Pass any redirect target read from a query parameter through safeRedirect.
It keeps same-origin relative paths and returns your trusted fallback for an
external, malformed or unsupported target.
import { safeRedirect } from "@zappie/sdk/redirect";
return redirect(safeRedirect(searchParams.get("returnTo"), "/"));Use a publishable key (pk_test_… or pk_live_…) in browsers. Secret keys work only in @zappie/sdk/server. @zappie/sdk/internal is for Zappie's own packages and can change in any release.
Docs
Status
The SDK is at 0.x. Its API can change in a minor release while it settles. Each change is listed in CHANGELOG.md.
License
MIT
Quote fees
quote.feesTotal is the sum of quote.fees, so a template can print one
"Fees" line without adding money itself. It leaves delivery out (that is
quote.delivery) and is zero when there are no fees. Each quote line has
optionsTotal when the API prices its options.
Starting price
startingPrice(item) from @zappie/sdk/pricing returns the price an item starts from: the cheapest
available variant plus the cheapest valid choices of each required add-on group. A group that needs
exactly or at least four choices adds its four cheapest units, and a choice counts once unless the
shopper can set its quantity. It is the rule Zappie uses for a product's starting price. When no
variant is available, it uses the cheapest variant. showsFromPrice(item) says whether to show that
price as "From": available variants differ in price, or a required add-on raises it. item.price is
the branch price, not the starting price.
startingPriceWith(item, choices) is the starting price when the shopper picks from the given
choices only, such as one plan length: [{ groupId: "length", choiceId: "4-weeks" }]. An attribute
group narrows the variants, and an add-on group narrows its choices.
The API sends one available flag per item and variant, and a free-text
stockLabel. It doesn't say whether an item is sold out or unavailable for
another reason, so isAvailable covers both.
Phone numbers and in-person orders
formatPhone(phone) from @zappie/sdk/display spaces a number for reading:
formatPhone("+2348098226262") is "+234 809 822 6262". Link with the unspaced
number, as in tel:+2348098226262. It knows Nigerian and Ghanaian numbers and
returns any other number as given. Pass { country: "NG" } to read a number
written without a country code.
inVenueLabel(branch) says what an order placed at the branch is called:
"Walk-in" when branch.category is "RETAIL", and "Dine-in" otherwise.
Tables and bills
A guest who scans a table code lands on one of three pages the platform owns:
/pay-point/:id, /dine-in/menus and /dine-in/:order.
Mount InVenuePage from @zappie/sdk/in-venue/react at each of those paths,
before your catch-all, and pass it the path and query, your clients, your
router's navigate, your header and footer, and renderMenu. renderMenu
draws your own catalogue and item sheet. It renders inside a ZappieProvider
whose client is the table's, so useMenu() reads the table's menu and adding
an item fills the table's bag. Leave your own bag and checkout out of it. The
page brings the table's bag and Place order.
import { createInVenue } from "@zappie/sdk/in-venue";
import { InVenuePage } from "@zappie/sdk/in-venue/react";
const inVenue = createInVenue();
<InVenuePage
pathname={location.pathname}
search={location.search}
client={zappie}
inVenue={inVenue}
customer={customer}
navigate={(href, { replace } = {}) => navigate(href, { replace })}
header={<Header />}
footer={<Footer />}
renderMenu={() => <Catalogue />}
/>;Ordering and paying need a signed-in guest. A signed-out guest goes to sign in
and comes back to the same page, with the table's bag kept on the device, and
the order goes on as soon as they're back. Paying sends the guest to Zappie's
payment page with return set to the bill. Self-service and collect-payment
tables aren't served on storefronts. Scanning one says the table can't be used
on this site and sends the guest to staff.
Place routes
places.place(placeId, { branchId }) returns route with optional
distance_meters and duration_seconds, as the API sends them.
Maps browser key
createIntegrations().get() from @zappie/sdk/integrations returns optional
googleMaps: { browserKey: string }. The REST field is
google_maps: { browser_key: string } | null. An absent or null field returns
googleMaps: undefined, so apps can use this before the API field is deployed.
The SDK does not load Maps scripts.
Legacy redirects
storefrontRedirect(input, { installation }) from @zappie/sdk/url returns
string | null. Serve the target as a permanent redirect (301): a classic
URL has moved for good, so search engines carry its ranking to the site in one
step.
V2 URLs use item_ and ord_ public IDs, menu=menu_<id>, and category
anchors #c-cat_<id>. Already-prefixed IDs stay unchanged. Legacy cart,
checkout and sign-in overlays become routes. Unsupported legacy UI parameters
are dropped. Ad click IDs, ref, and every utm_* parameter retain their values.
Payment-return and printed QR routes retain their existing parameters.
Store and menu in one round trip
loadStoreAndMenu(client, request, options) from @zappie/sdk/server reads
the store and the menu of the branch a request is for, as resolveBranch
picks it, and returns { store, branch, chosen, mustChoose, menu }:
import { loadStoreAndMenu } from "@zappie/sdk/server";
const { store, branch, chosen, mustChoose, menu } = await loadStoreAndMenu(
client,
request,
{ cookie: "site_branch", fallback: env.ZAPPIE_BRANCH },
);When the link, the cookie or the fallback names the branch by ID (br_…),
the menu read starts alongside the store read, so the page waits for one round
trip instead of two. You get the menu once the store confirms that branch,
with the same errors as store.get followed by menu.get. A branch named by
slug starts early too once a store read in the same Worker isolate has given
that slug's ID. The first such request reads the menu after the store, because
the API takes branch IDs only. cookie is optional for a site that keeps no
branch cookie. requestedBranch(request, options) returns the raw value a
request names, link first, before you have the store.
Edge cache in a site Worker
On Zappie hosting each site runs as a Worker in a Workers for Platforms
dispatch namespace. There caches.default is disabled, and each Worker's
caches.open() cache is its own. @zappie/sdk/server keeps two kinds of
response in that cache, through openEdgeCache().
cachedApiFetch({ ctx }) is a fetch for createZappie on the server. It keeps
GET /store and GET /menus for as long as the API's own Cache-Control
says (s-maxage, then stale-while-revalidate). A stale read answers at once
and refreshes after the response through ctx.waitUntil, with the menu's ETag.
Its key is the URL, the API version and a hash of the publishable key, never
the key itself. A customer's, cart's, order's or quote's call, and any call
signed in as a shopper or carrying a cookie, goes straight to the API.
cachePage(request, render, { ctx, deployId, branchCookie }) answers a site
Worker's anonymous pages from the cache: documents, their .data, robots and
the sitemap, for as long as each response's Cache-Control says. Its key is
the full URL, the branch cookie's value, the deploy, and the site the host
names. It renders afresh for a request that isn't a GET, a draft, review or
preview, the closed state, an Authorization header and a session or sign-in
cookie. It keeps only a 200 that sets no cookie and isn't the closed page. A
cached HTML page gets a new CSP nonce in its policy and its markup for each
shopper. x-zappie-edge-cache says how each response was answered: HIT,
STALE, MISS or BYPASS.
import { cachePage, cachedApiFetch } from "@zappie/sdk/server";
const client = createZappie({
store,
key,
baseUrl,
fetch: cachedApiFetch({ ctx }),
});
export default {
fetch: (request, env, ctx) =>
cachePage(request, (fresh) => handle(fresh, siteContext(env, ctx)), {
ctx,
deployId: import.meta.env.ZAPPIE_DEPLOY_ID,
branchCookie: "site_branch",
}),
};Vite plugins
@zappie/sdk/vite holds the build and dev plugins a site uses.
zappieSource({ previewHost })marks elements with their source on the Studio dev server. On every dev server it also pre-bundles each browser entry of the installed@zappie/sdkand@zappie/foundations, and scans every module underapp/, so opening a page that imports an entry the session hasn't seen never re-bundles and reloads the preview.zappieWorker()minifies the site's Worker, renders it with React's streaming renderer alone, and setsimport.meta.env.ZAPPIE_DEPLOY_IDto a new id for each build. The browser's code is unchanged.zappieHoistImports()lists each route's chunks in its own file.zappieUploads({ host })serves the site's uploads on a local dev server.
Checkout defaults
@zappie/sdk/checkout-defaults fills in checkout contact details the way the
default storefront does, so every template follows one rule.
- Phone.
defaultPhone(typed, customer)keeps a number typed in this session. Otherwise it shows the signed-in customer's masked number withfromAccount: trueand nocontactPhone. Leavecontact_phoneout of the checkout and Zappie uses the customer's verified number. Show the masked number as a line or a placeholder, not as typed text. - Address.
defaultAddress()returns the last delivery address this shopper used on this device, otherwise the customer's first saved address. An address a guest used is offered only to a guest, and one a customer used only to that customer. Unless the fee type is"fixed", an address without a place ID counts as none. The cart's own delivery address always wins incheckoutDefaults(). - Remembering.
rememberAddress(address, storage, customerId)keeps the address line, place ID, coordinates and who used it inlocalStorage, on this device only, for that shopper alone. Pass the signed-in customer's ID, ornullfor a guest. Leave it out and the address belongs to whoever the page's customer client last saw signed in, and nothing is kept before the session answers.rememberedAddress()reads it back the same way. An address stored before it named its shopper is dropped, not offered.rememberAddress(null)forgets it. Both do nothing where storage is blocked. - Sign-out. The customer client forgets the remembered address on
signOut(), and whenever the session shows a guest or another customer, so a sign-out on another page or an expired session counts too.signOut()also takes the delivery address out of each bag saved on this device. The bag keeps its items and promo code and holds no fulfilment, so choosing delivery asks for an address again. A pickup bag is left as it is. - Region.
defaultRegion(branch, chosen)keeps a chosen region and otherwise picks the branch's only one. - Time.
restoreSchedule(fulfilment, branchId)keeps the cart's scheduled time when it belongs to this branch and parses. Drop it otherwise. - Applying.
prefillFulfilment(fulfilment, branch)fills the only region and drops a stale time. It never changes the fulfilment type or address, and returns the same object when nothing changes. - Sign-in.
watchCheckoutDefaults(customer, read, listener)publishescheckoutDefaults()now and again each time the shopper signs in or out. On sign-in it fetches/me/addressesfirst. On sign-out it forgets the address the customer used on this device.
import {
prefillFulfilment,
rememberAddress,
watchCheckoutDefaults,
} from "@zappie/sdk/checkout-defaults";
const stop = watchCheckoutDefaults(
customer,
() => ({ branch, fulfilment: cart.fulfilment, typedPhone: phone }),
(defaults) => {
setPhonePlaceholder(defaults.phone.display);
setAddressDraft(defaults.address);
const next = prefillFulfilment(cart.fulfilment, branch);
if (next && next !== cart.fulfilment) {
cart.setFulfilment(next);
}
},
);
// When the shopper picks a delivery address:
rememberAddress(address, undefined, customer.customer?.id);