Build a storefront
This runbook takes you from a blank Next.js app to a completed checkout against your Cartbase store. It is written to be followed by a developer or handed to a coding agent as-is. Each step names the domain doc that carries the full contracts (shapes, curls, error codes, settings). Follow the steps in order, later steps assume earlier wiring exists. If anything here is unclear or wrong, it's a documentation bug, report it.
Already have an app, built with any tool? Read BRING-YOUR-OWN-STOREFRONT.md first: it takes that app onto the backend and points back here chapter by chapter.
What you need before starting: ONE value, the store's publishable key. Your Cartbase admin hands it out on the Storefront page (and lists it under Settings, API keys).
| Input | Example | Where it goes |
|---|---|---|
| Publishable API key | pk_… |
NEXT_PUBLIC_CARTBASE_PUBLISHABLE_KEY |
The key names the store on its own and scopes the catalog to the key's
sales channels. The API origin is the platform's, https://admin.cartbase.ai
(NEXT_PUBLIC_CARTBASE_URL only overrides it for a local or staging
platform). The store's id is not an input: hosted builds receive it, and
GET /api/store/store answers it for anything that needs it.
Sanity-check the store before writing any code:
# The regions listing is the cheapest liveness + auth probe.
curl -sf "$BASE/api/store/regions" -H "Cartbase-Key: $PUBLISHABLE_KEY" | grep -q '"regions"'Step 1: Scaffold + package
Create the Next.js app (App Router) and add the package:
# doc-noexec: scaffolding happens in YOUR repo, not against the API.
bunx create-next-app@latest my-store --ts --app --tailwind
cd my-store && bun add @cartbase/storefrontThe package is source-shipped TypeScript: add
transpilePackages: ["@cartbase/storefront"]tonext.configor nothing from it will compile.Styling is two imports and nothing else. Tailwind 4 is CSS-first, so there is no config file and no preset to register. In your
globals.css:@import "tailwindcss"; @import "@cartbase/storefront/theme"; /* The package ships TypeScript source, so Tailwind must scan it or the components render unstyled. */ @source "../../node_modules/@cartbase/storefront/src"; /* Dark mode is class-based: put `.dark` on <html>. */ @custom-variant dark (&:where(.dark, .dark *));The theme ships filled, so the store renders designed before you choose a single value. To make it yours, override the token values (
--primary,--background,--radius-base, the font families) after the imports. Never redefine the token names: components reference them, and the whole library repaints from the values alone.Pin the package version, storefronts never float
latest.Monorepo caveat: when the app lives in a workspace, set
outputFileTracingRootinnext.config, Next infers the root from the nearest stray lockfile, and a wrong root silently breaks page-segment hydration in dev (buttons render but nothing responds).
Step 2: The client seam
Construct ONE StorefrontClient per scope and pass it to every SDK call
(all SDK functions take the client as first argument, see any domain doc's
SDK line):
- Server, catalogue (
src/lib/store-client.ts): ONE client with the store's key and nothing about the visitor. It reads no cookie, so every catalogue read made with it can be cached and every page built from those reads is prerendered (Step 3). A store with customer prices or several languages keys its cached reads by the customer group or the locale, passed in as arguments; it never reads a cookie inside one. - Server, visitor (
src/lib/server-client.ts, checkout, account): construct per request;getLocalereads the locale cookie, andgetSessionTokenreads the store's session cookie (_cartbase_session,SESSION_COOKIEinlib/cookie-names) from the page request, so a server read is the signed-in customer's. Only behind a<Suspense>boundary. - Browser: construct once, on the store's own origin (below). The signed-in customer's session is an HttpOnly cookie the platform set on that origin, and the browser sends it with every call on its own: the account, the orders, the customer's prices and catalogue. The client holds no token.
Auth model (recap, full detail in auth.md):
Cartbase-Key always (it names the store and scopes the catalog
and carts to the key's sales channels; the SDK sends it for you); a
signed-in customer is the store's session cookie, set by the code sign-in
and sent by the browser (a password sign-in's authorization: Bearer <jwt>
is accepted too). x-client-id is the platform's own door and is accepted
in the key's place; the endpoint docs' curls use it because the docs
harness runs as the platform.
CORS (bites every browser client): the store API sends NO CORS
headers today, so browser-side SDK calls (cart drawer mutations, the
whole checkout orchestration) only work same-origin. Unless your
storefront is served from the Cartbase deployment origin itself, proxy the
store surface through your own origin, in Next.js one rewrite does it,
and give the BROWSER client window.location.origin as baseUrl
(server-side calls hit NEXT_PUBLIC_CARTBASE_URL directly and are
unaffected; see examples/storefront/next.config.ts for the working
rewrite):
// next.config.ts, proxy browser SDK traffic to the API origin
async rewrites() {
return [{ source: "/api/store/:path*",
destination: `${process.env.NEXT_PUBLIC_CARTBASE_URL}/api/store/:path*` }]
}Step 3: Store configuration bootstrap, and the prerendered store
Every page is a prerendered file on the CDN. The scaffold runs Next.js
Cache Components (cacheComponents: true and the catalog life in
next.config.ts), which is what makes a storefront fast.
- Every catalogue read (the store, consent, tags, menus, products,
collections, content, reviews) is a function in
src/lib/catalog.tsmarked"use cache: remote"withcacheLife("catalog")andcacheTag("catalog"), made with the catalogue client. The platform is asked once per two minutes per read, whichever server renders; a change in the admin reaches the store within that window. A failed read throws inside the cache, so an error is never stored as an empty answer; the public function decides what it reads as. - Keep the
catalogtag on every read of the store. A version is built once, and Publish switches your live address onto that build without building again, so its pages hold the store as the build read it. Right after the switch the platform marks everything taggedcatalogstale and visits the home page: a page is served as it was until it has read the store again behind a visit, a matter of seconds for the home page. A read without the tag is not refreshed at a publish; it follows its own cache life. - What belongs to one visitor renders behind
<Suspense>: the query (searchParams: sort, page, search, the product page's?variant=), the checkout's cart, a customer's account. A page passessearchParamsdown unread and the component inside the boundary reads it. - Dynamic routes list their pages with
generateStaticParams(every product handle, every collection handle), so the build prerenders them; a page added later renders on its first visit and is kept. - The build refuses a request read outside a boundary ("Uncached data was
accessed outside of
<Suspense>"). That error is the speed law doing its job: wrap the read, never switch the setting off. - A component never reads the query while it renders
(
useSearchParams): readwindow.location.searchwhen you need it, at the click or in an effect. The package holds itself to this with a test.
Fetch once at layout level, through src/lib/catalog.ts:
- regions.md, regions (the region_id for pricing + payment providers), currencies, supported locales.
- integrations.md,
GET /api/store/integrations: which carriers are enabled (pickup points/lockers for checkout), COD fee presence, and the tracking block (pixel/GA4/GTM/ads public ids). - consent.md, the CMP config for the consent banner.
Step 4: Layout: consent, tracking, navigation
Order inside <body> matters (contracts in components.md
and consent.md):
<ConsentInit required={consent.enabled}>FIRST child of body, synchronous, never awaits a fetch in the browser (first-hit consent race otherwise); the layout resolves the consent config on the server and passes the switch. A store that collects consent starts visitors denied until they choose; a store with the banner off starts them granted.<StorefrontTags config={tracking}>, every tag the store configured, fed by the integrations tracking block (a cached read insrc/lib/catalog.ts), never by env vars, each gated by the same switch (tracking.consent_required).- Navigation from menus.md,
main-menu/footerhandles; an unknown handle 404s and must render as "no nav", never crash.
The layout reads nothing from the request: no cookies(), no cart. The
cart drawer reads the stored cart id in the browser
(readBrowserCartId() handed to CartDrawerProvider as cartId) and the
cart after it, and <CartButtonClient /> with no cart counts the
drawer's cart. A layout that reads the cart cookie makes every page of the
store render per visit.
Step 5: Catalog
- products.md, listing + PDP. Always pass a pricing context
(
currency_codeorregion_id) or prices come back undecorated; rendervariant.calculated_price, fall back to baseprices[]. Never cache acalculated_priceresponse shared when a customer was signed in: prices vary by customer group, and on a key split by the B2B flag the catalogue does too (auth.md, What the login decides). The product page reads the product from the cache for the page and handsProductTemplatethe query as a promise (initialVariantId={searchParams.then((q) => q.variant)}): the buy box re-reads the product live behind its boundary, so price and stock are this minute's while the rest of the page is prerendered. - A sliding row in a browser component takes cards drawn on the server, never the products: a product is tens of kilobytes, and every prop of a browser component is written into the page.
- collections.md, collection pages use the membership
endpoint (
/collections/:id/products) which honors the admin's sort. - categories.md, category tree, tags, types.
- search.md, search page:
q+ facets from the response (render buckets, apply via the documented query params), typo-tolerant, synonym-aware. Related products on the PDP come from the same doc. - SEO:
seo_title/seo_descriptionfields with title/description fallbacks; path conventions are/products/<handle>,/collections/<handle>,/categories/<handle>.
Step 6: Content
- content.md,
/pages/<handle>and/blogs/<handle>routes; body HTML is server-sanitized, safe to render raw. Every store seeds policy pages (privacy-policy,terms-of-service,refund-policy,shipping-policy), link them in the footer. - metaobjects.md, merchant-defined content (size charts via the product, metafield, metaobject chain).
- redirects.md, call ONLY from your
not-foundhandler; 301 whento_pathis non-null. Never on regular page loads.
Step 7: Cart
carts.md: create the cart lazily on first add-to-cart with the
region + (optionally) sales channel; persist cart.id in a cookie
(writeCartCookie in the drawer's onCartChange, readBrowserCartId()
for its cartId, clearCartCookie for its onCartEnd); all cart
mutations return the decorated cart, totals are SERVER truth, render them
verbatim, never compute client-side. Line items, quantity updates, deletes,
and the customer-attach call after login are all in that doc.
gift-cards.md: the apply/remove endpoints + the three
decoration fields (gift_cards[], gift_card_total,
gift_card_remainder) your summary UI must render.
Step 8: Checkout
checkout.md is the authoritative sequence. In brief:
- The page is static:
<CheckoutClient client={browserClient} …/>and nothing else. The form paints with your header and the client reads the cart, the delivery methods and the tenders from the browser in one round after the paint. Nocookies(), no server await, no page refresh (checkout.md § The page). - List shipping options and payment providers with
cart_id: the server filters both through the merchant's checkout rules; your UI never hides methods on its own. The client does this for you; a store that lists on its server hands the lists in as feeds. - Carrier pickers (office/locker) come from the integrations config
(integrations.md); the chosen point goes into
carrier_metadata. - Buy click =
prepare-checkout(ONE call: address + shipping method + payment session at the final amount), then for card: StripeconfirmPayment(client_secret), thencomplete. For COD:completedirectly. Gift-card-covered carts skip the provider entirely. - Handle the documented failure codes (
checkout_method_hidden,account_required,gift_card_insufficient_balance, cart-vs-order union on complete), each has a UI recovery path described in the doc. sync-payment-amountafter any total-changing edit on the payment step;refresh-payment-if-terminalonly from Elementsloaderror/ aged-cart mount.- Order confirmation renders from orders.md
(
/orders/display/:displayIdembeds items, fulfillments, tracking).
Step 9: Customer accounts
auth.md: the email-code sign-in (request, then verify) signs
the customer into the store with an HttpOnly session cookie on the store's
own address; getSession on page load when the readable
_cartbase_signed_in cookie is there, signOut on the account page (forget
the cart with it). Right after the verify, attach the open cart
(setCartCustomer): it takes the customer's prices, and a B2B customer's
cart moves to the B2B channel. customers.md: profile,
addresses, issued documents (invoices); orders.md: the order
list, each row opening the order's own page at /order/{key}. Respect the
store's accounts mode (getStore().store.accounts.mode): required blocks
guest checkout with 403 account_required; disabled means render no
account UI at all (the code doors answer 403 accounts_disabled). Gate B2B
content on customer.account_status === "approved"; customer.b2b says
the customer is in the store's B2B group, whose catalogue and prices the
platform already serves them.
Step 10: Reviews
reviews.md: the PDP widget (/reviews/widget, aggregate +
first page + display options in one call) and the token wizard route for
email CTA links (/review/<token>): validate the token, then submit rating+body,
then the optional photo step mints the reward code. Resume rules are in the doc.
Step 11: Tracking events
components.md tracking section: fire client events via the
package helpers; Purchase MUST use eventID = "purchase_" + order.display_id so Meta dedupes browser Pixel against the server CAPI
event; write the attribution keys (fbp/fbc/anon-id/ga session) into
cart.metadata (consent-gated) so server events inherit them.
Step 12: Go-live checklist
- Pricing context passed on every catalog surface; no shared caching of a signed-in customer's responses.
- Consent banner renders for an unconfigured store (defaults are server-applied); tags mount only behind consent.
- Checkout completes: card (Stripe live), COD (fee renders from config), gift card (partial + full cover).
- Not-found handler consults redirects; policy pages linked.
- Order confirmation + emails render totals identical to the cart.
- Locale switching keeps cart + session; EUR everywhere.
- The store's publishable key (if any) is set, B2B catalogs are key-scoped and look "missing products" without it.
Step 13: Ship it
deploy.md: send the app to Cartbase hosting, permanent preview URL on every deploy, Publish to go live, deploy history as rollback. Hosted storefronts get the three inputs above injected automatically, so there is nothing to configure.