Bring your own storefront
You already have a Next.js app, built with any tool, and you want it to sell through a Cartbase store. This page takes that app, as it is, onto the Cartbase backend: the store's products and stock behind your buttons, Cartbase's cart and checkout inside your design, the order page, the mails, the couriers and the payments the platform runs, and Cartbase hosting with your own domain. It is written to be followed by a coding agent as-is. The runbook starts from a blank app and is the reference for every chapter named here; nothing on this page replaces a chapter, it tells you which ones you need and in what order.
What you need: ONE value, the store's publishable key, handed out on the Storefront page of the store's Cartbase admin. The domain comes at the end, and the courier, the payment method and the products are set in the admin, not in code.
| Input | Example | Where it goes |
|---|---|---|
| Publishable API key | pk_… |
NEXT_PUBLIC_CARTBASE_PUBLISHABLE_KEY |
The rules, before the first edit
These are not style. Each one is enforced by the platform or costs the store its support, and an agent that reads nothing else reads these.
- The package is the way in, with no exception.
@cartbase/storefrontholds the typed client for every store endpoint, the cart, the checkout's whole money path, the courier pickers, the consent-gated tags and the languages. The platform's checkout completion refuses a client that skipped the platform's filtered listings and logs the refusal, and it refuses a total that differs from the one shown, so a checkout written against raw endpoints fails at the moment of money. Every read and every write goes through the package'sapifunctions or its hooks. - Totals and prices are the server's. Render what the platform answers, verbatim. Never add, multiply or round money in the app.
node_modulesis never edited. The package is a dependency, pinned to one version. A change you need comes from a newer version of the package, from a prop or a slot the component already has, or from the theme tokens. A patch insidenode_modulesis gone at the next install and nobody supports it.- The hooks are imported, never copied and never rebuilt. The cart
provider, the product hook and the checkout's nine concerns are the
platform's rules in code (
components.md, the checkout family). A store that needs a different flow composes them through their public surface; it does not write its own cart or checkout. The money path,checkout/use-checkout-buywith the payment wrapper, the Stripe scope and the payment button, is locked: it is never ejected, never copied and never wrapped by code that changes what it sends. - Your design stays; the components are restyled, not rewritten.
Every component reads the theme tokens (
@cartbase/storefront/theme) and most take slots and labels. Override token values, never token names. Ejecting a component is the last resort, and it is one command, never a copy by hand:cartbase eject <module>(for instancecartbase eject products/thumbnail --reason "a square picture") puts the file insrc/cartbase/with a header that says where it came from, its imports pointed back at the package, and the sentence every ejected file carries: it leaves Cartbase support, receives no fixes, and its safety is yours. The money path is refused. A wired piece (the checkout, the cart provider, the product hook, the API, the tracking) is said to stop receiving the platform's fixes, and the store's staff list is mailed the first time one leaves support: the deploy reads every header. - The platform's files are not yours to write. On Cartbase hosting
the deploy refuses
middleware.*,app/api/*,pages/api/*,vercel.json,proxy.tsandinstrumentation-client.js(deploy.md, the bundle rules). What your app's own API routes did (a form that mailed an order, a webhook) is the platform's work now, or a custom app (BUILD-AN-APP.md).
Step 1: the store, before the code
The merchant sets up the store in the admin; the agent reads it. Before touching the app, the store needs:
- the products, each sellable option a variant (three bottle bundles are three variants of one product, each with its own price, SKU and weight; the courier prices by weight);
- the prices, VAT included, in the store's currency;
- stock on the variants, or the buy button reads sold out;
- a connected courier and at least one delivery option, and the payment methods the store takes (cash on delivery is a method);
- the store's language under Settings, Languages, which the mails follow.
Then the probes. The regions listing is the cheapest liveness and key check, and the products listing says whether the key sees the catalogue:
curl -sf "$BASE/api/store/regions" -H "Cartbase-Key: $PUBLISHABLE_KEY" | grep -q '"regions"'
curl -sf "$BASE/api/store/products?limit=1" -H "Cartbase-Key: $PUBLISHABLE_KEY" | grep -q '"products"'An empty products list with a working key means the key's sales channels hold no products: the key is scoped (auth.md).
Step 2: the package into the app
# doc-noexec: in YOUR app's folder.
bun add @cartbase/storefront@0.42.1 # pin the version; a storefront never floats `latest`
npx cartbase@latest init # the brief your agent reads in every later sessionThree files change, and nothing else of your setup:
next.config.ts: ADD these keys to the config the app already has;
never replace the file. What is there (the Tailwind loader under
turbopack.rules, cacheComponents, partialPrefetching, your own
redirects) stays, or the build loses it: a dry run that replaced the file
shipped its CSS unprocessed. The package is source-shipped TypeScript,
the store API answers no cross-origin browser call, product pictures live
on the Cartbase media CDN, and the catalogue reads need a cache life
(step 3).
// doc-noexec, added to the existing nextConfig object
transpilePackages: ["@cartbase/storefront"],
cacheLife: { catalog: { stale: 300, revalidate: 86400, expire: 604800 } },
images: { remotePatterns: [{ protocol: "https", hostname: "cartbase.cloud" }] },
async rewrites() {
const cartbaseUrl = process.env.NEXT_PUBLIC_CARTBASE_URL || "https://admin.cartbase.ai"
return [{ source: "/api/store/:path*", destination: `${cartbaseUrl}/api/store/:path*` }]
},The catalogue life is a day because a change never waits for it: Cartbase marks your store's pages stale within a minute of every save in the admin and at every Publish, and a page is rebuilt behind its next visit. The life only bounds how old a page nobody changed can get.
What a cached read names, and who writes it. The package owns the
store's cached reads: @cartbase/storefront/catalog (getProduct,
getProductPage, getCollection, getCollections,
getCollectionProducts, getCollectionPicks, getRelatedProducts,
getComplementaryProducts, getCategory, getCategories,
getProductReviews, getProductRating, getReviewWidget,
getStoreRating, getContentPage, getBlogIndex, getArticle,
getMenuByHandle, getStoreIdentity, getStorePaymentMarks,
getConsentSettings, getTracking, getMetaobjects). Build your pages
on them and write no cache line of your own. Each carries the tag
catalog, which Cartbase purges on a change every page shows (the menu,
the brand, a price list's dates), and names what it returned, by id, from
the data it read: one product product:<id>, one collection
collection:<id>, one content page page:<id>, one post post:<id>, a
few named products (a section, related picks) each product's name, a page
of products the set's name products (and collection:<id> or
category:<id> when scoped), the list of collections collections, a
product's reviews its product's name, the store's rating reviews. An
answer of "not found" has nothing to name, so it carries the name of the
set it was asked of (products, collections, pages): the day a
product is published at that address, or put back online, its save marks
the set and the page is read again, never a day later.
A page that shows a few products never reads a page of the catalogue to
pick them. A page of products carries the set's name products, and
every product's save marks the set, so a product page that picks its
related products out of the whole catalogue is refreshed by every save in
the store. Ask for the few: getProductsById for products you know by id
(colour siblings, a cross sell, a set's contents), getRelatedProducts and
getComplementaryProducts for the platform's picks, getCollectionPicks
for a section. Only a listing page (a collection, the catalogue, a search)
reads a page of products.
Cartbase then purges only the pages that show the thing a save changed,
which is what keeps the hosting bill flat on an editing day. A read of
your own that returns a thing without naming it is a page that goes stale
until the daily life; if you must write one, name what it returns the
same way (@cartbase/storefront/catalog/names), and keep the three rules
of the module's header: nothing but the platform's answer in the result
(no clock, no random value), nothing that moves without a save in a read
a static page embeds (a sales-ordered list belongs in the browser), and a
failed read throws. The host keeps at most 128 names on one entry, which
is why a page of products carries the set's name and not every product's.
globals.css: Tailwind 4 is CSS-first, so the theme is two imports;
the package's source must be scanned or its components render unstyled;
your brand is token values below the imports, never new token names.
/* doc-noexec */
@import "tailwindcss";
@import "@cartbase/storefront/theme";
@source "../../node_modules/@cartbase/storefront/src";
@custom-variant dark (&:where(.dark, .dark *));
:root {
--primary: oklch(0.45 0.16 150);
--primary-foreground: oklch(0.985 0 0);
--radius-base: 0.75rem;
--font-body-family: Arial, Helvetica, sans-serif;
}The path in @source is relative to the CSS file: from src/app/ it is
../../node_modules/…, from app/ it is ../node_modules/….
.env.local: the one value, never committed. On Cartbase hosting it
is injected at build and .env* files are refused in a deploy.
# doc-noexec
NEXT_PUBLIC_CARTBASE_PUBLISHABLE_KEY=pk_…Then five small files under src/lib/, copied from the reference
storefront (npx create-cartbase@latest reference --key pk_… scaffolds
it beside your app with the whole docs corpus in docs/, and
cartbase pull fetches the store's hosted source):
| File | What it is |
|---|---|
config.ts |
the key, the platform origin, the locale cookie name, the store's language pack (@cartbase/storefront/locales/bg, en, es), the pricing context ({ currency_code: "eur" }) |
store-client.ts |
ONE StorefrontClient with the key and nothing about the visitor, for every catalogue read on the server |
browser-client.ts |
ONE client in the browser whose baseUrl is window.location.origin, so its calls ride the rewrite |
server-client.ts |
a client per request for one visitor's reads (the order page), reading the locale cookie |
catalog.ts |
the store's own answers to a failed read, over the package's cached reads (@cartbase/storefront/catalog: its identity, consent, tags, menus, products, collections, categories, pages, posts, reviews, each "use cache: remote" on the catalog life, each carrying catalog and the names of what it returned; a missing record answers null, a failed read throws and is never kept). A store writes no cache line of its own and cannot forget a name |
The contracts are the runbook's step 2 and step 3.
Step 3: the shell, inside your layout
Your root layout keeps its header and footer. Inside <body>, in this
order, the store's shell goes around your markup:
<ConsentInit required={consent.enabled} />first, synchronous;<StorefrontTags config={tracking} />, every marketing tag the store configured, from the store's own config, never from env;<TrackInit />, the attribution capture;<PlatformInit storeId={store.id} />, and the layout's metadata fromcreateStorefrontMetadata(...), which puts the platform mark on every page;- a client
Providerscomponent:StorefrontLocaleProviderwith the pack,CustomerSessionProvider, ONECartDrawerProviderwith the browser client, the cookie handlers andhrefsnaming pages your app has (the drawer links to/checkout, to/storefrom its empty state and to/products/{handle}from every line by default; an address your app does not have is a 404 the shopper can reach), thenCartDrawerTemplate, and the consent banner when the store's consent says so; <CartButtonClient />wherever your header wants the cart.
The reference wiring is examples/storefront/src/app/layout.tsx and
providers.tsx in the scaffold; the contracts are
components.md and consent.md.
Freshness. The store, the consent settings, the tags and the products
are read on the server, through lib/catalog.ts. A new Next.js app runs
Cache Components (cacheComponents: true is what create-next-app
writes today): every read of the store is "use cache: remote" on the
catalog life and the page prerenders, the platform asked once per
window, a change in the admin on the store within a minute. An
older app without Cache Components exports revalidate from the layout
and from every page that reads the store instead, or the store's facts
are frozen into the build:
// doc-noexec, only in an app WITHOUT cacheComponents: app/layout.tsx and every page that reads the store
export const revalidate = 300The build is the first visitor. A page that reads the store is
prerendered at build, on Cartbase as on your machine, so a read that
throws fails the build. A product the store does not have (unpublished,
renamed) answers null from getProduct; the page shows its empty state,
never throws.
Step 3b: the admin's screens, and what each one needs in the app
Every setting a merchant touches in the admin reaches the storefront through one mount. Without the mount the screen saves and nothing shows:
| Admin screen | What the app mounts | Where |
|---|---|---|
| Settings, Integrations: Meta, TikTok, Google (GA4 and Ads), GTM, Klaviyo | <StorefrontTags config={tracking} /> from the store's own config |
the root layout, after ConsentInit |
| Settings, Consent | <ConsentInit required /> first in <body>, <ConsentBanner> in the providers |
the root layout and Providers |
| Analytics (visitors, sessions, the funnel, live) | nothing of yours: StorefrontTags mounts the page views and the heartbeat, and Cartbase hosting answers them (the platform adds two files to every deploy) |
Cartbase hosting |
| The order's conversion and the attribution | <TrackInit /> in the layout, <TrackOrderPurchase> on the order page, the moments the hooks fire on their own |
the layout and /order/[key] |
| Experiments | <ExperimentsProvider client> in the providers, useExperiment(key) where a variant differs |
Providers |
| Marketing (popups, signups) | <PromoPopup client /> in the providers, /unsubscribe page |
Providers and a page |
| Reviews | the review widget on the product page, /review/[token] |
the product page |
| Customer accounts | <CustomerSessionProvider client> in the providers, /account and /account/login |
Providers and two pages |
| Navigation (menus) | getMenu by handle, rendered by you |
your header and footer |
| Search | <PredictiveSearch> in the header, /search with SearchTemplate |
your header and a page |
The contracts for each row are in components.md; the package's README shows the mounts in three lines each.
Step 4: your buy button on the store's inventory
The page that sells reads the product on the server, with the pricing
context, and draws its own buttons; each button hands its variant to the
mounted cart drawer, which opens with the line while the platform
confirms it. The variant's availability is the server's in_stock,
never computed:
// doc-noexec, a server page
import { getProduct } from "@/lib/catalog"
const product = await getProduct("ydris") // null when the store has no such handle: show an empty state
// each bundle: product.variants[i].id, .title, .calculated_price?.calculated_amount, .in_stock// doc-noexec, a client button
"use client"
import { useCartDrawer } from "@cartbase/storefront/cart-drawer/context"
const { addLine } = useCartDrawer()
const result = await addLine(variant.id, 1, { product_id, product_title, product_handle, thumbnail, variant_title, unit_price })
if (!result.ok) /* the platform's refusal: `insufficient_inventory` names a sold-out variant */Disable the button when variant.in_stock === false. For a full buy box
with option selects and quantity, mount ProductActionsWrapper. Product
pages are app/products/[handle]/page.tsx from the reference: every
handle listed in generateStaticParams through listProductHandles, the
product read through getProduct, ProductTemplate rendering it with
the pack's product labels (products.md, the product page
contract in components.md); the cart drawer links there
from every line. Collections, categories, the search box and the search
page come from the store family; never hand-build a listing.
Step 5: the checkout is Cartbase's, in your brand
Replace your order form with the checkout page: a static page that mounts the checkout with the transport alone. It reads the cart, the delivery methods and the payment methods from the browser after the paint, in the store's language, with the courier's offices and lockers, cash on delivery and the cards the store takes, and it lands on the order page:
// doc-noexec, app/checkout/page.tsx renders this client component
"use client"
import { CheckoutProvider } from "@cartbase/storefront/checkout/context"
import { CheckoutClient } from "@cartbase/storefront/checkout/checkout-client"
import { browserClient } from "@/lib/browser-client"
export function CheckoutPageClient() {
return (
<CheckoutProvider orderConfirmedPath="/order/{key}">
<CheckoutClient client={browserClient} customer={null} countryCode="bg" />
</CheckoutProvider>
)
}countryCode preselects a one-country store's country; leave it out and
the hook reads the store's markets. The look follows your tokens; the
labels follow the pack. The laws of the page are checkout.md
§ The page, and rule 4 above stands: the checkout is composed from its
nine hooks only by a store whose flow must differ, never for its look.
Step 6: the order page
/order/[key] is where the checkout lands and where every order mail
links. Copy the reference page: it reads the order from the platform by
the key on every load and renders OrderCompletedTemplate with the pack's
order labels, under a Suspense boundary. A wrong key is your not-found
page (orders.md). Under streaming the page answers 200 even
for a wrong key; that is Next.js, not a defect. The template's links name
pages your app must have: storeHref (the way back, /store by default),
contactHref and returnsHref (the help links, /contact and /returns
by default); pass your own or build those pages.
Step 7: what leaves your app
- The order form's own backend (an API route that mailed the order, a spreadsheet, a webhook): gone, the platform takes the order.
middleware.*,app/api/*, a hosting provider's configuration file: refused by the deploy.- Secret env vars: a storefront build receives the three public values and nothing else (deploy.md, Environment).
- Old addresses keep working through
redirects()innext.config.ts(/poruchkato/checkout, for instance), so links in the wild and search results land on the new page.
Step 8: run it, build it, and what you will see
# doc-noexec
bun run dev
bun run build # before every deploy: what fails here fails on the host, in the same words- The home page carries
<meta name="generator" content="Cartbase">. GET /api/store/storeon the app's own address answers the store: the rewrite and the key are right./checkoutrenders the form with the header; the delivery methods appear once an address is in.- The browser console shows
/_cb/pageviewand/_cb/heartbeatanswering 404: those are the store's analytics beacons, sent byStorefrontTagsand answered by the platform's own files on Cartbase hosting, absent locally. Nothing else breaks. - The store's configured tags mount from its config (a wrong pixel id is reported by the vendor's script in the console, nothing of yours).
- A test order placed with the store's manual method lands in the admin.
- The build's route table lists
/and/checkoutas static and/order/[key]as partially prerendered.
Step 9: deploy to the preview
# doc-noexec: from the app's folder; the CLI acts as the person signed in
npx cartbase@latest login # prints the link; approve it in the admin
npx cartbase@latest deploy --message "The storefront on Cartbase"The folder is sent as the site it is: .gitignore and .cartbaseignore
honoured, caches and .env* left out, the platform's files added. The
build runs on Cartbase, the command prints the permanent preview link
when it is built, and a build that fails prints its own error lines and
cartbase build-log <id> for the whole log; the store's staff list is
mailed too. Only what changed since the last version travels. The live
site is untouched by a deploy (deploy.md).
Then the platform reads the built version itself, on its own address: the site and its platform mark, the store API through the site (the rewrite), the checkout page, the order page, the analytics. The command waits for that verdict and prints it. A version that fails a check is broken: the command names the check and the fix and ends with an error, the version's page in the admin lists every check, the staff list is mailed, and Publish refuses the version until a deploy passes (deploy.md, the platform's checks).
Step 10: the domain, then Publish
- In the admin, Settings, Domains: add the domain. The domain's page hands over the one A record and reports connected once the domain is both owned and pointing here.
- Publish the version from the Storefront page. Publish is the merchant's own click, never a command: it moves the live address onto the build you looked at on preview, building nothing.
- Move the DNS record last: the old site serves until the record moves, and the moment it moves the Cartbase build answers on the domain. The store's mails link to the domain from then on.
Step 11: keeping it working
- Versions are pinned and bumped on purpose. A bump is: change the
version in
package.json, install, run locally, deploy, look at the preview, publish. The release notes are the package's ledger; a caret on a 0.x version never crosses a minor. - Every session starts with the brief.
cartbase initwroteCARTBASE.mdand pointed the agent brief files your app already had at it; the docs are this corpus, at https://docs.cartbase.ai and in the scaffold'sdocs/. - The store is operated from the terminal too.
cartbase resourceslists every admin endpoint as a command: products, orders, inventory, prices, settings. - What breaks, and how you learn of it. A refused bundle is a sentence in the terminal. A failed build is the build's own lines in the terminal, on the version's page in the admin and in a mail to the staff list. A built version that cannot sell (the rewrite missing, the checkout not Cartbase's, the order page throwing, the platform's mark or files gone) is marked broken by the platform's checks: named in the terminal with the fix, listed on the version's page, mailed, and refused by Publish. A failed publish is mailed and told on the page; the live site is exactly as it was.
The checklist
An agent with no other context follows this top to bottom; every line is checkable.
- The store has its products as variants, VAT prices, stock, a courier with a delivery option, a payment method, and its language set.
- The key probes answer: regions, and a products list that is not empty.
- The package is installed, pinned;
cartbase initwrote the brief. next.config.tscarries the four additions and nothing of it was removed;globals.csscarries the two imports, the@sourceline and thedarkvariant;.env.localcarries the key and is ignored by git.src/lib/holds config, store-client, browser-client, server-client, catalog, copied from the reference.- The root layout mounts, in order,
ConsentInit,StorefrontTags,TrackInit,PlatformInit, thenProviders; its metadata comes fromcreateStorefrontMetadata; every read of the store goes throughlib/catalog.ts. - Every buy button adds through
useCartDrawer().addLineor the package's buy box; availability is the server'sin_stock. /checkoutmountsCheckoutClientand nothing else;/order/[key]is the reference page.- The app's own API routes, middleware and hosting configuration are gone; old addresses redirect.
bun run buildpasses locally; the route table is as step 8 says.cartbase deployprints the preview link and the platform's checks, all passed; the preview is looked at: the home page, a buy, the checkout with an address, a test order.- The domain is added and connected; the version is published from the admin; the DNS record moves last.
Danger zones
What breaks without an error at the moment it is done.
- Replacing
next.config.tsinstead of adding to it: the Tailwind loader goes and the components ship unstyled; Cache Components go and every page renders per visit. - A page that throws at build: one missing product fails the whole
build on the host.
getProductanswers null; pages read it that way. - A wrong
@sourcepath: the components render with no styles and no error; the path is relative to the CSS file. - Two
CartDrawerProviders or aCheckoutClientoutside the providers: two carts, a checkout that reads none. cookies()or the cart in the root layout: every page of the store renders on every visit.- Money computed in the app, a method hidden by the app, a total sent that the platform did not compute: the platform refuses the order at Place order, and the shopper reads a refusal.
- A key that is not this store's: the catalogue reads empty or another store's, with no error.
- A secret in the app: the build never receives it, and code that expects one is a design error.
- Edits inside
node_modules: gone at the next install, supported by nobody. - Deploying from a folder that fell behind the hosted source: a
deploy is a full snapshot, so files another deploy added are removed.
cartbase pullfirst when more than one hand deploys. - Renamed token names: the components reference the names; a renamed name is a component with no colour.