> ## Documentation Index
> Fetch the complete documentation index at: https://www.commercengine.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Production Storefront

> A complete agent execution contract for planning, building, validating, and shipping a production-ready Commerce Engine storefront.

This page defines what an AI coding agent should do when asked to build a complete Commerce Engine storefront. It is intentionally stricter than a feature tutorial: the agent must inspect the project, load multiple skills, use exact SDK contracts, implement the full customer journey, and prove the result builds.

## Start with one install

Run inside the storefront repository:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx skills add commercengine/skills
```

Then give the agent the storefront brief. The skills package should be treated as the architecture and implementation playbook; the LLM-first reference supplies exact operation contracts only when needed.

## Execution contract

<Steps>
  <Step title="Inspect before editing">
    The agent must read:

    * `package.json` and the package-manager lockfile
    * framework and deployment configuration
    * current route structure
    * existing styling and component conventions
    * environment-variable examples
    * lint, typecheck, test, and build scripts

    It should preserve the application's conventions unless the request explicitly asks for a migration.
  </Step>

  <Step title="Resolve the architecture">
    The agent must identify:

    * framework and rendering model
    * public versus session data boundaries
    * Hosted Checkout versus custom checkout
    * whether account UI is required outside checkout
    * catalog model: grouped products or flattened SKUs
    * deployment target and adapter

    For a new storefront, Hosted Checkout is the default unless the brief explicitly requires a custom checkout UI.
  </Step>

  <Step title="Load all applicable skills">
    A complete storefront is not a single-feature task. Load setup, catalog, cart/checkout, the relevant SSR/framework patterns, and—when required—authentication and orders. Use webhooks only when the storefront also needs server-side integrations such as fulfilment sync or notifications.
  </Step>

  <Step title="Retrieve exact contracts">
    Before writing an SDK call, fetch the corresponding operation page from `llm-docs.commercengine.io` using Markdown content negotiation or a `.md` suffix. Fetch schema pages only for types the implementation actually needs.
  </Step>

  <Step title="Study the nearest production starter">
    Compare the generated architecture with the closest starter implementation. Pay special attention to session bootstrap, Hosted Checkout token synchronization, route rendering, URL state, structured data, loading states, failure handling, and deployment configuration.
  </Step>

  <Step title="Implement in dependency order">
    Build foundation and public catalog first, then live session and checkout, then account and post-purchase pages. Do not build session-dependent UI before the session boundary is correct.
  </Step>

  <Step title="Validate before claiming completion">
    Run the repository's typecheck, lint/check, tests, and production build. Exercise the implemented customer journeys and report any step that could not be verified.
  </Step>
</Steps>

## Canonical route matrix

A storefront does not need every optional marketing page, but the commerce journey should be complete.

| Capability     | Typical route                     | Required behaviour                                                                               |
| -------------- | --------------------------------- | ------------------------------------------------------------------------------------------------ |
| Home           | `/`                               | Public, cacheable catalog content; useful empty/failure state                                    |
| Category / PLP | `/category/[slug]` or `/products` | Pagination, filters where applicable, stable URL state, scoped category resolution               |
| Search         | `/search?q=`                      | Debounced query, stale-response protection, empty state, facet reset between queries             |
| PDP            | `/product/[slug]`                 | Correct product/variant model, purchasability, option URL state, related products                |
| Cart           | Hosted Checkout drawer or `/cart` | Correct first-add behaviour, quantity updates, expiry recovery, final `to_be_paid` total         |
| Checkout       | Hosted Checkout or `/checkout`    | One auth session, addresses, fulfilment, payment, definitive completion status                   |
| Login          | Checkout-managed or `/login`      | OTP/password flow appropriate to the store; anonymous-cart continuity                            |
| Account        | `/account`                        | Logged-in guard and current profile state                                                        |
| Orders         | `/account/orders`                 | History, detail, shipment/payment status, conditional cancellation                               |
| Not found      | framework convention              | Real 404 for confirmed missing resources; do not turn transient API failures into permanent 404s |

## Rendering and session rules

* Use public accessors for catalog and store configuration when no live user identity is needed.
* Use framework session accessors only at request- or browser-session boundaries.
* Never create anonymous sessions during build-time rendering or static generation.
* Mount the framework bootstrap once near the root for first-visit session creation.
* Returning users should hydrate from existing session cookies/storage.
* When Hosted Checkout and the Storefront SDK are both installed, the Storefront SDK is the session owner and checkout must use `authMode: "provided"` with token updates in both directions.

## Production-quality catalog rules

### PLP and search

* Use `searchProducts` for filtered or faceted listings; it returns flattened sellable Items/SKUs.
* Resolve category identifiers before issuing category-scoped requests. An unresolved category must not silently fall back to the full catalog.
* Escape filter values according to the search filter syntax.
* Prevent slower, older requests from replacing newer search results.
* Reset captured facets when the search query changes.

### PDP

* Use option query parameters as canonical state for multi-option products.
* Match variants against all associated option keys.
* Disable option combinations that cannot resolve to a purchasable variant.
* Keep Add to Cart disabled until a valid variant is selected when `has_variant` is true.
* Allow purchase when `stock_available` is true or the item permits backorder.
* Use `variant_id: null` for products without variants.

## SEO and structured data

For server-rendered or prerendered storefronts:

* generate unique title and description metadata for category and product routes
* emit canonical URLs where appropriate
* provide Open Graph and social metadata
* emit Product and Breadcrumb structured data for PDPs
* include price, currency, availability, and aggregate rating only when valid data exists
* safely serialize JSON-LD so catalog content cannot terminate the script element
* return real 404s only for confirmed missing resources

## Performance baseline

The production starters demonstrate the expected direction:

* prerender or cache public catalog routes where the framework supports it
* keep session work out of public root rendering
* parallelize independent reads
* preserve stable layout dimensions for images and checkout loading
* load Hosted Checkout without blocking the main render
* avoid duplicate providers, listeners, and checkout initialization
* clean up checkout listeners on unmount and guard asynchronous initialization against resurrection after teardown
* use the framework's deployment adapter rather than assuming a Node-only runtime

## Deployment-aware generation

The agent must inspect the target platform rather than assume one runtime.

* **Cloudflare Workers:** verify the framework adapter and workerd compatibility. Apply the documented `User-Agent` workaround where required by the framework/runtime combination.
* **Vercel:** use the framework's supported adapter or output preset; do not carry Cloudflare-only plugins into the Vercel build.
* **Netlify:** use the framework's official Netlify adapter and confirm server/edge compatibility.
* **Static deployment:** only prerender routes that do not require request-time session state.

Environment variables must follow the framework's public prefix conventions and should be represented in an `.env.example` file.

## Validation gates

A production-ready claim requires all applicable gates:

### Repository gates

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
[ ] dependencies install successfully
[ ] typecheck passes
[ ] lint/check passes
[ ] tests pass, when present
[ ] production build passes
[ ] deployment adapter emits the expected output
```

### Commerce journey gates

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
[ ] public catalog renders without creating a session
[ ] first live-session action succeeds
[ ] product and variant URLs restore state after refresh
[ ] first Add to Cart creates a cart correctly
[ ] subsequent mutations preserve every requested change
[ ] Hosted Checkout initializes once and reports ready state
[ ] Storefront SDK and Hosted Checkout share one session
[ ] login/logout preserves anonymous continuity
[ ] checkout completion is handled
[ ] account and order pages reject anonymous access correctly
[ ] missing product/category behaviour is correct
[ ] transient API failure has a recoverable UI state
```

### Quality gates

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
[ ] keyboard-accessible interactive controls
[ ] visible focus states
[ ] responsive layout on mobile and desktop
[ ] useful loading, empty, error, and unavailable states
[ ] metadata and JSON-LD validated
[ ] no secrets embedded beyond publishable storefront credentials
[ ] no raw tokens or sensitive payloads in logs
```

## Copy-paste prompt

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
Build a production-ready Commerce Engine storefront in this repository.

First inspect the existing project, framework, routes, styles, scripts, deployment adapter, and environment conventions. Install and use the Commerce Engine skills package. Load every relevant skill rather than treating this as a single-feature task.

Use @commercengine/storefront and the framework-specific wrapper. Use public accessors for public catalog rendering and session accessors only for live cart, auth, account, and order flows. Use Commerce Engine Hosted Checkout unless the brief explicitly requires a custom checkout. When the Storefront SDK and Hosted Checkout are both present, use authMode: "provided" and synchronize tokens in both directions.

Before writing each SDK operation, retrieve its exact current contract from https://llm-docs.commercengine.io using a .md URL or Accept: text/markdown. Import Commerce Engine types directly from the SDK and do not create duplicate API interfaces.

Use https://github.com/tark-ai/ce-starter-projects as implementation evidence for the selected framework. Match its production patterns where applicable: rendering boundaries, session bootstrap, checkout lifecycle, URL state, error recovery, SEO, safe JSON-LD, performance, and deployment configuration.

Implement the complete route and customer-journey matrix appropriate to the brief. Run typecheck, lint/check, tests, and the production build. Fix failures. At the end, list what was implemented, the commands that passed, the customer journeys verified, and anything that could not be tested.
```

<Warning>
  Do not claim production readiness from code inspection alone. A successful build and verified customer journey are part of the deliverable.
</Warning>
