Components
The component layer of @cartbase/storefront: what each family ships, the SDK
calls it requires, the admin settings that change its behavior, and its mount
rules. Every family runs on live stores.
This page has no executable curls, the endpoints these components consume are executably documented in their own domain files (integrations.md, consent.md, etc.); this page is the component-side contract that binds to them.
Import discipline: always import from the subpath
(@cartbase/storefront/tracking/meta-pixel, @cartbase/storefront/lib/money),
tree-shaking and Next.js RSC boundary detection both work better than via
barrels. Styling resolves against STOREFRONT theme tokens (bg-card,
text-foreground, …, shadcn-standard names), @import "@cartbase/storefront/theme" in the app's CSS supplies both the token names
and a filled default set of values, so components render designed out of the
box. No component hardcodes a colour; retheming means overriding values, never
renaming tokens.
Language: the library is English, a language is a pack
No component holds copy. Every string comes from a label pack, and the
library's own defaults are international English (products/labels,
checkout/labels, and so on, beside each family's type).
A language is one object covering every family, imported by its own subpath so a store bundles only what it ships:
import { es } from "@cartbase/storefront/locales/es"
import { StorefrontLocaleProvider } from "@cartbase/storefront/locales"
<StorefrontLocaleProvider locale={es}>{children}</StorefrontLocaleProvider>Shipping: locales/en, locales/es, locales/bg. Each is typed
StorefrontLocale, so a label added to the library breaks an incomplete
pack at compile time instead of falling back to English mid-checkout.
The provider mounts the three pure label contexts (products, checkout,
order), and the cart drawer, the reviews family and the account family read
the language from it directly, so every CLIENT component inside it speaks the pack with no
further wiring. What it cannot reach is a SERVER component: the store,
product and order templates render on the server, so each page hands them
their area of the pack, and that prop is REQUIRED. A page that forgets it
does not compile; PropLabelAreas in locales names the areas.
<StoreTemplate labels={STORE_LOCALE.store} />
<SearchTemplate labels={STORE_LOCALE.store} />
<CollectionTemplate labels={STORE_LOCALE.store} />
<CategoryTemplate labels={STORE_LOCALE.store} />
<ProductTemplate labels={STORE_LOCALE.products} />
<OrderCompletedTemplate labels={STORE_LOCALE.order} />STORE_LOCALE is the pack the store declared once in its config (en, or
bg, or es); the scaffold ships it that way. English is not a special
case: an English store passes en.store.
Failure copy is copy. What a shopper reads when an address, a payment, a
gift card or a discount code fails lives in the checkout pack too
(addressErrors, paymentErrors, giftCardErrors, promotionErrors).
The modules that recognize each failure keep their English patterns,
because those match the API's wire format and are never shown to anyone.
Overriding one word is a partial: every provider merges over the defaults.
Family: tracking (@cartbase/storefront/tracking/*)
The ad pixels and analytics tags a store configures, Consent Mode v2 and
the platform's own page view and presence beacons. The Cartbase split of duties:
this package fires client events and writes attribution; server-side CAPI /
GA4 Measurement Protocol sending is Cartbase-backend-owned (the
order.placed forwarder). The whole family is safe to render
unconditionally, every component renders nothing when its id prop is absent,
every helper no-ops outside the browser.
<ConsentInit required />: tracking/consent-init
- Purpose: the synchronous Consent Mode v2 "default" snippet: sets
gtag's consent default before any Google tag loads.
requiredis the store's consent switch (consent.enabledfromGET /api/store/consent). With it true a new visitor starts DENIED until they choose on the banner; with it false the store collects no consent and a new visitor starts GRANTED. A choice stored in_1c_consentwins either way. - SDK calls: none in the browser. The layout resolves the consent config on the server (it fetches it for the banner anyway) and passes the switch; the script must NEVER wait on a fetch (async default = first-hit consent race).
- Mount rules: FIRST child of
<body>in the root layout, before any tag component. Plain inline<script>by design (not next/script). The prop is REQUIRED: neither default is safe, so a layout must say what the store does, and one that does not fails to compile. - Settings: the consent card's
enabled(admin, Settings, Consent).
<ConsentBanner copy layout privacyHref rejectOnFirstLayer />: tracking/consent-banner
- Purpose: the built-in two-layer CMP UI; writes the
_1c_consentcookie and applies the livegtag('consent','update')+fbq('consent'). - SDK calls:
GET /api/store/consent(via@cartbase/storefront/api/consent) for the store's config; passcopy = pickConsentCopy(consent.copy, locale), pluslayout/privacy_href/reject_on_first_layerfrom the payload. - Mount rules: mount ONLY when
shouldRenderBanner(consent)(i.e.enabled && mode === "builtin"). Inmode: "external"render nothing, the merchant's CMP must write the same_1c_consentcookie or callsetConsent(); all gating keeps working off that one seam. z-index isz-[70](above the cart drawer'sz-[60]). - Settings: the consent card config (admin, Settings, Consent):
enabled,mode,layout(modalblocks + scroll-locks;banner-bottomis non-blocking and must not trap focus),privacy_href,reject_on_first_layer, per-localecopy. - Also ships
<ConsentSettingsLink>(footer link that re-opens the settings layer, "withdraw as easily as given") and the pure<ConsentBannerCard>.
<MetaPixel pixelId consentRequired />: tracking/meta-pixel
- Purpose: injects fbevents.js, pushes the consent state BEFORE
fbq('init')(pre-init revoke = Pixel queues events until grant), fires the initial PageView. The state is the store's default overridden by the visitor's stored_1c_consentchoice: revoked on a store that collects consent, granted on a store with the banner off. - SDK calls:
getTrackingConfig(client)(tracking/get-tracking-config, wrapsGET /api/store/integrations, readingtracking.facebookPixel.pixelIdandtracking.consent_required). - Mount rules: root layout, after
<ConsentInit>;<StorefrontTags>mounts it with both props from the block. Renders nothing whenpixelIdis falsy.consentRequiredis REQUIRED for the reason<ConsentInit>gives, and so it is on<TikTokPixel>and<ChatGptPixel>, the two other tags that gate their own SDK. Google needs no prop: it reads the<ConsentInit>default. - Settings: admin Integrations hub
facebook_capirow (enabled+credentials.pixel_id); consent cardenabledbecomesconsent_required. - Companion:
updatePixelAdvancedMatching(visitor), call from checkout / signup as PII becomes known; hashes em/ph/fn/ln/ct/st/zp/country (SHA-256, Meta normalization) and re-inits the Pixel so every subsequent event carries Advanced Matching. Also persists raw values forgetKnownVisitor().
<GA4 measurementId />: tracking/ga4
- Purpose: loads gtag.js +
gtag('config'). gtag then owns the_ga/_ga_<MEASUREMENT_ID>cookies thatgetTrackingAttribution()later reads. - SDK calls:
getTrackingConfig(client), readingtracking.ga4.measurementId. - Mount rules: root layout, after
<ConsentInit>(the consent default governs whether gtag writes cookies or sends cookieless pings). Renders nothing when falsy. SPA route changes are NOT auto-tracked, firepage_viewfrom a route-change effect if per-route views are wanted. - Settings: Integrations hub
ga4row (credentials.measurement_id); consent card.
<KlaviyoTag publicKey />: tracking/klaviyo-tag
- Purpose: Klaviyo's onsite script for a store that saved its public
API key in the admin. Without a key it renders NOTHING: no element, no
script, no request, and the Klaviyo helpers find no
klaviyoobject and return at once, so a store without Klaviyo pays nothing for the integration being in the package. With a key it renders one inline script that queues calls and loads klaviyo.js from Klaviyo's CDN on every page, which from then on tracks Active on Site by itself, renders their forms and popups, and recognises a visitor arriving from a Klaviyo email. - SDK calls:
getTrackingConfig(client), readingtracking.klaviyo.publicKey. - Mount rules: root layout;
<StorefrontTags>mounts it with the key from the block. Klaviyo sits OUTSIDE the store's consent gate (0.31.1): the tag loads and the helpers send whatever the cookie banner says; the ad pixels beside it keep their gate. - What fires, and from where:
trackProductViewsends Viewed Product (and the recently-viewed entry their emails list);trackCartAddsends Added to Cart with the whole cart and the link that reopens it;trackCheckoutStartsends Started Checkout for a browser Klaviyo already knows, and the checkout funnel identifies the shopper the moment their email is typed and sends it then, once per cart. Nothing browser-side sends an order: Placed Order, Ordered Product, Fulfilled, Canceled and Refunded Order and the customer's profile go from the platform under the private key. - The link that reopens a cart: every Klaviyo cart event carries
CheckoutURL,{origin}/checkout?cart=<id>. The checkout adopts a cart named in its address and writes it as the cookie (useBrowserCartId), so an abandoned cart mail opens the shopper's own cart on any device. - Settings: admin Integrations hub
klaviyorow: the public key runs this browser half; the private key adds the server half, and a save with only the private key resolves the public one from Klaviyo's account. - Companion helpers (
tracking/klaviyo):klaviyoIdentify(person),trackKlaviyoViewedProduct,trackKlaviyoAddedToCart,trackKlaviyoStartedCheckoutOnce,checkoutLinkFor(cartId).
Client events: tracking/events (use this one)
ONE call per commerce moment, every vendor at once. Reach for these rather than the per-vendor helpers below, because the failure they prevent is the common one and it is invisible: a store adds a vendor, updates three of the four call sites, and an ad account optimises on partial data for a month before anyone notices.
| Step | Call |
|---|---|
| Product view | trackProductView({ line, currency, value }) |
| Add to cart | trackCartAdd({ line, currency, value, cart? }) |
| Checkout start | trackCheckoutStart({ lines, currency, value, coupon?, cartId?, checkoutUrl? }) |
| Address complete | trackCheckoutShippingInfo({ lines, currency, value, cartId, shippingTier?, coupon? }) |
| Tender chosen | trackCheckoutPaymentInfo({ lines, currency, value, cartId, paymentType?, coupon? }) |
| Order confirmed | trackOrderPurchase(order, trackingConfig) |
A line carries the catalogue key, the variant, the title, the quantity
and the unit price, and may carry url, imageUrl, sku and
categories: what an email needs to show the product (Klaviyo reads them,
the ad vendors do not).
Every moment fires on its own. The product view is
reported by useProductActions when the buy panel mounts on the product
page (trackView, on by default, off with syncAddress: false for a
quick-buy card). The add to cart is reported by the cart drawer's addLine,
the one door every add passes through, from the cart the platform
confirmed, with the whole cart for Klaviyo. The three checkout moments come
from useCheckoutFunnel, mounted by useCheckoutOrchestration. A store
calls these by hand ONLY on a path that bypasses those doors (its own
addToCart server action, its own checkout), and never beside them, or
the moment counts twice.
cartId is not decoration: the mid-funnel steps are driven by form state
rather than by a click, so their Meta event id is DERIVED from the cart
(checkoutStepEventId, tracking/once). Two tabs on one cart, a restored
session or a retried request then collapse into one event instead of three.
Pair it with markFiredOnce(event, cartId) if you fire them yourself.
A line is { productId, variantId?, title, quantity, price }. Pass the
PRODUCT id: Meta's content_ids, TikTok's content_id and the catalogue
feed's <g:id> must be the same value or the event matches no catalogue
entry, which costs dynamic ads on both platforms. GA4 is keyed by variant
instead, on purpose, and these helpers do that split for you.
trackOrderPurchase takes the tracking config as its second argument
because Google Ads only fires when the store configured BOTH the account id
and the purchase label. Pass order.metadata.customer_type through as
customerType when present: it is computed once server-side, so the
browser and the server tell Google and TikTok the same thing.
Per-vendor helpers: tracking/fbq, tracking/gtag, tracking/ttq, tracking/google-ads
Call on the matching funnel step; all are no-op-safe (SSR, blocked, absent tag).
| Step | Meta (fbq.ts) |
TikTok (ttq.ts) |
GA4 (gtag.ts) |
|---|---|---|---|
| Product view | trackViewContent |
trackTikTokViewContent |
trackGAViewItem |
| Add to cart | trackAddToCart |
trackTikTokAddToCart |
trackGAAddToCart |
| Checkout start | trackInitiateCheckout |
trackTikTokInitiateCheckout |
trackGABeginCheckout |
| Address complete | trackAddShippingInfo |
none | trackGAAddShippingInfo |
| Tender chosen | trackAddPaymentInfo |
trackTikTokAddPaymentInfo |
trackGAAddPaymentInfo |
| Order confirmed | trackPurchase(data, order.display_id) |
trackTikTokPurchase({…, displayId}) |
trackGAPurchase({transaction_id: String(order.display_id), …}) |
| Newsletter/popup signup | trackLead |
none | none |
Two gaps in that table are deliberate. AddShippingInfo is not in Meta's
standard vocabulary, so fbq takes it through trackCustom; TikTok has no
shipping-step event at all, and a custom one there would optimise nothing
and report nowhere.
Google Ads has one event, the purchase conversion:
trackGoogleAdsPurchase({ sendTo, value, currency, transactionId, newCustomer? }),
with sendTo from googleAdsPurchaseSendTo(config) (null when the label
is not configured, skip the conversion rather than fire a malformed
send_to, which Google accepts and silently drops).
THE Purchase dedupe contract (must never drift; mirrored on the platform's server side):
- Meta: browser Pixel
eventID="purchase_" + order.display_id: the exact id the backendorder.placedCAPI Purchase uses.trackPurchase()builds it from the caller'sdisplay_idso the format cannot drift. Meta dedupes by event_name + event_id (~3 days). - TikTok: browser pixel
event_id="tt_purchase_" + order.display_id, the same id the backend Events API Purchase sends. Thett_prefix keeps it from colliding with Meta's on a page carrying both pixels. TikTok dedupes on event_source_id + event + event_id and discards duplicates for 48 hours; the backend ALSO carries an idempotency flag, because 48 hours does not cover an order email opened on day four. - GA4:
transaction_id = String(order.display_id)on both browser event and backend Measurement Protocol, GA4 dedupes by transaction_id natively. - Google Ads:
transaction_idagain, the same value. Never send it empty: an empty transaction_id dedupes nothing, so every re-open of the confirmation page counts another conversion. - The browser fires the purchase once, whatever a vendor dedupes:
<TrackOrderPurchase>fires once per order, in the browser that placed it: the checkout's Place order marks the order (markOrderPlaced,tracking/placed-order) and the order's page fires only on consuming that mark, so the order email's link, a reload, the merchant opening the page or another device fire nothing. A checkout of your own callsmarkOrderPlaced(order.display_id)whencompleteCartanswers, or the page never fires. - All other events get
<eventname>_<unixSeconds>_<6hex>ids (generateEventId).
setEnhancedConversions(input) (gtag.ts), Google Ads Enhanced Conversions
for Web: hashes email/phone/names client-side and gtag('set','user_data',…).
Call alongside updatePixelAdvancedMatching at checkout. The phone is
normalised to E.164 WITH the plus, which is NOT the digits-only string Meta
wants: two vendors, two normalisers, and merging them re-creates a defect
that fails silently and costs match rate with nothing in any log.
Attribution: tracking/attribution, tracking/get-tracking-attribution, tracking/use-engagement-time
- Browser side (call from a top-level client component, e.g.
TrackInit):captureUtmsFromUrl()(first-touch_1c_utm_first365d, last-touch_1c_utm_last90d),getOrCreateFbp()/getOrCreateFbc()(defensive_fbp/_fbcwrites so the Pixel-load race never ships empty match keys, production fix),getOrCreateAnonId()(_1c_anon, the guestexternal_id),initEngagementTime(). - Server side, at checkout completion:
getTrackingAttribution(clientHints?, opts?)reads the cookies + headers and returns theTrackingAttributionkeys to write intocart.metadata(CONSENT-GATED, only when the visitor's choice allows). Cart completion copies them toorder.metadata; the backend forwarder inherits fbp/fbc/anon-id/ga signals from there. Pass{ engagementTimeMsec: getEngagementTimeMsec() }as clientHints, and eitheropts.ga4MeasurementIdoropts.clientso the_ga_<id>session cookie can be located. - Browser side, at the checkout:
readBrowserAttribution()returns the same flat keys from the cookies a client component can read (the Facebook pair, the visitor id, both UTM tuples, every ad-click id). The checkout funnel writes them onto the cart for you at checkout start, so a store needs none of this by hand; it exists because a checkout is a client component and the server reader cannot run there. The server reader stays the authority for the request facts it alone sees (user agent, IP, referer, GA session), and the two payloads merge by key. - Whether any of it is written is
consentDecision()(tracking/consent): the visitor's stored choice, and before they make one, the store's own default (a banner means nothing until they agree; no banner means the store collects none).CONSENT_CHANGED_EVENTfires onwindowwhenever a decision is applied, by the built-in banner or an external CMP throughsetConsent, so a surface that must ACT on consent can hear a later Accept instead of reading once and missing it. - Settings: Integrations hub rows (which signals exist), consent card (whether capture happens).
Family: primitives (@cartbase/storefront/primitives/*)
Generic shadcn-style building blocks. No SDK calls, no admin settings, pure UI over the theme tokens.
primitives/field:<Field label … />: floating-label input (checkout house style) with thepulseattention cue (soft blue 2-cycle pulse, distinct from focus/error, production UX fix).primitives/select-field:<SelectField label>…options…</SelectField>: floating-label native select (native mobile keyboards).primitives/ui/*: shadcn-standardbutton(cva variants incl.default/destructive/outline/secondary/ghost/link),input,label,select,dialog,sheet,tabs,accordion,collapsible,popover. Radix-backed, ported verbatim; import per file.- Mount rules: all are
"use client". Requires the Tailwind preset tokens.
Family: lib (@cartbase/storefront/lib/*)
Pure helpers, no React except price, no fetches. The SDK never
invents server truths: prices/totals arrive computed from the API
(variant.calculated_price, cart.total); these helpers only select and
format.
lib/utils:cn()(clsx + tailwind-merge).lib/money:convertToLocale({amount, currency_code, …})Intl currency formatting (amounts are decimal EUR major units per the store contract);noDivisionCurrencies.lib/price:<Price amount currencyCode className />: the amount in its own currency, formatted throughconvertToLocale. Every price in the library renders through it. It shows ONE currency; a store that wants a second one displayed adds it in its own locale layer rather than in every price.lib/cart-helpers:isProductLine/isFeeLine/productTotal/productItemCount/findFeeLine+COD_FEE_METADATA_KEY. THE single source of truth for hiding the backend-injected COD-fee line in cart surfaces while checkout/order totals show it as its own row. Affected by: COD settings (whether a fee line ever appears).lib/get-product-price:getProductPrice({product, variantId})/getPricesForVariantgives a formattedVariantPrice(cheapest + selected) from server-computedcalculated_price. Reads Cartbase's flatprice_list_typewith a legacy nested shape as fallback. Affected by: price lists / B2B pricing context (whatcalculated_pricecontains), currency + region query context.lib/get-percentage-diff: sale badge math.lib/product:isSimpleProduct(skip the option selector for one-option-one-value products).lib/sort-products: client-side re-sort of a fetched page (price_asc|price_desc|created_at); the API'sorderparam stays the authority for paginated listings.lib/payment-constants:isStripeLike/isPaypal+paymentInfoMap. Two tender shapes since the pp_* kill: a processorprovider_id(pp_stripeexact, plus the earlierpp_stripe_*spellings as fallbacks) or a merchant METHOD rendered by its snapshot NAME, a method never has a provider id to bucket. Affected by: connected processors + enabled methods + checkout rules (which entries ever reach the client).lib/store-api-error:storeApiError(err): display-boundary normalizer (capitalized message + terminal period). CatchStoreApiErrordirectly instead when branching onstatus/code.lib/format-label:formatLabel(template, vars)fills a label's{slot}words ("Order {number}"); a slot with no value stays as written.lib/hooks/use-intersection,lib/hooks/use-toggle-state, viewport + toggle micro-hooks (client).
Family: checkout (@cartbase/storefront/checkout/*)
The full checkout page family: a deferred-intent architecture (no payment session exists until the Buy click) over the Cartbase orchestration endpoints. The flow every component serves (executable ground truth: checkout.md):
listShippingOptions(cart_id)andlistPaymentProviders(cart_id)render the pickers.- The Buy click calls
prepareCheckout(one call, one write: everything or nothing). pp_stripe:stripe.confirmPayment(client_secret); a merchant method skips this step.completeCart, then navigate to the confirmed page.
Amounts are EUR major units and SERVER truth, components render totals,
never compute money; the only client-side arithmetic is the optimistic
display overlay (shipping/COD-fee prediction) that the server value
replaces at prepare. All user-facing copy flows from CheckoutProvider
labels (English by default; a language is a pack from locales/*); errors surface
code-first through the error-copy maps, never raw API strings.
<CheckoutProvider labels orderConfirmedPath />: checkout/context
- Purpose: supplies labels + the order-confirmed path template
(
{key},{number},{id},{country}substitution) to every checkout primitive. - SDK calls: none.
- Mount rules: wrap the checkout page (or any custom composition).
The scaffold passes
"/order/{key}": the order's public page, the key minted with the order, the same address every order email links (orders.md). The default template keeps the older"/{country}/order/{id}/confirmed"shape for stores whose URL structure includes a country segment. - A nested provider inherits: mounting a second one, which is what
you do when you set
orderConfirmedPathon a page inside aStorefrontLocaleProvider, keeps every label from the provider above and changes only the keys you name. The same holds forProductLabelsProviderandOrderLabelsProvider. - Settings: none (labels come from the store's locale pack).
useCheckoutOrchestration(options): checkout/use-checkout-orchestration
- Purpose: THE hardened checkout state machine: address form + debounced autosave, shipping/payment selection (client-state-only pre-Buy), carrier metadata, optimistic totals, the atomic Buy click, 3DS-return handling, completed-cart detection.
- The typed form survives a refresh: the form is kept in
the tab's own sessionStorage (
cartbase:checkout-form), restored after mount into EMPTY fields only, so what the server knows (the cart's address, a signed-in customer's) always wins, and cleared when the order is placed. Storage that throws never breaks a checkout. - The way back from a payment redirect is one screen:
usePaymentReturnknows it from the first paint, the orchestration pauses the listings and the funnel,CheckoutClientrendersCheckoutReturnScreen("Confirming your payment", the label pack'sreturnTitle/returnText/returnFailedTitle/returnFailedText) until the browser leaves for the confirmation; the return asks the platform again oncart_lockedand offers Try again after its own retries (redirectReturn,retryReturn). - A completed cart is forgotten everywhere: the tab that
placed the order already cleared the cart; a second tab or the back
button now clears it too the moment the hook sees
completed_at, so the next Add starts a new cart instead of being refused by a placed one. - The funnel fires itself: the hook mounts
useCheckoutFunnel: begin_checkout on arrival, add_shipping_info when contact and address are complete, add_payment_info when the tender is settled, each once per cart to every configured tag; the ad platforms' identity signals (updatePixelAdvancedMatching+setEnhancedConversions) as the fields are typed, with the shopper's own country rather than a constant; and the ad-click ids written onto the cart so they reach the order.trackFunnel: falsefor a store that fires its own. - Nothing left to pay:
nothingToPay/amountDueon the returned surface: a promotion that covered the order, or gift cards that cover the whole total. The Buy click then skips Stripe from the start, and<CheckoutPaymentMethodList nothingToPay>offers no tender at all. - SDK calls:
carts.updateCart(address autosave + tracking metadata),customers.updateMe(best-effort profile sync incl. Cartbase's first-classcompany_name/company_eik),checkout.calculateShippingOption(calculated-rate forward-compat),checkout.prepareCheckout,checkout.syncPaymentAmount(exposed + fired on payment-tab switch with the newprovider_id),checkout.refreshPaymentIfTerminal(exposed, call REACTIVELY from Elementsloaderroronly), the server-evaluated payment availability map fromcheckout.listPaymentProvidersso delivery-option payment rules update synchronously; a prospective-option request is the fallback for older hosts,carts.completeCart. - Props contract:
{client, cart, customer, availableShippingMethods, availablePaymentMethods, paymentMethodsByShippingOption?, countryCode?, countries?, paymentMethodFilter?, orderConfirmedPath?, onOrderPlaced?, resolveTrackingMetadata?, logError?}.countriesis OPTIONAL and is an override: omit it and the hook callsGET /api/store/countriesitself, so the address form offers the countries the store's Markets declare, or the whole catalogue when it declares none. A failure to load the list never blocks a checkout: it falls back tocountryCodeand reports throughlogErrorascountry_list_failed. Fee prediction is never hardcoded: each method LISTING entry carries its ownfee_amount/fee_label.logErroris the one log writer. Returns the full orchestration surface (performBuyClick,optimisticTotal(Cents),deliveryReady, …). - Cartbase specifics: zero-remainder gift path:
prepareCheckoutreturningclient_secret:null+provider_id:null+payment_method_id:nullSKIPS Stripe and completes on the gift session (gift-cards.md). Processors arepp_stripeexactly; merchant methods list as{payment_method_id, name, kind, instructions, fee_amount, fee_label}entries, the COD-kind method wins the offline tab, else the first manual method. The charged fee reads the cart-levelpayment_method_fee_totaldecoration. - Settings: checkout rules (filter the listings + complete guard),
the methods' own fee configuration (Payments settings), Stripe
credentials, gift cards,
accounts_mode.
The checkout's concerns, each its own import: checkout/use-checkout-*
useCheckoutOrchestration is the COMPOSITION of nine hooks, one per
concern. A store that keeps the package's layout never sees them;
a store composing its own checkout imports the ones it keeps and replaces
the ones it does not, and every one has its own suite. The rule between
them: the cart is read ONCE, by useCheckoutCart, and every other concern
takes it as an input; nothing writes to the cart before Place order except
notes, through useCartNotes.
| Import | What it owns | Locked? |
|---|---|---|
checkout/use-checkout-error-log, useCheckoutErrorLog({client, override?}) |
Where failures go: the platform's checkout error log by default, the store's sink when given. Returns logError, a ref of it, and the cart-id ref every report carries. |
open |
checkout/use-checkout-feed, useCheckoutFeed(feed, read, onFailure), useBrowserCartId() |
One feed followed: loading, ready or failed, last good value kept, single-flight newest-wins reads, retry, adopt. |
open |
checkout/use-checkout-cart, useCheckoutCart({client, cart?, delivery?, payment?, legacy props, logError}) |
The cart and the two listings in one round; cartStatus, cartLoaded, knownCartId, adoptCart, reloadCart; the quiet re-read on visibilitychange; a cart completed elsewhere forgotten here. EMPTY_CART until the shopper's arrives. |
open |
checkout/use-cart-notes, useCartNotes({client, cart, cartLoaded}) |
The checkout's notes on the cart's metadata (_checkout_*, the company fields, the attribution) as ONE union writer: the platform replaces metadata wholesale, so every write carries the cart's metadata as last read plus every key this tab wrote. remember (queued, coalesced), compose (for a write that carries metadata beside other fields), write (now, awaited). |
open |
checkout/use-checkout-address, useCheckoutAddress({client, cart, cartLoaded, customer, countryCode?, countries?, errorCopy, logError, notes}) |
The form and its fill order (typed, then the cart, then the tab's storage), the 600 ms debounced save with the billing mirror, blur, the in-flight guard, the store's country list, saved addresses, the idle cue, the committed snapshot a carrier may price. | open |
checkout/use-checkout-delivery, useCheckoutDelivery({client, cart, cartLoaded, shippingMethods, address, logError, notes}) |
The courier and the point, remembered under the checkout's own keys; the live quotes (asked once the address is committed, again when the destination or the parcel changes, never for an address since changed; a refused quote disables its row alone, single-flight retry); optimisticShippingCost derived from the selection; deliveryReady; repriceAll() reads the listing and asks every courier again (the composition calls it when the platform answers total_changed). |
open |
checkout/use-checkout-tender, useCheckoutTender({client, cart, cartLoaded, listing, selectedShippingMethod, selectedShippingOption, paymentMethodFilter?, logError, notes}) |
Which tenders are offered (the per-delivery map on the same render, the rules door for a delivery the map does not know, the store's filter on top), the card only when the browser can mount it, the merchant's order, WHICH is selected (the click, the remembered one, the merchant's first), optimisticMethodFee derived, the after-prepare session sync. |
open |
checkout/use-checkout-totals, useCheckoutTotals({cart, optimisticShippingCost, optimisticMethodFee}) |
optimisticTotal, optimisticTotalCents, amountDue, nothingToPay, all from checkoutTotals, the one formula the summary and the mobile bars read. |
open |
checkout/use-checkout-selection-totals, useCheckoutSelectionTotals({client, cart, cartLoaded, shippingMethods, calculatedPricesMap, committedDestination, selectedShippingMethod, tenderKey, paused?}) |
The platform's total for every delivery with every way to pay, in one answer (getSelectionTotals), asked when the prices land, the cart's own totals change or the destination moves, never at a click; selectionTotal is the figure for the choice on screen, null until the current table has arrived (an older one is never shown); refresh() asks again. |
open |
checkout/use-checkout-buy, useCheckoutBuy({client, cart, cartLoaded, address, delivery, tender, nothingToPay, expectedTotal?, onTotalChanged?, notes, resolveTrackingMetadata?, onOrderPlaced?, orderConfirmedPath, logError, telemetry?, errorCopy, debug?}) |
Place order: flush the address, the attribution before prepare, the card form's own check, ONE atomic prepare, confirm with the secret (skipped when nothing is left to pay), complete, forget the cart; the return from a bank challenge; syncPaymentAmount, refreshPaymentIfTerminal; one order per intent however many clicks. expectedTotal is the platform's own total for the choice on screen (selectionTotal.total, never the page's arithmetic): it rides prepare as expected_total, and when the platform answers total_changed nothing is placed, onTotalChanged runs (the composition reads the cart, the courier prices and the table again) and the shopper reads the label pack's paymentErrors.totalChanged. |
LOCKED: compose around it, never reimplement it |
The pure rules the concerns hold are exported beside them:
checkout/address-snapshot (the required fields, the form and cart
snapshots), checkout/calculated-rates (when a carrier may be asked, which
answer may be shown), checkout/selection-prices (the two rows and the
selected tender, from the selection).
<CheckoutClient />: checkout/checkout-client
- Purpose: the assembled single-page checkout layout over the hook + every component below. Stores wanting a custom layout compose the same hook + primitives instead.
- SDK calls: everything the hook + summary widgets call; the host
fetches
listShippingOptions/listPaymentProviders(+ customer, +getIntegrationsConfig().cod) and passes them down. - Props contract: hook options +
showGiftCards?,showSecureCheckout?,paymentMarks?,termsContent?,logoByFulfillmentOptionId?, Stripeappearance/fonts,onCartChange?(receives every decorated cart from summary mutations; the layout also re-runssyncPaymentAmounton those). - Mount rules:
"use client"; insideCheckoutProvider; redirect server-side whencart.completed_atis set (the hook also flagscartIsCompleted).
<PaymentWrapper cart amount /> + Stripe scope: checkout/payment-wrapper, checkout/stripe-wrapper
- Purpose: deferred-intent Stripe context:
PaymentWrapperpublishes{stripePromise, amount, currency, appearance, fonts};StripeElementsScopemounts<Elements mode:"payment">where needed (passthroughrenders children scope-less on COD-only stores);StripeContextboolean = "Stripe.js ready". - SDK calls: none. The KEY comes from the store: the
pp_stripeentry ofGET /api/store/payment-providerscarriespublishable_keyand, for a Connect store,account_id, andCheckoutClientpasses them aspublishableKey/stripeAccountId. Under Connect the key is Cartbase's and the account is the merchant's, so this pair only exists on the platform: connecting Stripe in the admin is the whole setup and a storefront configures nothing. When the merchant turns the store's Test mode switch on (Settings, Payments, Stripe), the same entry carries the platform's test key with the same account: Stripe's test cards work, nothing is charged, and the storefront still configures nothing.NEXT_PUBLIC_STRIPE_KEYandNEXT_PUBLIC_STRIPE_ACCOUNT_IDremain the fallback, as a PAIR, for a storefront running its own Stripe outside the platform. - How the card is kept: the same entry carries
card_setup_future_usage(on_sessionoroff_session), the platform's word on how a card paid with is kept on the shopper's Stripe customer.CheckoutClientpasses it ascardKeeping, the form mounts with it (paymentMethodOptions.card.setup_future_usage), holds it for as long as it is mounted, and the Buy click sends the same on prepare-checkout, so the payment the platform creates matches the form. A storefront never chooses the value: a store mountingPaymentWrapperby hand passes what the listing says. Without it the form asks nothing (docs/storefront/checkout.md,card_setup_future_usage). - Mount rules:
PaymentWrapperwraps the page ONCE withamount={optimisticTotalCents}(cents at this Stripe boundary only);StripeElementsScopelives INSIDE the payment section so a session rotation never tears down the form/tracking tree. - Settings: Stripe integration (whether
pp_stripeis ever listed). - A card with no key is not offered.
resolveCardOffer(checkout/card-offer) reads the entry and the fallback together; without a publishable key Stripe.js never loads, so the tab would sit on a skeleton for ever. The orchestration hook hides it and reportscard_unmountableto the merchant's checkout error log instead.
<CheckoutAddressForm /> (+ <AddressSelect />, <CompanyDetails />): checkout/address-form, checkout/address-select, checkout/company-details
- Purpose: email + delivery address (floating-label
Fields, 3s-idle pulse cue), saved-address picker, collapsible BG company-invoice fields (name/VAT/MOL/address intocart.metadata+ customer profile). - SDK calls: none directly; the hook autosaves via
updateCart/updateMe. Saved addresses come fromcustomers.getMe()throughaddressesInRegion. - Props contract: everything from the hook (
formData,handleFormChange,handleFieldBlur,regionCountries,addressInput,addressError,pulseFields);hideCountry?for single-country stores. The country field is a NATIVE select carrying the chosen country's flag, and it keepsautocomplete="country"on purpose: a custom listbox would draw a flag per row but lose browser autofill and the phone's own picker, and a checkout does not trade autofill for decoration. A list of exactly one country still renders as a read-only name, which is right for a store that truly sells to one country and is no longer the default for everyone else (0.11.0). - Settings: Admin, Settings, Markets, Regions, read through
GET /api/store/countries.
<CheckoutShippingMethodList />: checkout/shipping-method-list
- Purpose: radio list of shipping options with inline carrier-picker
expansion, free-shipping label, optional per-carrier logos, optional
read-only price preview pre-address (
previewWhenAddressNotReady). - Presentation: visible shipping-option titles are uppercase so merchant and carrier naming conventions do not create mixed capitalization in one list. An unselected option keeps its card background and uses the primary border color on hover.
- SDK calls: renders
checkout.listShippingOptions(client, {cart_id})rows AS SERVED (rule-filtering +checkout_method_orderare server-side). - Props contract: hook state +
logoByFulfillmentOptionId?as an optional store override. The normal path needs no carrier-specific props: each option carries the platform-resolvedcarriercontract. - Settings: checkout rules (
target_type=shipping_option), method ordering, carrier integrations (which options exist at all).
Which destination an option books, and the carrier's mark: checkout/fulfillment-option, checkout/carrier-marks
fulfillmentOptionId(option): the merchant's choice on the shipping option:econt-office,speedy-address,boxnow-locker,pigeon-officeand the rest of the carrier registry. The platform resolves it through the carrier adapter and returns it ascarrier.fulfillment_option.id;data.fulfillment_optionanddata.idremain read fallbacks for an older platform response. Every picker, every mark and the hook's own readiness go through this one function.carrierMark(option): reads the mark URL returned by the carrier adapter.CheckoutClientuses it unless the store supplies an override, so a connected carrier arrives branded without a storefront asset map.
<PickupPointSelector />: checkout/pickup-point-selector
- Purpose: THE pickup picker, every carrier, mounted by
CheckoutClientwhen the option's adapter says its destination is an office or locker. Nearest three by haversine distance to the typed address, each with its distance, and a door to search the whole catalogue. Primary office and locker names render uppercase across carriers; secondary addresses retain their source casing. Point rows stay on the card surface and show only a primary border on hover. - SDK calls:
integrations.listPickupPoints(client, provider, {mode, catalogue: true, locale}), one door for all carriers. The complete eligible catalogue is cached per SDK client, carrier, mode and language for ten minutes, then ranked by distance BEFORE taking three results. Search runs over the same complete list, matching name, city, street and postcode in Latin or Cyrillic. - Always a point: the list is always the carrier's whole
network for the option and the cart, never cut to the typed town, whatever
pickup_scopesays (the platform sendsglobalfor every carrier). The three suggestions are a best try, never a promise of the nearest: the address found on the map, ranked by distance; else three points of the typed town; else three points of the saved postcode, so a misspelled town still finds its points ("Елин Пелон" with 2100 offers Elin Pelin's lockers); else the network's first three. Only the map try shows distances. Nothing is offered only when the network itself is empty, and the search reaches every point whatever the address says. A picker the shopper meets with nothing to pick reports itself throughlogError:pickup_points_failedwhen the network cannot be read (with the error's name, code and status) andpickup_points_emptywhen it holds no point this option can offer this cart, each once, to the platform's checkout log on the delivery step, where an unread network or an empty one is the platform's failure. An empty search is the shopper's own typing and is never reported. The mounted locale pack selects Speedy's BG/EN names and addresses. Econt APS stations never appear as offices. Speedy's lockers appear in its office list only for a store whose Speedy integration turns on "Lockers in the office list": each locker row then starts with the wordpickupLockerTag("Автомат"), the heading and the search name offices and lockers (pickupNearestOfficesAndLockers,pickupSearchOfficeOrLocker), and a locker leaves the list once the cart is heavier than itsmax_weight_kg(one parcel of 20 kg); a locker picked before the cart outgrew it is let go and the shopper picks again. Pigeon's adapter reads every page. The original{mode, q, limit}search call remains available to other consumers. - Props contract:
{client, provider, mode, userCity, userAddress, userPostalCode?, cartWeight?, selectedPoint, onSelect, logError?}.userPostalCodeis the saved postcode andlogErrorthe checkout's error sink (useCheckoutErrorLog);CheckoutClientpasses both, and without a sink the picker reports nothing.scope?is deprecated and ignored.cartWeightis the cart'stotal_weightin grams (CheckoutClientpasses it); without it every point is offered.onSelectreceives the point AND the carrier's own key names, which arrive with the answer from the platform's destination registry, so the checkout writes the point under the names this carrier's booking reads without carrying a copy of that map. The choice is remembered on the cart under the checkout's own_checkout_*keys so a reload restores it; the carrier's REAL keys are still written exactly once, at prepare. - One picker for every carrier:
pickupOptionOf(checkout/pickup-option) reads the carrier and the mode from the option's carrier contract, so a carrier connected tomorrow opens its picker with no line added anywhere. - Settings: the carrier integrations (connected; the market's options; Speedy's "Lockers in the office list").
<EcontOfficeSelector /> / <BoxNowLockerSelector /> / <PigeonOfficeSelector />: checkout/econt-office-selector, checkout/boxnow-locker-selector, checkout/pigeon-office-selector
- Superseded by
<PickupPointSelector />, no longer mounted byCheckoutClient. Exported still for a store that imports one directly; the default checkout has no carrier-specific branch or prop. - Purpose: Bulgarian office/locker pickers: nearest-3 by haversine distance (Nominatim geocode of the typed address), city-locked search with Cyrillic↔Latin normalization, selected pill + change.
- SDK calls: Econt: none (public Econt Nomenclatures endpoint,
page-level cache). BoxNow:
integrations.listBoxNowLockers(client). Pigeon:integrations.listPigeonOffices(client, {type:"office"}), the carrier catalogue is credentialed, so the platform serves it and the browser never asks Pigeon; its id arrives as a NUMBER and is stringified when it is written. All three: 503/502/network render one "temporarily unavailable" state, and a town with no point of that carrier says so instead of showing an empty box (integrations.md). - Props contract:
{userCity, userAddress, selectedOffice|Locker, onSelect}(+clientfor BoxNow and Pigeon). The CHOSEN office/locker is client state; the hook writes it intocarrier_metadataexactly once at prepare (previous carrier keys are server-side swept,_prepared_carrier_keys). - Settings: the carrier integrations (enabled/lockers).
<CheckoutPaymentMethodList /> + <PaymentButton />: checkout/payment-method-list, checkout/payment-button
- Purpose: pay-online vs cash-on-delivery radio rail. The online tab
hosts Stripe
<PaymentElement layout:"accordion">(every Dashboard-enabled method, no per-method code; deliberately NOfields.billingDetails.addressoverride, the strict-completeness IntegrationError fix).PaymentButton= the Buy button: re-entry-guarded click callsperformBuyClick, cycling processing narration, translated inline errors, Price total. - SDK calls: renders
checkout.listPaymentProvidersresults via the hook'shasCard/hasCod; the click path runs the hook's calls. - Props contract: hook state +
buyButtonNotReady(Reason?),gatePaymentUntilDelivery?(default false: everything is on screen from arrival and the Buy button carries the gate, naming the missing step; pass true for the older dimmed-until-delivery flow),beforePaymentButton?slot,total(passoptimisticTotal),nothingToPay?(pass the hook's),paymentMarks?(the ordered result ofgetPaymentMarks),termsContent?(the store's own linked policy notice),logError?. Payment tabs follow the server's checkout-method order. The offline tab prints the configured method name and its instructions, with{fee}in them read as the method's own fee (codNoteWith,checkout/cod-note: whole units bare, otherwise two decimals; a method with no fee keeps the text as written); the connected processor tab shows up to three enabled payment marks and a+Nremainder. - An order that asks for no money: with
nothingToPaythe rail is replaced by one line saying the order is covered and the button becomes Complete order, carrying no amount and waiting on no card form; prepare mints no session at a zero charge. - Settings: COD integration (
labels.codNote+ fee timing), Stripe credentials, checkout rules (target_type=payment_method), hidden methods are also re-enforced at complete (checkout_method_hidden).
<CheckoutErrorScreen error reset client? cartId? />: checkout/checkout-error-screen
- Purpose: the checkout route's error boundary. Next renders a route's
error.tsxin place of the page when anything in it throws, a server component included; without one the shopper meets the framework's error page at the moment of paying and nobody is told. Mount it as the default export ofapp/checkout/error.tsx(the reference storefront, and so the seed and every scaffolded store, ships exactly that). - SDK calls:
checkout.reportCheckoutErroraserror_boundary_checkoutwhen aclientis passed; without one the screen still renders and the failure reaches nobody. - Props contract: Next's
{error, reset}plusclient?,cartId?andtitle?/body?/retryLabel?. The copy comes from the label pack when aCheckoutProviderstands ABOVE the boundary (one in the route's layout does; one inside the page does not, because the page is what Next replaced), pass the three strings otherwise. The technical message is never shown to the shopper, only logged.
<PageErrorBoundary error reset client? surface title body retryLabel /> and <GlobalErrorPage error reset client? lang title body retryLabel />: platform/page-error-boundary
- Purpose: the boundaries of the rest of the store, so a crashed page
is the store's own words with Try again, and the merchant hears of it.
PageErrorBoundaryis a route'serror.tsx(a product page, the order page), drawn inside the store's layout;GlobalErrorPageis the rootglobal-error.tsx, the last boundary, reached when the root layout itself is gone, so it draws its own<html>and<body>with inline styles. The reference storefront, and so the seed and every scaffolded store, ships all three (the checkout's isCheckoutErrorScreen). - SDK calls:
platform/page-error'sreportPageErroronce per failure,error_boundary_<surface>(global,product,order, or the store's word) through the checkout error sink, the one log of every browser-side failure, when aclientis passed; without one the screen still renders and the failure reaches nobody. - Props contract: Next's
{error, reset},client?, thesurfaceand the three strings (labels.pagein every locale pack holds them);context?carries what the route knows (the handle, the order key). The technical message is never shown to the shopper, only logged. - Why both stores carry them (2026-11-10): a store without them shows the framework's blank error and tells nobody; a store with hand-written ones reports in its own shape. One shape, from the package.
<OrderSummary /> (+ CheckoutLineItem, <LineItemCard />): checkout/order-summary, checkout/line-item-card
- Purpose: items (flat rows, READ-ONLY), promo + gift-card widgets,
totals breakdown (subtotal / shipping / COD fee / discount / total +
gift-card tender rows UNDER the unchanged total), optional secure badge.
LineItemCardis the standalone card variant. - A checkout is a checkout: the rows carry no quantity control and call no cart endpoint. The order is stated here and changed in the cart; the typed form survives the walk back and forth. The quantity is still shown, as a count on the picture and a "Qty n" line on the card.
- A free line says so: a line whose total is zero prints
labels.lineFree, never €0.00, which reads as a pricing fault where a shopper is deciding to pay. It is a SEPARATE label fromshippingFree: Bulgarian agrees the adjective with its noun, so the rows differ ("Безплатно" on a line, "Безплатна" on shipping). - The VAT row is for a company:
isCompanyOrder(cart)decides it, on the platform's own precedence (invoice_to, thencompany_id, plus the Company invoice fields the package writes into metadata), and it prints only when the figure is known. A consumer sees the price they pay: the VAT is inside it and a row for it is noise. - SDK calls:
carts.updateLineItem(quantity); child widgets below. Totals are rendered STRAIGHT from the cart decoration:item_total,shipping_total,payment_method_fee_total/payment_method_fee_label,discount_total,tax_total,total,gift_card_total,gift_card_remainder. - Props contract:
{client, cart, optimisticShippingCost, onOptimisticShippingClear?, optimisticMethodFee?, onOptimisticMethodFeeClear?, methodFeeLabel?, showGiftCards?, showSecureCheckout?, onCartChange?}. The two figures are the hook's, DERIVED from the selection every render: the selected option's flat amount or live quote, and the selected tender's own fee. A courier restored on return, a quote landing after the click and a tender chosen before the listing arrived all price correctly, because there is no click-time number to go stale. The twoon…Clear?callbacks are for a host that manages its own predictions;CheckoutClientpasses none. - The numbers: every figure comes from
checkoutTotals(checkout/summary-math), the pure function the two mobile bars call too, so the total in the column and the total on a phone are the same number by construction. It takes{cart, optimisticShippingCost, optimisticMethodFee?}and answers the product rows (newest first, fee lines filtered), the unit count, the subtotal, the shipping figure and whether it is known, the method fee, the grand total and the gift-card tender pair. - Settings: the payment method's own fee (fee row), gift cards, promotions.
The phone's order overview: checkout/mobile-checkout-top-bar, checkout/mobile-checkout-bottom-bar, checkout/mobile-order-summary-body
- Purpose: the summary column is a desktop shape; on a phone the same
content is two bars, each closed on arrival and one tap from everything.
<MobileCheckoutTopBar />is the strip above the contact form: the words "Order summary", a chevron and the total.<MobileCheckoutBottomBar />is the card directly above Place order: the newest item's picture with the unit count on it, the word Total, the count, the figure, a chevron, and it opens upwards so the row and the button stay under the thumb; with no product line it renders nothing. Both reveal<MobileOrderSummaryBody />: the items with their quantity pills, the code and gift-card doors, then subtotal, shipping, the method fee, discount, VAT and the gift-card tender pair. The grand total is not repeated inside, because the bar's own row carries it open or closed. The top bar and its open body use the normal card surface, preserving the contrast of item copy, widgets and totals on small screens. - Mount rules:
CheckoutClientmounts both (the bottom one throughbeforePaymentButton, withhideDiscount, beside an always-openDiscountSection, because a code field two taps deep inside a closed bar is a code field nobody finds). Every piece issm:hidden, so a viewport never shows a bar and the column at once. A store with its own layout imports them and composes the same way. - Props contract:
{client, cart, optimisticShippingCost, optimisticMethodFee?, methodFeeLabel?, showGiftCards?, onCartChange?}, plushideDiscount?on the bottom bar and the body. - The fee is Cartbase's own: cart-level decoration
(
payment_method_fee_total/payment_method_fee_label, already insidecart.total), never a flagged line item, so no surface subtracts a fee row out of the item list. Any method may carry a fee, and the row wears the merchant's name for it.
<DiscountSection />: checkout/discount-section
- Purpose: promo-code input + applied-promotion list (percentage or
fixed amount display). Collapsed behind its own door by default;
alwaysOpenrenders the field itself, which is what the checkout passes on a phone. The door and open field use bounded grids: the action never wraps or escapes the card, and the supporting line is hidden below 380px. - SDK calls:
carts.applyPromotionsandcarts.removePromotions(POSTandDELETE /api/store/carts/:id/promotions {promo_codes}, additive apply; see carts.md for the cart shape;cart.promotionsarrives as the{promotion:{…}}pivot embed, unwrapped here). - Props contract:
{client, cart, alwaysOpen?, giftCards?, onCartChange?}. Enter applies the code. Errors code-first viapromotion-error-copy(promotion_not_found/promotion_inactive/… + the no-email campaign-budget heuristic). - The one code field: with
giftCards(the checkout passes it where the store takes gift cards) the field takes a promo code OR a gift card: it reads "Discount code or gift card" (codeOrGiftCard,codeOrGiftCardSub,codeOrGiftCardPlaceholder), sends the code tocarts.applyCartCode(POST /api/store/carts/:id/codes {code}), and the platform decides what it is. The applied gift cards are listed under the applied codes (masked••••last4, what each covers, remove). A code that is neither readscodeInvalid, the same words whether or not a gift card with that code exists; a promo code that exists is refused in its own words.CheckoutClientmounts this one field and no second one. - Settings: promotions admin (codes, status, application method).
<GiftCardSection />: checkout/gift-card-section
- Purpose: gift-card code input + applied-cards chips (masked
••••last4, per-card live coverage, remove), for a store that composes its own checkout and wants the gift card apart. The package's checkout does not mount it: its one field is<DiscountSection giftCards />. Its narrow-screen door follows the same bounded grid as the promo door, so the label cannot turn the action into a four-line row. - SDK calls:
giftCards.applyGiftCard/giftCards.removeGiftCard(gift-cards.md). Renderscart.gift_cards[]/gift_card_total/gift_card_remainder, server truth, no client math; totals never move (tender, not discount). - Props contract:
{client, cart, onCartChange?}. Error copy honors the anti-oracle contract: ONE generic message forinvalid_gift_card(never branch on reasons the API hides),rate_limitedfor burned windows. After apply/remove the host mustsyncPaymentAmount(the CheckoutClient wiring does). - Settings: gift-cards admin (issue/disable, expiry, balances).
Error-copy maps: checkout/payment-error-copy, checkout/address-error-copy, checkout/promotion-error-copy
- Purpose: every raw failure becomes actionable copy in the store's locale,
CODE-FIRST against the Cartbase error envelope (
StoreApiError.code), then the production substring layers (Stripe.js browser errors carry no Cartbase code), then a clean per-context generic.PAYMENT_CODE_KEYSmaps the documented codes of complete/prepare/sync/refresh to locale-pack keys,checkout_method_hidden,account_required,gift_card_insufficient_balance, the 402 payment family, … - SDK calls: none (pure).
- Mount rules: call
translatePaymentError(err, "card"|"cod", labels.paymentErrors)/translateAddressError(err, labels.addressErrors)/translatePromotionError(err, labels.promotionErrors, {hasEmail})/translateGiftCardError(err, labels.giftCardErrors)at the display boundary; never showerr.messageraw.
Also in the family barrel: compareAddresses (saved-address match
detection) and the geocode helpers (normalizeForMatch,
distanceMeters, formatDistance, cleanAddress, geocodeAddress),
extra modules beyond the per-file exports, imported from
@cartbase/storefront/checkout.
Family: cart-drawer (@cartbase/storefront/cart-drawer/*)
Sliding cart UI. All
components are "use client". Money is EUR decimal major units everywhere
(cart totals are SERVER truth from the decorated cart, components render,
never compute; the only client arithmetic is the optimistic
unit_price × quantity preview that the next server snapshot replaces).
Domain doc for every call: carts.md; gift-card tender:
gift-cards.md; cross-sell sources: products.md
<CartDrawerProvider client cart onCartChange … />: cart-drawer/context
- Purpose: the family's root: open/close state, the optimistic cart
snapshot (React 19
useOptimistic), labels + hrefs, and the SDK-wired mutations every child uses. Auto-opens when the product-line item count rises from a nonzero base (the guard that keeps the late-arriving initial cart snapshot from opening the drawer on page load, so the very FIRST add does not auto-open; open explicitly viauseCartDrawer().open/ the headerCartButtonClient, or wireProductActions'openCartseam in a client composition). Locks body scroll while open, closes on Escape. - SDK calls:
@cartbase/storefront/api/carts:createCart(firstaddItemwith no cart,region_idfalls back to the store default),retrieveCart(mount inclient+cartIdmode, andrefresh()),addLineItem,updateLineItem(body{quantity}ONLY, Cartbase accepts no metadata on update; quantity 0 deletes),deleteLineItem. Every mutation returns the FULL decorated cart, which becomes the confirmed snapshot, no page refetch needed. - The instant cart (since 0.18.0): every change shows at once and
reaches the platform through ONE queue (
cart-drawer/mutation-queue,createCartMutationQueue): one call at a time, each reading the cart the answer before it left, so two answers never overwrite each other and a second add never creates a second cart. Fast quantity clicks on one line send the number the shopper stopped at; the stepper never locks. A line added a moment ago carriespending: trueand a placeholder id (isPendingLine(line)); its quantity and removal work at once and are sent to the real line when the platform has confirmed it. - A completed cart is no cart (since 0.18.1): the
platform still answers a completed cart and refuses every change to it
(
409 cart_completed), so the drawer never holds one. Reading one, or being told the stored cart is gone (cart_not_found), empties the drawer and callsonCartEnd; an add aimed at such a cart starts a new cart with the item. The checkout clears the cookie (clearCartCookie,lib/cookie-names) and callsforget()the moment the order is placed. - Props contract:
cart?: Cart|null(server-fetched snapshot; prop updates win unless a change of the provider's own is on its way; leave it out and passcartIdso the page never waits for the cart),client?: StorefrontClient(enablesaddLine/addItem/updateQuantity/removeItem/refresh),cartId?(read in the browser on mount, through the queue, when no snapshot),onCartEnd?()(the cart is over: clear the stored id;onCartEnd={clearCartCookie}for the cookie),onCartChange?(cart)(fires on every confirmed change INCLUDING first-add cart creation, persistcart.idhere),onOptimisticError?(failure)(the ops funnel for every failed optimistic mutation, wire to store logging; replaces the source'slogEventbackend call),labels?: Partial<CartDrawerLabels>(overrides: the language mounted byStorefrontLocaleProvideris the default),hrefs?: {checkout, browse, productPrefix}. - Hook:
useCartDrawer()returns{isOpen, open, close, toggle, cart, addLine(variantId, qty?, display?)(answers{ok: true, cart}or{ok: false, error}, the platform's refusal with itscode),addItem(variantId, qty?, display?)(the same, answering a boolean),updateQuantity(lineId, qty), removeItem(lineId), refresh, forget(empties the drawer and callsonCartEnd),canMutate, applyOptimistic, dispatchOptimistic, labels, hrefs}.applyOptimistic(action, serverAction)stays for store-owned server actions; the SDK methods are the fast path. - Settings: store default region + enabled currencies (cart create),
B2B price lists via attached customer, gift-card product flags
(
is_giftcardlines are non-discountable), automatic promotions, COD-fee integration (injects the fee line the drawer hides). - Mount rules: wrap the root layout; ONE provider per app. i18n: mount
StorefrontLocaleProviderabove it and the drawer speaks the pack with nothing handed over;labelsoverrides single keys (cart-drawer/labelsholds the English defaults).
markCartIntent() / useCartIntent() and useCartProducts(client, lines, active, query?): cart-drawer/intent, cart-drawer/use-cart-products
- Purpose: the drawer's own reads wait until the shopper is about to
look at the cart, and run in the browser.
markCartIntenton the cart button (onPointerEnter,onPointerDown,onFocus), on the drawer's open and on a rise of the item count;useCartIntentwhere the reads are, true for the rest of the visit once set.useCartProductsreads the cart's products with their kit links (SET_FIELDS) from the store API when the cart's products change and only whenactive; a quantity change keeps the answer, a product added a moment ago counts from the click, the last answer stays while the next is read, a failed read keeps it.queryis the store's pricing context. - The rule they carry (2026-11-10, from the two stores): the cart is
the BROWSER's. The provider reads it from the cart id in the cookie
(
client+cartId), the page never waits for it, nothing about the cart is rendered on the server per visit and no server action moves it. A store that read the cart on the server, in a Suspense island of its layout, resolved the drawer's extras there and re-resolved them through a server action after every change, carried a hole on every page, its 404 page included, and crashed into its root boundary whenever that hole went unfilled. The server-readcartprop remains for the day it is retired; a new store never passes it.
<CartDrawer sidebar children />: cart-drawer/cart-drawer
- Purpose: the slide-out shell: overlay + right panel (
z-[60]/z-[61], the consent banner sits above atz-[70]), optional desktop left sidebar slot for cross-sell. No SDK calls. - Mount rules: render once, inside the provider; put drawer body
components in
children.panelClassNamecomposes onto the panel.
<CartDrawerHeader />: cart-drawer/header
- Purpose: title + item-count badge + close button. Counts PRODUCT
lines via
productItemCount(lib/cart-helpers) so a backend-injected COD-fee line never inflates the count. No SDK calls (context cart).
<CartPromoBanner message variant />: cart-drawer/promo-banner
- Purpose: top strip message (
info|success|warning). Pure props.
<CartTieredProgress tiers currencyCode />: cart-drawer/tiered-progress
- Purpose: progress bar to the next shipping/discount tier with
checkpoint markers. Reads
cart.total(tax-inclusive server truth). - Props contract:
tiers: CartTier[]sorted ascending;thresholdin EUR major units (50 = €50). Pure math exported ascomputeTierProgress(amount, tiers)(unit-tested).
<CartItem item currencyCode>{upsell?}</CartItem>: cart-drawer/item
- Purpose: one line row: thumbnail, title link, variant, quantity
stepper, per-line price with strikethrough (server
total<original_total), remove button (optimistic, via the provider'sremoveItem, which isDELETE line-items/:id). - Props contract:
item: CartLineItem(the SDK's decorated line, per-line totals are server-computed),currencyCode,children= per-item upsell slot. - Subcomponents:
item/quantity(<CartItemQuantity lineId quantity maxQuantity? />, stepper floor 1, callsupdateQuantitywith{quantity}on every click and never locks),item/variant(<CartItemVariant variantTitle options? />, Cartbase lines carry the flatvariant_titlestring, not an embedded variant object),item/upsell(<CartItemUpsell products onAdd />, feed fromlistRelatedProducts,variantIdincluded soonAddcan calladdItem).
<CartFreeGift … />, <CartGiftWrap … />, <CartNotes … />, <CartRewardsPoints … />
- Merchandising slots (
cart-drawer/free-gift,gift-wrap,notes,rewards-points), pure props + labels; prices EUR major units. The store owns the effects:CartGiftWrap.onToggleadds or removes the store's gift-wrap variant viaaddItem/removeItem;CartNotes.onSavecallsupdateCart(client, cartId, {metadata: {...cart.metadata, gift_note}}), the update route REPLACES metadata wholesale (no merge), so always spread the currentcart.metadata; cart metadata is copied onto the order at complete. No admin settings, configured per store in code.
<CartCrossSellSidebar / CartCrossSellCarousel products onAdd label? />: cart-drawer/cross-sell-*
- Purpose: desktop sidebar card list / horizontal strip of recommendations.
- SDK calls: feed
productsfromapi/products.listProducts(curated collection/tag) orapi/search.listRelatedProducts(anchor complements, manual admin picks first, deterministic fallback fills; see search.md). Map responses withtoCrossSellProduct(exported fromcart-drawer/cross-sell-sidebar; picks the first variant with a server-computedcalculated_price, returns null unpriced, passcurrency_codeon the listing call). WireonAdd(productId, variantId)toaddItem(variantId). - Settings: Admin, Product, Related (manual picks); price lists
(what
calculated_pricecontains); publishable-key channel scope.
<CartSummaryBreakdown />: cart-drawer/summary-breakdown
- Purpose: full totals breakdown rendered EXACTLY from the decorated
cart:
subtotal,discount_total(>0, negated for display),shipping_total(once a shipping method is set; 0 renders FREE; before that "calculated at checkout"),tax_total(>0),payment_method_fee_total(>0, labeled by the server'spayment_method_fee_label),total, then one row per applied gift card (maskedlast4, negated; a depleted card stays listed at 0) andgift_card_remainder, what the remainder provider charges. Row selection is the pureselectSummaryRows(cart)(unit-tested). - SDK calls: none directly (context cart; every cart read re-derives gift-card tender from the live ledger).
- Settings: COD integration (fee + label), promotions, gift cards.
<CartStickyFooter />: cart-drawer/sticky-footer
- Purpose: pre-checkout subtotal + checkout CTA. Deliberately shows
productTotal(cart.items)(product lines only), NOTcart.total, which carries shipping/tax/COD checkout-context state that must not leak into the shopping drawer. Navigates tohrefs.checkout.
<CartPaymentBadges methods? badges? />, <CartContinueShopping />, <CartEmpty />
payment-badges: inline SVG payment logos (visa/mastercard/googlepay/ applepay/amex), overridable per store.continue-shopping, close link.empty, empty state withhrefs.browseCTA. Pure props + labels.
<CartDrawerTemplate config />: cart-drawer/template
- Purpose: the optional default assembly; every
feature opt-in via
CartDrawerConfig. Stores wanting a different layout compose the primitives themselves inside<CartDrawer>. - Props contract:
config:promoBanner,shippingTiers(EUR thresholds),freeGift(minCartTotalEUR),giftWrap,notes,rewards(pointsPerCurrency= points per 1 EUR, major-unit port change from the source's per-cent rate),crossSell(productsor asyncloader, fires once when the drawer first has items; build it from the SDK +toCrossSellProduct). Cross-sell adds are wired to the provider'saddItemautomatically. - Mount rules: renders product lines only (
isProductLine), a fee-only cart renders as empty rather than a fake product row.
Family: products (@cartbase/storefront/products/*)
The product page and product card family. All prices
render the SERVER-computed variant.calculated_price via
lib/get-product-price (Cartbase's flat price_list_type wire shape), no
component computes money. Product data is the canonical StoreProduct
(@cartbase/storefront/api/products) every discovery endpoint serves.
Labels / i18n: products/labels (ProductLabels + English defaults),
and a pack from locales/* for any other language,
products/context (<ProductLabelsProvider labels> + useProductLabels();
components read copy only through the context or explicit labels props).
<ProductLabelsProvider labels />: products/context
- SDK calls: none. Settings: none.
- Mount rules: client component; wrap the product page (or app) once;
partial
labelsmerge over English defaults.
<Thumbnail thumbnail images size isFeatured />: products/thumbnail
- Purpose: the product image tile used by cards;
ImageOfffallback when no image exists. - SDK calls: none (props:
product.thumbnail/product.images). - Props:
size: "small"|"medium"|"large"|"full"|"square"(aspect + width),isFeatured(11/14 aspect),className. - Mount rules: server-safe; renders through
StoreImage(@cartbase/storefront/lib/media-image),next/imagewith resizing on for the Cartbase media CDN (cartbase.cloud, allowed in the scaffold'snext.configimages) and off for any other host, so a picture from elsewhere renders as it is instead of failing the page. UseStoreImagefor your own pictures too, or add your hosts toremotePatterns.
<PreviewPrice price />: products/preview-price
- Purpose: card price line; strikethrough original + accent price when
price_type === "sale". - SDK calls: none; takes a
VariantPricefromlib/get-product-pricegetProductPrice(...).cheapestPrice. - Settings: price lists (whether a
saletype ever appears).
<ProductPrice product variant? />: products/product-price
- Purpose: PDP price panel: "From
" until a variant is selected, then the variant price; sale shows original + percentage off. - SDK calls: none directly; the product must have been fetched WITH a
pricing context (
currency_code/region_id) or it renders the loading shimmer (nocalculated_pricemeans no price, by design). - Settings: price lists / B2B groups (via the signed-in customer on the fetch), region/currency context.
- Mount rules: client; reads labels from context.
<OptionSelect option current updateOption title disabled />: products/option-select
- Purpose: one option row of value buttons (
product.options[], which carriesvalues[]). - SDK calls: none. Mount rules: client; controlled by the parent.
The product page contract: products/variant-url, products/use-product-actions
Six rules every buy panel is held to, the package's own and a store's:
- The address is the state. The chosen variant is named in the URL as
?variant=<id>, so a link copied from an email, an ad or a chat opens on the variant it was copied from and a refresh never forgets a choice. The value is the id's DIGITS (pvar_1000683784068travels as1000683784068), the platform's law for every id in a URL; reading accepts the whole key too. - The first paint is right. The page hands
searchParams.variantdown (initialVariantIdonProductTemplate,ProductActionsor the hook), so the server renders that variant's price, code and stock and nothing flashes. On Cache Components the page passes it toProductTemplateas a promise (searchParams.then((q) => q.variant)) and the live buy box reads it behind its boundary, so the rest of the page stays prerendered. The hook itself never reads the query while rendering: it readswindow.location.searchwhen it rewrites the address. - A switch is a browser event. The address is rewritten with the browser's own history call, which Next's router picks up; no server render runs. (Going through the router made every click a navigation: the address lagged a whole render behind the click and a fast second click left it on the first variant.)
- The default is the merchant's. With no variant in the address, the variant made of each option's FIRST value is chosen, in the option order the admin shows; never the wire's first variant, which is the database's scan order.
- The server is asked only for what needs it: adding to the cart.
- The add is instant (since 0.18.0). With no
addToCartpassed, the add goes through the mountedCartDrawerProvider(addLine): the drawer opens at the click with the product already in it, the platform confirms behind it, and no page render runs. A store that passes its ownaddToCartserver action keeps the old path (await it, open the cart, refresh the page so a server-rendered cart follows).
products/variant-url is the pure half (VARIANT_PARAM,
variantParamValue, findVariantByParam, defaultVariant, variantHref).
useProductActions({product, addToCart?, initialVariantId?, onAddToCart?, openCart?, syncAddress?}) is the behaviour as a headless hook: the chosen
values, choose, the resolved variant, quantity/setQuantity,
inStock (the server's in_stock predicate, never re-derived;
insufficient_inventory on add flips it until the choice changes),
price, add. A store that wants its own look draws its own panel on the
hook and inherits every rule; ProductActions below is the package's own
panel on the same hook. Client hook; it reads useSearchParams, so mount it
under a <Suspense> boundary on a static page (a dynamic page needs none).
Pure: products/sets (sets from inventory kit links)
A set is an inventory kit: its variant draws on the stock items of the
products inside it. Pass fields: SET_FIELDS to listProducts or
retrieveProduct and every variant carries inventory_items; then
setContents(product, variant) names what a set holds (product, variant,
title, handle, picture, how many), setContentsByVariant(products) keys
that by variant for a page of products, and setsContaining(product, variant) names the products holding this variant's own item, the sets it
is in. linkOwner(link, productId) is the rule underneath: an item's owner
is the other product's variant carrying the item's SKU.
A list of cards passes fields: LIST_FIELDS instead: every variant carries
set_parts, what the set holds and nothing else, and the description is
left out. setContents reads either form, so a card works from both;
setsContaining needs the kit links and is for the product page and the
cart. SET_PARTS_FIELDS is the light parts alone, for a list whose cards
quote the description. The package's own list reads (getProductPage,
getCollectionProducts, getCollectionPicks, the paginated grid and the
collection template) ask LIST_FIELDS unless the caller names its fields.
Pure: products/variant-matching
optionsAsKeymap / optionsMatch / findMatchingVariant, the
option choice to variant resolution, extracted from product-actions, reading
the option-value LINK shape (variant.options[].value.{option_id,value})
with a flat-row fallback.
<ImageGallery images />: products/image-gallery
- Purpose: stacked PDP gallery in the merchant's order (the store API
serves every product's images by rank); first three
images
priority. - SDK calls: none (props:
product.images). Server-safe.
<ProductActions product addToCart? initialVariantId? disabled? onAddToCart? openCart? showQuantity? />: products/product-actions
- Purpose: the package's own buy panel on
useProductActions: option rows, price, the quantity stepper (showQuantity, on by default), the add button, the mobile bar. Every rule of the product page contract above is the hook's; this is only the markup. - SDK calls: none itself; the injected
addToCart({variantId, quantity})seam is the host's cart orchestration (typicallyapi/cartsaddLineItem+ the host's cart-id cookie).openCartreplaces the legacy cart-drawer context import (no hard cross-family dependency). - Stock contract: the variant's
in_stockis THE availability predicate, computed by the server on every product read and only read here; the SERVER still enforces at add (400insufficient_inventory, which flips the button to the out-of-stock state until the choice changes). - Settings: inventory (manage/backorder flags, inventory kit components at add), price lists, promotions (server re-applies on add).
- Mount rules: client; needs
ProductLabelsProviderfor non-English. FiretrackCartAdd(every configured vendor at once) fromonAddToCart.
<MobileActions … />: products/mobile-actions
- Purpose: the
lg:hiddensticky bottom bar + options bottom sheet (z-[75], above the cart drawer's z-[60]) shown when the desktop actions scroll out of view. - SDK calls: none; pure props from
ProductActions(which mounts it, rarely used directly).
<ProductTabs product />: products/product-tabs
- Purpose: accordion: product information (material, origin, type, weight, dimensions) + static shipping/returns copy from labels.
- SDK calls: none. Settings: none (copy via labels).
<ProductInfo product />: products/product-info
- Purpose: collection link (
/collections/<handle>), title, description. SDK calls: none. Server-safe.
<ProductPreview product isFeatured? />: products/product-preview
- Purpose: THE product card (links
/products/<handle>): thumbnail + title + cheapest price. Reused by store grids, search results, related strip; every template acceptsrenderProductto swap it for a custom card. - SDK calls: none; expects a
StoreProductfetched with pricing context for the price line. Server-safe.
<RelatedProducts client product labels pricingContext? limit? renderProduct? />: products/related-products
- Purpose: the "You might also like" strip.
- SDK calls:
api/searchlistRelatedProducts(product.id), manual admin picks first, deterministic fallback fills tolimit(auto_filled); anchor never appears. Renders nothing on empty/404. - Labels:
labels: ProductLabels, REQUIRED: a server component cannot read the provider, so passSTORE_LOCALE.products;ProductTemplatepasses its own through. - Settings: Admin, Product, Related (manual picks), price lists.
- Mount rules: async server component; render inside
<Suspense>.
<ProductActionsWrapper client id pricingContext? initialVariantId? addToCart … />: products/product-actions-wrapper
- Purpose: re-fetches the product with the LIVE pricing context (and
the signed-in customer, for their group prices) and mounts
ProductActions; the PDP shell stays cacheable. - SDK calls:
api/productsretrieveProduct(idOrHandle, pricingContext); a 404 renders nothing. - Mount rules: async server component inside
<Suspense>(fallback: disabled<ProductActions>).
<ProductTemplate client product labels addToCart initialVariantId? renderProduct? pricingContext? onAddToCart? openCart? promises? hideSpecs? sections? />: products/product-template
- Purpose: the full PDP: sticky info column (
ProductInfo+ProductTabs), gallery, sticky actions column (suspendedProductActionsWrapper), related strip.initialVariantIdis the address's variant (searchParams.variant, rule 2 of the contract), a string or a promise of one; a promise is read inside the live buy box's boundary, and the fallback box renders the merchant's default;renderProductis the store's card for the related strip, so a store with its own card no longer draws the library's preview on one page. - SDK calls: via children (retrieveProduct, listRelatedProducts). The
page fetches the product by handle (
retrieveProduct) and passes it in. - Settings: union of children's.
- Mount rules: server component;
labelsis REQUIRED (the pack'sproductsarea) because the related strip renders on the server; the client parts inside readProductLabelsProvider, whichStorefrontLocaleProvidermounts;addToCart/openCartseams as onProductActions.
Family: store (@cartbase/storefront/store/*)
The listing family: paginated grids, sort, collection/category/search
templates. Sorting discipline: the API's order param is the authority for
paginated listings; client-side re-sort (lib/sort-products) exists ONLY
for the price sorts on the plain products listing (price is not a products
column) over the legacy 100-item window.
Labels / i18n: store/labels (StoreLabels + defaults + the pure
sortOptionLabelKeys map, completeness unit-tested) and locale.store
from a pack. Templates take labels: StoreLabels, REQUIRED: they are
server components and cannot read the provider, so a page hands them
STORE_LOCALE.store (en.store for an English store).
<Pagination page totalPages />: store/pagination
- Purpose: windowed page-number pagination; writes the
pagequery param and pushes the route (server re-renders with the new offset). - SDK calls: none. Mount rules: client.
<SortSelect sortBy? labels? />: store/sort-select
- Purpose: sort sidebar; writes the
sortByquery param (created_at|price_asc|price_desc, rendered fromsortOptionLabelKeys). - Props:
sortByOPTIONAL (port adaptation): on collection pages no selection = the collection's admindefault_sort, nothing highlighted. - SDK calls: none. Mount rules: client.
<PaginatedProducts client page sortBy? collectionId? categoryId? productsIds? pricingContext? renderProduct? />: store/paginated-products
- Purpose: the 12-per-page product grid + pagination over the plain products listing.
- SDK calls:
api/productslistProducts:created_atis serverorder:"-created_at"+ real offset pagination;price_asc/price_descis a 100-item window fetch,lib/sort-productsre-sort, slice (see the module's own notes for the caveat past 100 products). - Props note:
collectionIdfilters by collection membership (a product in three collections is listed under all three); the collection's own ordered page lives inCollectionTemplate. - Settings: price lists (pricing context), sales-channel/publishable- key scope on the client.
- Mount rules: async server component; render inside
<Suspense>with<SkeletonProductGrid />.
<SkeletonProductGrid numberOfProducts? />: store/skeleton-product-grid
- Purpose: pulse skeleton for any product grid. Server-safe, no calls.
<StoreTemplate client labels sortBy? page? pricingContext? renderProduct? />: store/store-template
- Purpose: the
/storeall-products page: sort sidebar + heading + suspendedPaginatedProducts. - SDK calls: via
PaginatedProducts. Pass the page'ssortBy/pagequery params straight in.
<CollectionTemplate client collection labels sortBy? page? pricingContext? renderProduct? />: store/collection-template
- Purpose: collection page over the MEMBERSHIP listing (multi- collection products appear in every collection).
- SDK calls:
api/collectionslistCollectionProducts(collection.id), the admindefault_sortis honored SERVER-side whensortByis unset (no client re-sort, port adaptation); a shopper override mapscreated_at(asnewest),price_asc,price_descto theorderparam (price sorting server-side here, unlike the plain listing). Fetch the collection itself vialistCollections({handle})in the page. - Settings: collection
default_sort+ manual order, smart-collection conditions, channel links (scoped-away collection 404s), price lists. - Mount rules: server component; grid suspends internally.
<CategoryTemplate client category labels sortBy? page? pricingContext? renderProduct? />: store/category-template
- Purpose: category page: breadcrumbs (ancestor chain), description,
child-category links,
PaginatedProductsfiltered bycategory_id. - SDK calls: via
PaginatedProducts. Fetch the category in the page withretrieveCategory(id, {include_ancestors_tree: true, include_descendants_tree: true}), without the flags the breadcrumb and children sections don't render. - Settings: category tree (active/internal flags are server-filtered).
The search contract: store/use-predictive-search, store/predictive-search, store/predictive-search-results
The shopper opens the box, types, and after a short pause the products and the pages for the word appear under it, without leaving the page. Enter opens the results page. Seven rules every search box is held to, the package's own and a store's:
- The box answers products and pages. One read,
GET /api/store/search/suggest(search.md): the products as the results page ranks them, and the published pages whose title the word finds. Never collections, never tags: those are the merchant's organising words, not destinations. - Nothing is asked below two characters.
- A word is asked once, after a pause. A keystroke waits 250 ms for the next one; only the last word is asked.
- The last word wins. A newer word cancels the older request, and an answer for a word the shopper moved past is never shown.
- The panel never flashes empty. While the next word is asked, the last answer stays on screen; the first word shows a searching line.
- Closing forgets. Escape, a press outside the box, Cancel, or following a result closes the box, cancels what is in flight and forgets the answer, so the next opening starts clean.
- Enter, and "view all results", open the results page for the word
(
/search?q=<word>), which answers the same products and pages.
usePredictiveSearch({client, query, enabled?, minLength?, debounceMs?, limit?, types?, pricingContext?}) is rules 2 to 6 as a headless hook: it
returns {status, term, products, pages}, status one of idle (closed or
too short), loading, done and error (a failed read, answered empty).
PredictiveSearchResults draws a state: the product rows (picture, title,
price), the pages, the searching and nothing found lines in the store's
language, and the way to every result; renderProduct, productHref,
pageHref and emptyState (what an open box shows before a word, popular
products for one) are the store's. PredictiveSearch is the package's own
box on both: a field with its clear button, the panel under it, Cancel when
onClose is given (a box that opens over the header from a search button,
with autoFocus). A store that wants its own look draws its own field and
container on the hook and places PredictiveSearchResults inside; it never
re-implements a rule. Client components.
<SearchTemplate client searchParams labels basePath? pricingContext? limit? renderProduct? pageHref? />: store/search-template
- Purpose: the search results page in the
store-template idiom, GET query box, facet sidebar from the response
facets[], the pages the word finds above the result grid (reuses the product card), pagination. Fully URL-state driven: works server-rendered with zero own client JS. - SDK calls:
api/searchsearchProductsandpredictiveSearchfor the pages (types: ["page"], beside it, only whenqpresent; a failed pages read leaves the products standing). Facet buckets toggle by rewriting the wire-named query params (collection_id/type_id/tag_idCSV,price_min/price_max,availability,option.<Title>CSV) via the purestore/search-paramshelpers (round-trip unit-tested); every toggle resetspage. - Words: the filter names and the stock words come from
labels(facetPrice,facetAvailability,facetType,facetTags,facetCollection,inStock,outOfStock), never the platform's English; an option filter is named by its option. - Settings: Search & discovery: synonyms, pins/boosts, facet config
(order/enabled, price bucket strategy
auto/fixed; tags and collection are off unless the merchant turns them on); price facet currency follows the pricing context. - Mount rules: async server component; pass the route's raw
searchParams;basePathdefaults to/search.
Pure: store/search-params
parseSearchParams / buildSearchQueryString / fromQueryString /
toggleFacetSelection / isFacetSelected / clearFilters /
toSearchQuery, the search page's URL-state machine, exported for custom
search UIs (chips, drawers) that want the same URL contract.
Family: order (@cartbase/storefront/order/*)
Order confirmation + account order views. Some
platforms ship ONE StoreOrder object carrying computed line
totals, order totals, shipping methods and payments; Cartbase splits those
across surfaces, so the family takes them as separate props, the Cartbase
StoreOrderDetail (api/orders) carries items as version-pivot rows
({quantity, line_item}), fulfillments with tracking labels, and both
addresses, while MONEY comes from the decorated cart (api/carts Cart)
or the order summary snapshot. Components render server truths; the only
arithmetic is the two documented production subtractions in the totals
selector.
Labels: OrderLabelsProvider/useOrderLabels (order/context) +
defaultOrderLabels (order/labels, English) + locale.order from a
pack in locales/* for any other language. Every
component also takes a labels prop pick, and the template's is REQUIRED
(labels: OrderLabels): it renders on the server, where no provider
reaches, so the page passes STORE_LOCALE.order.
<OrderCompletedTemplate order labels locale? totals? items? shippingMethod? paymentProviderId? cardLast4? … />: order/order-completed-template
- Purpose: the order's page: hero header, fulfillment timeline,
items+totals card, contact/delivery/payment/help cards,
continue-shopping CTA. The confirmation the checkout lands on and the
page every order email links, read from the platform on every load. ONE
page for every order, saying what is true: the heading follows the
order (
orderStage: confirmed, on its way, delivered, canceled with its date), the steps show for a live order only, and the total is what the order cost (a canceled order keeps it) with what was paid, refunded and still owed printed beneath it (selectSettlementRows), the order emails' rule. - SDK calls: none itself; feed it the
orderasretrieveOrderByKey(client, key)returns it and it renders everything from the order alone: the lines with the money the shopper paid (items[].total), the totals (order.totals, VAT included; the fee row when charged; the VAT row for a company buyer, the checkout's rule), the delivery method with its price and the office or locker chosen (order.shipping_methods,order.pickup_point), and the tender (order.payment_methods, the store's own method by its name or a card by the locale's word).locale(STORE_LOCALE.code) writes the order date in the store's language. The optional props override a part of that for a store composing the page from its own checkout state (totals,itemsviadisplayItemFromCartLine,shippingMethod,paymentProviderId/paymentMethodName/cardLast4). - Mount rules: the order route, a server component that reads by
key (the scaffold's
app/order/[key]/page.tsx); only the timeline child is client. The Purchase tracking (trackOrderPurchase, every vendor at once, deduped byorder.display_id) is APP-OWNED: fire it from the route exactly once per order per the tracking family's dedupe contract, the template deliberately does NOT fire it. - Settings: the payment method's fee (fee row presence +
payment_method_fee_label), checkout rules (which tenders appear), store locales (labels pack).
<OrderConfirmationHeader order locale? />: order/order-confirmation-header
- Purpose: the hero as the order stands (
orderStage(order)): confirmed or on its way or delivered, with "we sent a confirmation to" the email, or canceled, with the date it was canceled; then "Order #display_id" and the localized date. - Props: structural
OrderHeaderData(display_id,email,created_at, andstatus,canceled_at,fulfillment_statusorfulfillmentsfor the stage), order detail andcompleteCart().orderboth satisfy it.localedrivestoLocaleDateString; without it the date is English on a page that is otherwise the store's language, so the template passes the store's code.
<OrderItemsList items currencyCode /> + <OrderItem item currencyCode />: order/order-items-list, order/order-item
- Purpose: the purchased lines (thumb, title, variant caption, qty, line total with discount strike-through when the source had it).
- Data seam: normalized
OrderDisplayItem[]via the pure convertersdisplayItemFromOrderItem(pivot)(order path:unit_price × quantity) /displayItemFromCartLine(line)(cart path: servertotal/original_total). Legacy COD-fee line items (metadata.is_cod_fee=true) are hidden here and surfaced inOrderTotalsinstead (lib/cart-helpers.isProductLine); Cartbase-native COD fees are never line items, so on pure Cartbase data the filter is a no-op safety net. Newest-first sort bycreatedAtwhen present.
<OrderTotals totals currencyCode items? methodFeeLabel? />: order/order-totals
- Purpose: the money breakdown: Subtotal / Shipping (FREE badge at
- / COD fee / Discount (negated) / Tax / Total, all via
Price.
- / COD fee / Discount (negated) / Tax / Total, all via
- Data seam:
OrderTotalsSource(the decorated cart satisfies it:item_subtotal,shipping_subtotal,discount_total,tax_total,total,payment_method_fee_total,payment_method_fee_label); the summary snapshot adapts viaorderTotalsFromSummary. Row policy is the pure, unit-testedselectOrderTotalsRows: nativepayment_method_fee_totalwins over a legacy fee LINE; a legacy fee line's net is subtracted from the visible subtotal (v2.3.1 production fix); COD label preference: themethodFeeLabelprop, then the server'spayment_method_fee_label, then the fee-line title, thenlabels.paymentMethodFee. - Settings: COD settings (
payment_method_fee_total/payment_method_fee_label), promotions (discount row).
<OrderAddressCard order />: order/order-address-card
- Contact info card: shipping-address name + phone + order email.
Structural
OrderContactData, the order detail satisfies it.
<OrderDeliveryCard order shippingMethod? currencyCode />: order/order-delivery-card
- Purpose: pickup point (Econt office metadata / stable
fulfillment-option ids
econt-office,boxnow-locker; the id beats name parsing) or shipping address, the method row with price/FREE, and the fulfillment tracking labels. - Data seam:
order.metadata+order.shipping_address+order.fulfillmentsfrom the detail;shippingMethod(structural,CartShippingMethodfits) from checkout state since the Cartbase order read has no shipping-method embed. Tracking rows come from the pure, unit-testedpickTrackingLabels(order.fulfillments), skips canceled fulfillments, drops number-less labels, dedupes re-prints. - Settings: carrier integrations (whether labels/urls exist), shipping options (ids/names).
<OrderPaymentCard providerId cardLast4? />: order/order-payment-card
- Payment method card;
resolvePaymentTitle(providerId, titles, methodName?), the method's merchant NAME wins verbatim when present (the snapshot from session data); otherwise the processor id buckets vialib/payment-constants(pp_stripe= card) through the locale pack, falling back topaymentInfoMapthen the raw id. Payment internals never cross the Cartbase store surface, both arrive via props from checkout state.
<OrderTimeline fulfillmentStatus? />: order/order-timeline
- Placed, Processing, Shipped, Delivered progress (client, animated).
Cartbase has no
fulfillment_statuscolumn on the store surface, derive it with the pure, unit-testedderiveFulfillmentStatus(order.fulfillments)(packed_at/shipped_at/ delivered_at ladder,partially_*when only some active fulfillments reached a stage, canceled ignored).
<OrderHelpSection contactHref? returnsHref? />: order/order-help-section
- "Need help?" links card (contact + returns). No SDK calls, no settings.
Family: account (@cartbase/storefront/account/*)
The customer's side of the store: who is signed in, the sign-in with an
emailed code, and the account page with the orders and the profile. Every
piece is a client component on the BROWSER client (the store's own
origin): the session is an HttpOnly cookie the platform sets through the
store's /api/store rewrite, the browser sends it on its own, and no
script on the page can read it. The doors and the cookies are in
auth.md.
What the sign-in changes is the platform's to decide, not the page's. A
signed-in customer pays their price lists on every read, and when the
store's key carries a channel flagged for accounts, a customer of the
store's B2B group sees that channel's products and only those
(customer.b2b says which shopper is one). A page that reads the
catalogue on its SERVER for the visitor gives that server's client
getSessionToken (step 2 of the runbook) so the platform answers for
them; the edge never holds a signed-in answer.
Labels: the locale pack's account area (AccountLabels, with
defaultAccountLabels in account/labels), read from the mounted
StorefrontLocaleProvider; each piece's labels prop overrides single
words. A {slot} in a word is filled with formatLabel
(lib/format-label).
<CustomerSessionProvider client /> + useCustomerSession() (account/session)
- Purpose: who is signed in, for every client component.
statusisloading, thensigned-inorsigned-out;customeris theStoreCustomer(withb2bandaccount_status);refresh(),setCustomer(customer)andsignOut()are the acts. - SDK calls:
getSessionon mount, and only when the readable_cartbase_signed_incookie says someone is signed in, so a visitor who never signed in costs no request. The ask renews the session, at most once a day.signOutcalls the sign-out door, forgets the cart cookie and records nobody. - Mount rules: once, high in the app (the providers file), with the
browser client. The server render is always
loading, so a header draws its neutral account entry until the browser knows.useCustomerSessionthrows outside the provider;CustomerSessionContextreads it without throwing.
<SignInForm client redirectTo? onSignedIn? labels? className? /> (account/sign-in-form)
- Purpose: the sign-in page's form. The email, then the 6-digit code the store emails, a new code after 30 seconds, and a way back to the email. A first sign-in is the registration too, and the orders a guest placed with the same email are on the account.
- SDK calls:
requestLoginCode,verifyLoginCode, thensetCartCustomeron the open cart: the cart takes the customer's prices, and a B2B customer's cart moves to the B2B channel. A cart that is gone or already an order is forgotten. - After: records the customer on the mounted provider and goes to
redirectTo(default/account) with a full navigation, so every part of the page reads the store as the customer.onSignedIn(customer)stays on the page instead. - Errors: a wrong or expired code, too many codes, accounts disabled on the store, each in the pack's words.
<AccountTemplate client signInHref? signedOutHref? orderHref? labels? className? /> (account/account-template)
- Purpose: the whole account page: the greeting and the email, the Wholesale badge for a B2B customer, the approval note for a pending account, Sign out, the orders and the profile.
- Mount rules: the store's
/accountpage, inside the provider. A visitor who is not signed in is sent tosignInHref(default/account/login). A store with its own layout mounts the pieces below in it instead. The seed does exactly this:app/account/page.tsxmounts the template andapp/account/login/page.tsxthe sign-in form, both with the browser client on prerendered pages, and the header carriesAccountButtonClientbeside the cart button, so every store starts with its account.
<AccountOrders client pageSize? orderHref? labels? className? /> (account/account-orders)
- Purpose: the customer's orders, newest first: the number, the date,
the item count, where the order stands (canceled, or its delivery and
its money in the pack's words,
orderStanding), the total, the first four lines with their pictures, and View order. Show more reads the next page (pageSize, default 10). - SDK calls:
listOrders(client, { limit, offset }). A row opens the order's own page,/order/{key}(orderPagePath), the page the checkout lands on and every order email links;orderHrefchanges the address.
<AccountProfile client labels? className? /> (account/account-profile)
- Purpose: the name, the phone, and the company an invoice is made out
to (its name, ЕИК and VAT number). Save writes only what changed
(
profileChanges, an emptied field cleared) and the provider takes the answer. - SDK calls:
updateMe. A customer who buys under a company the store registered cannot rewrite that company's details (400 company_identity), and the form says where they come from.
<AccountSubscriptions client labels? className? /> (account/account-subscriptions)
- Purpose: the customer's subscriptions, newest first: the plan, where
it stands, the next charge and the method. Manage opens the contract in
place: the items with their quantity and option, the upcoming charges,
the history with the order each charge made, the delivery address, and
every act the merchant allows (subscriptions.md): skip the next delivery,
move the next date, pause for one, two or three months or until resumed,
resume, change the frequency to another of the product's plans, change
an item's quantity or option, change the address, cancel with a reason,
start a canceled one again on a chosen date, and update the card. The
acts render from the detail's
permissionsand the contract's status, never assumed; cancel is always there. A failed last charge puts the card update first, which is the dunning recovery the payment-failed mail points at. - SDK calls:
api/subscriptions(listSubscriptions,retrieveSubscription, every action, each answering the fresh contract the screen re-renders from);listSellingPlansfor the plans every line's product carries;retrieveProductfor an item's other options. - Mount rules: the account page, with the browser client, for a
signed-in customer.
AccountTemplatemounts it between the orders and the profile. The words are the pack'ssubscriptionsarea.
<SubscriptionPaymentMethod client subscriptionId onUpdated onCancel? labels? className? /> (account/subscription-payment-method)
- Purpose: a new card for a subscription paid by card: the platform opens a SetupIntent, Stripe.js confirms it with the card the customer types (the card never touches the platform), and the platform is handed the confirmed intent; the next charge uses the new card. Under Stripe Connect the session names the merchant's account and Stripe.js is loaded with it, as the checkout does.
- SDK calls:
createSubscriptionPaymentMethodSession,updateSubscriptionPaymentMethod. - Mount rules: for a contract whose
permissions.can_update_paymentis true;AccountSubscriptionsmounts it on Update card.
<SignOutButton redirectTo? onSignedOut? labels? …ButtonProps /> (account/sign-out-button)
- Purpose: ends the session, forgets the cart, and goes to
redirectTo(default/) with a full navigation, so no part of the page keeps the customer's prices or catalogue.onSignedOutstays on the page. Outline by default; every Button prop passes through.
Family: common (@cartbase/storefront/common/*)
Shared storefront chrome.
<SocialLinks links label /> + <SocialIcon network />: common/social-links
- Purpose: the store's social profiles as round links with each
network's mark in the text colour, for a footer or a header. Networks:
Facebook, Instagram, TikTok, YouTube, X, LinkedIn, Pinterest, Threads,
Snapchat, WhatsApp, Viber, Telegram (
SOCIAL_NETWORKS). - Data:
linksisstore.brand.socialfromgetStore(Settings, Brand, Social links); a network with no address is left out, none renders nothing.labelnames the list for screen readers (STORE_LOCALE.store.socialProfiles). - Style:
linkClassNamestyles the round hit area (colour, hover),iconClassNamesizes the mark. Server-safe.
<PaymentIcons methods label /> + <PaymentIcon method />: common/payment-icons
- Purpose: the payment marks in their brands' colours on a 38 by 24
card: Visa, Mastercard, Maestro, American Express, UnionPay, Discover,
Diners Club, JCB, Apple Pay, Google Pay, PayPal, Revolut, Klarna,
Bancontact, iDEAL (
PAYMENT_METHODS). No Shop Pay. - Data:
methodsispayment_marksfromgetPaymentMarks(client)(api/store), what the store's Stripe allows, in order; empty renders nothing.labelisSTORE_LOCALE.store.paymentMethods. - Style:
iconClassNamesizes a mark by height (24px default).CartPaymentBadgesdraws the same marks. Server-safe.
<PoweredByCartbase label />: common/powered-by-cartbase
- Purpose: "Powered by" and the Cartbase wordmark, a link to cartbase.ai, for the footer's last line. Drawn in the text colour.
- Data:
labelisSTORE_LOCALE.store.poweredBy.markClassNamesizes the wordmark by height (14px default). Server-safe.
The marks are generated: SVG files in assets/icons, built by
scripts/build-icons.mjs (sources and licences in
assets/icons/README.md).
<LocalizedLink href … />: common/localized-link
next/linkthat persists the URL locale/country segment when the route has one ([countryCode]param by default,paramNameoverridable); plain link on cookie-locale apps (the Cartbase default). Client.
<CartButton client cartId? /> + <CartButtonClient cart? />: common/cart-button, common/cart-button-client
- Purpose: header cart button: badge count + opens the cart drawer.
- SDK calls:
<CartButtonClient />with nocartcounts the drawer's own cart (the one the provider read in the browser): the default, and the only shape that keeps a store's pages prerendered. The server wrapperCartButtonreadsapi/carts.retrieveCart(client, cartId)from the cookie, so it renders per visit and belongs behind a<Suspense>; fetch failure degrades to an empty button. Badge count =productItemCount(cart.items)(fee-line-aware, consistent with the drawer). - Mount rules:
CartButtonClientmust sit inside the cart-drawer family's<CartDrawerProvider>(it callsuseCartDrawer().open).
<AccountButtonClient accountHref? signInHref? className? />: common/account-button-client
- Purpose: the header's account entry, beside the cart button: the
person icon, named with the pack's
account.accountTitle. - SDK calls: none. It reads the mounted
CustomerSessionProviderwhen there is one: a visitor the session says is nobody goes tosignInHref(default/account/login), everyone else, the server render included, toaccountHref(default/account). Without the provider it is always the account page, whose template sends a visitor to the sign-in itself. - Mount rules: anywhere in the header; a plain link, so the page around it stays prerendered.
<DeleteButton client cartId id onDeleted? />: common/delete-button
- Cart-line remove with spinner. Calls
api/carts.deleteLineItem(client, cartId, id)(idempotent) and hands the refreshed{cart}toonDeleted; spinner resets on failure.
<MarketSelect regions value? onChange />: common/market-select
- Purpose: the market picker for a header or footer: the store's
REGIONS (
api/regions.listRegions) by name, valued by region id; persistence is app-owned viaonChange(usuallycarts.updateCart(client, cartId, {region_id})+ a cookie). A country is a different thing: the checkout picks one fromlistCountries, withCountryFlagbeside it. - Was
CountrySelect(common/country-select): the old path and names still import for one release and then go. - Settings: Admin, Settings, Markets, Regions: which rows exist.
<CountryFlag code title? className? />: common/country-flag
- Purpose: a country's flag from its ISO-3166 alpha-2 code, at the size of the text beside it. An unknown or empty code renders a neutral box that holds the same space, so a field does not jump when a shopper picks their country.
- Why a sprite and not an emoji: Windows ships no flag glyphs, so an
emoji flag reads as the two letters "BG" there. This draws
flag-iconsSVG under a CSS class, which renders the same on every platform, and it is the same sprite the Cartbase admin uses, so one country treatment runs across the admin and the storefront. - Accessibility: decorative and
aria-hidden: a flag never carries meaning the name beside it does not. Passtitlewhen it stands alone.
<LanguageSelect locales currentLocale onChange labels? />: common/language-select
- Purpose: locale switcher. Feed
localesfromapi/regions.listLocales(client)(bare codes, store default first, SDK wins over the source's{code,name}objects); display names vialocaleDisplayName()(Intl.DisplayNamesautonym) with per-storelabelsoverrides.onChangepersists (cookie read byStorefrontClient.getLocale) inside the preserveduseTransitionpending-disable UX. - Settings: Settings, Store, locales (per-store
store_locales).
<Skeleton className? /> + <SkeletonProductPreview />: common/skeleton
- Loading placeholders (pure UI over theme tokens).
Family: experiments (@cartbase/storefront/experiments)
The store's A/B tests in a storefront. Endpoint truth:
experiments.md. The variant is computed in the page with
the platform's own assignment (GrowthBook's hash version 2,
experiments/assign, held to the platform's answers by a shared test), so
the variant shown is the variant judged.
<ExperimentsProvider client experiments? visitorId? /> in experiments/provider
- Purpose: holds the store's experiments and the visitor for every
useExperimentbelow it; reports what each visitor was shown. - Mount rules: client component, once, in the root layout's providers.
Pass
experiments(listExperimentsread on the server) andvisitorId(the_cartbase_visitorcookie of the request) and the first paint already shows the visitor's variant; without them the browser reads both, the experiments only once a component first asks for one, so a store whose pages ask for none never makes the call. - SDK calls:
listExperiments(lazily),recordExposures(once per visitor per experiment, the keys asked in one render in one call, from the browser; remembered inlocalStorageunder_cartbase_experiments_reported; a refused analytics banner is sent asconsent: false, which the platform answers and never records). The reports go through the page's one reporter (exposureReporter(client)inexperiments/report), which the checkout shares for the experiments its listings name, so a visitor is reported once whichever asked first. - Preview: a page opened with
?cartbase_preview=<key>:<variant>makes this tab answer that variant (a draft's included) until the tab closes or?cartbase_preview=off; nothing previewed is reported (experiments/preview:readExperimentPreview(),previewParam()).CartDrawerProviderkeeps the link for the tab as well, so a store that mounts noExperimentsProviderstill previews its checkout tests from any page.
useExperiment(key) in experiments/provider
- Purpose: the variant key to show for one experiment, or
nullfor the control (no experiment by that key, a draft, one ended without a winner, a visitor outside its coverage or not known yet). An experiment ended with a winner answers the winner to every visitor and reports nothing. Outside a provider it is alwaysnull. - Usage:
const variant = useExperiment("drawer-weight"), thenvariant === "kilos" ? <WeightLine /> : null.
getExperimentVariant(client, key, visitorId) in experiments/server
- Purpose: the same variant on the server (a page, a layout, a route handler), from the request's visitor cookie. Reports nothing: only a browser's report is recorded.
Family: marketing (@cartbase/storefront/marketing)
The merchant's campaign popups and the unsubscribe page every marketing
mail links to. Endpoint truth:
marketing.md and the unsubscribe doors in
customers.md. The targeting is applied in the browser from
the merchant's own words (marketing/targeting, pure); the words come from
the campaign in the store's language, the family's own labels where a field
is blank (StorefrontLocaleProvider's marketing area, labels? to
override).
<PromoPopup client campaigns? pathname? locale? labels? onSignup? /> in marketing/promo-popup
- Purpose: the popup. Reads the live campaigns (or takes
campaignsread on the server withlistCampaigns), picks the first the visitor qualifies for on this page (the pages, the device, the page views, a dismissal's cap, never after a signup, and the experiment arm when the campaign rides one, asked of the mountedExperimentsProvider), opens it on the campaign's trigger (the delay, a scroll depth, exit intent), and walks the question, the email with the consent box, and the thanks. - Mount rules: client component, once, in the root layout's providers,
with the browser client. Pass
pathnamefrom the app's router so a client navigation counts as a page view and re-targets; without it the address at mount is the page. - SDK calls:
listCampaigns(once, unless given),signupon submit (campaign_id, the email, the chosenintent, thedevice, the visitor cookie asdevice_id,consent: true). After an ok:trackLeadfor the pixel,rememberKnownVisitor({ email }), andonSignupfor the store's own tracking. - What the browser remembers: per campaign under
_cartbase_popup_<id>(dismissed when, signed up, the reopen tab closed when); the session's page views under_cartbase_popup_views. A dismissal leaves a tab on the page's left edge that reopens the popup; its X closes it for the cap's window.?popup_reset=1forgets all of it. - Words: the campaign's copy in the storefront's locale (the mounted
language, or
locale), else the first locale the campaign has; a blank field falls back to the family's labels.
<UnsubscribePage client token? labels? className? /> in marketing/unsubscribe-page
- Purpose: the store's
/unsubscribepage, where every marketing mail's link and the mailbox provider's own button land. Reads the token (prop, else the address'stoken), says whose link it is (the address masked) and where they stand, unsubscribes on the button, and offers "Subscribe again" with the same token. A tampered, foreign or missing token says the link is not valid. - SDK calls:
readUnsubscribe,unsubscribe,subscribe(@cartbase/storefront/api/marketing).
marketing/targeting (pure)
qualifies(campaign, ctx),tabShows(campaign, ctx),pageMatches(pages, pathname),withinCap(at, days, now),deviceOf(width),copyFor(campaign, locale); the browser's memoryreadMemory,writeMemory,forgetPopups,countPageView,resetAsked.
Family: reviews-ui (@cartbase/storefront/reviews-ui)
Verified-purchase review components over api/reviews. ONE barrel export
seam: everything imports from @cartbase/storefront/reviews-ui. Endpoint
truth: reviews.md. Labels: the family reads the language
mounted by StorefrontLocaleProvider on its own (English with none),
labels? on any component overrides keys, and StarBadge,
the one server-safe piece, takes its labels as a prop. Strings are
parameterized with {n}/{pct}/{name}/{mb}/{s}/{email} slots
(resolve via formatLabel).
<ReviewWidget client productId initialData? />: the PDP section
- Purpose: the product page's review grid: a header, the review cards
(photo reviews first), "Show more reviews", and the lightbox a card
opens. The header is one of three
(
ReviewSummaryHeader):minimal, the stars and one fact (the count, the average or nothing) with the breakdown under a chevron;compact, the average, the stars and the count on one line;expanded, the section title, the big score and the breakdown open beside it. The sort menu (ReviewSortMenu, an icon with "Sort by" under it) sits on the right. Renders null at zero reviews (production rule); derives avg/distribution from the loaded page if the aggregate is missing (never a misleading "0.0"). - SDK calls: bootstrap:
getWidget(client, productId)(ONE call: aggregate + first page per the store's display options; edge-cached 60s), server-fetch it and passinitialData(recommended), else the widget fetches on mount. Sort changes / load-more:listReviews(sortParamsFormaps the UI keys to the API(sort, order)tuple). - Mount rules: client component, PDP below the fold;
id="reviews"anchor built in. Verified badge is unconditional (every review is token-minted, a system tautology, not a flag). - Settings: admin, Reviews, Widgets: the header and what the minimal
one shows, masonry or list, reviews per page, photo reviews first, and
the rating breakdown, the sort menu and the card date, each of which can
be switched off. They arrive in
getWidget().options;reviewWidgetOptions(options)fills what an older platform leaves out with the defaults (minimal header with the count, everything shown). Moderation decides visibility. - Pieces exported for custom layouts:
<StarRow>(size="lg"is the lightbox's row),<StarBadge>,<RatingDistribution>(star-badge),<ReviewList>(the presentational cards; a click on a card opens it in<ReviewLightbox>),reviewDisplayName(first name and surname initial, shared with any app JSON-LD so UI and structured data cannot drift, a production fix),formatReviewDate. - Theme: the stars fill in the
ratingcolour (--ratingin tokens.css, the warning yellow unless the store sets its own).
<ReviewLightbox reviews position onPositionChange labels? />: one review, whole
Purpose: the review opened from ANY widget that shows reviews: the photo or video on the left, and on the right the reviewer, the verified badge with a button that says what it means, the stars, the date, the text and the store's reply. On a phone the photo sits on top and the review scrolls under it. The arrows and the arrow keys walk the open review's photos, then on to the next review; the dots jump between one review's photos; Escape, the close button and a click outside close it.
Mount rules: client component, built on the Dialog primitive. The opening widget owns the state and hands over its own list, so the lightbox walks the reviews in the widget's order:
const [open, setOpen] = useState<LightboxPosition | null>(null) // on a card: onClick={() => setOpen({ review: index, media: 0 })} <ReviewLightbox reviews={reviews} position={open} onPositionChange={setOpen} />mediaindexeslightboxMedia(review), the same filtered list a card counts its photos from.stepLightboxis the walk itself, for a widget that steps on its own.
<ReviewWizard client token validation rewardPct? supportEmail? … />: the token page
- Purpose: everything behind
<review_link_base>/<token>: invalid/ expired panels, the terminal already-submitted panel, and the two-step form (rate, then photo, then done) with the reward-code reveal. - SDK calls:
validateToken(client, token)SERVER-SIDE in the page (pass the result asvalidation, never flash a form on a dead token; mark the route noindex), then client-side:submitReview(step 1, consumes the token, rating locked in even if the customer bails),createUploadUrl, then a PUT to the signed upload link, thenattachReviewPhoto(step 2, mints the single-use reward code;code: nullon 200 = media saved, mint failed: a "write to us" note, never an error). - Step resolution: the pure, unit-tested
resolveWizardEntry(validation); THE RESUME RULE: consumed token + review row withreward_codenull resumes at photo;reward_codeset is done, showing the code; consumed with no review row shows the terminal panel. Submit errors map by status viasubmitErrorKeyFor(429/409/410). - Mount rules:
ReviewWizardis the full page body (client);ReviewWizardFormand<ReviewPhotoUpload>(drag-drop, per-file slot caps ≤6 images/≤1 video, 8/50 MB, 60s video, blob-preview swap + revoke) are exported for custom pages. - Settings: Settings, Reviews:
reward_enabled/reward_percentage(the store surface does not expose the percentage, passrewardPct, default 10),moderation_mode(holdlands the review pending; the thanks copy stays true either way), request-scanner settings decide when tokens are minted at all.