Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Update Storefront docs and fixed create-spree-app storefront CI gener… (#14348)
Damian Legawiec55a05e37c2ae
diff --git a/docs/developer/core-concepts/channels.mdx b/docs/developer/core-concepts/channels.mdxindex 5f2f4d1837..52e1a9372f 100644--- a/docs/developer/core-concepts/channels.mdx+++ b/docs/developer/core-concepts/channels.mdx@@ -21,6 +21,8 @@ Every store ships with one default channel named *Online Store*. You can add mor| `code` | URL-safe slug, stable identifier sent via the `X-Spree-Channel` header | `pos` || `active` | When `false`, the channel stops accepting orders | `true` || `default` | Exactly one channel per store is the default. Used as a fallback when no channel header is present and as the auto-publish target for new products | `true` |+| `storefront_access` | Controls what an anonymous visitor may see: `public`, `prices_hidden`, or `login_required`. Unset inherits the store's setting. See [Storefront Access Gating](#storefront-access-gating) | `login_required` |+| `guest_checkout` | Whether an order may be placed without an account on this channel. Unset inherits the store's setting | `false` || `preferred_order_routing_strategy` | Optional per-channel override of the store's [Order Routing](/developer/core-concepts/shipments#order-routing) strategy | `Spree::OrderRouting::Strategy::Rules` |`code` is normalized to a URL-safe slug on save — `POS` becomes `pos`, `Point of Sale!` becomes `point-of-sale`. Leaving `code` blank derives it from `name`.@@ -92,6 +94,55 @@ Every order is attributed to one channel. The channel is set from the `X-Spree-CThis attribution drives reporting (best-selling by channel, revenue per channel) and per-channel order routing — see [Order Routing](/developer/core-concepts/shipments#order-routing).+### Storefront Access Gating++<Since version="5.6" />++A channel's `storefront_access` decides what an **anonymous** visitor — a request with no authenticated customer — may see. Logged-in customers are never gated. The posture is one of three values:++| Mode | Guest sees catalog | Guest sees prices | Use case |+|---|---|---|---|+| `public` | Yes | Yes | The default. An open storefront — anyone can browse; guests can also check out when `guest_checkout` is enabled. |+| `prices_hidden` | Yes | No — prices come back `null` | A catalog you want discoverable, with pricing revealed only after sign-in (e.g. a trade catalog for lead generation). |+| `login_required` | No — reads rejected with `401` | No | A fully gated surface — a guest can't read the catalog at all (e.g. a members-only or B2B wholesale portal). |++The gate is enforced by the **Store API**, not the storefront, so a storefront app can't loosen it:++- **`login_required`** — every gated read returns `401` for an unauthenticated request. Endpoints that must stay reachable before sign-in (authentication, password reset, reference data like countries and currencies) are exempt.+- **`prices_hidden`** — reads succeed, but every money field is serialized as `null` for a guest. The storefront renders these as a sign-in prompt rather than a price.++A companion control, **`guest_checkout`**, decides whether an order can be placed without an account on the channel. It's independent of `storefront_access` — a `public` channel can still require accounts, and the two are resolved separately.++#### Store fallback++Both controls fall back to the owning [Store](/developer/core-concepts/stores) when the channel's own value is unset — the same inheritance pattern as the channel's order-routing strategy. `storefront_access` resolves to the channel value, then the store value, and finally `public` when neither is set. This lets you set a store-wide default (e.g. "all channels require login") and override per channel where needed.++<CodeGroup>++```typescript Admin SDK+// Gate a channel behind sign-in, and require accounts at checkout+await adminClient.channels.update('ch_wholesale', {+ storefront_access: 'login_required',+ guest_checkout: false,+})++// Clear the channel value to inherit the store's default+await adminClient.channels.update('ch_wholesale', {+ storefront_access: null,+})+```++```bash cURL+curl -X PATCH 'https://api.mystore.com/api/v3/admin/channels/ch_wholesale' \+ -H 'X-Spree-API-Key: sk_xxx' \+ -H 'Content-Type: application/json' \+ -d '{ "storefront_access": "login_required", "guest_checkout": false }'+```++</CodeGroup>++Switching a channel between modes takes effect immediately — the posture is resolved per request, so no cache warm-up or redeploy is needed. The Next.js storefront's [wholesale portal](/developer/storefront/nextjs/wholesale) is a worked example of a `login_required` / `prices_hidden` channel driving the UI.+## Publishing Products on Channels### Dashboard@@ -179,3 +230,4 @@ The write contract is **full-set**: the array represents the complete desired st- [Order Routing](/developer/core-concepts/shipments#order-routing) — Channels can override the store's routing strategy- [Store SDK: Products](/developer/sdk/store/products) — Channel-scoped product listing and filtering- [Admin SDK: Resources](/developer/sdk/admin/resources) — How `adminClient.channels.addProducts` and other resource methods are structured+- [Wholesale Portal](/developer/storefront/nextjs/wholesale) — A gated channel driving the Next.js storefront's B2B surfacediff --git a/docs/developer/core-concepts/stores.mdx b/docs/developer/core-concepts/stores.mdxindex d7d826e34f..82263234a2 100644--- a/docs/developer/core-concepts/stores.mdx+++ b/docs/developer/core-concepts/stores.mdx@@ -5,7 +5,9 @@ description: Understand Spree Stores — the top-level tenant boundary that scop## Overview-The StThe Store is the top-level tenant in Spree. Every resource — products, orders, channels, markets, taxonomies — belongs to exactly one store. A store owns its [channels](/developer/core-concepts/channels) (online, POS, wholesale, …), its [markets](/developer/core-concepts/markets) (region/currency/locale), and its [product catalog](/developer/core-concepts/products).tore Attributes+The Store is the top-level tenant in Spree. Every resource — products, orders, channels, markets, taxonomies — belongs to exactly one store. A store owns its [channels](/developer/core-concepts/channels) (online, POS, wholesale, …), its [markets](/developer/core-concepts/markets) (region/currency/locale), and its [product catalog](/developer/core-concepts/products).++## Store Attributes| Attribute | Description ||-----------|-------------|@@ -19,6 +21,8 @@ The StThe Store is the top-level tenant in Spree. Every resource — products, o| `mail_from_address` | Sender address for transactional emails || `logo_url` | URL to the store's logo || `facebook`, `twitter`, `instagram` | Social media links |+| `storefront_access` | Store-wide default for anonymous [storefront access gating](/developer/core-concepts/channels#storefront-access-gating) (`public`, `prices_hidden`, `login_required`). Each channel can override it |+| `guest_checkout` | Store-wide default for whether orders can be placed without an account. Each channel can override it |## Fetching Store Information@@ -56,6 +60,10 @@ Two different ways to split a store, often confused:A single Online Store channel can serve multiple markets (one storefront → many regions). Conversely, POS and Online channels can share the same market (same currency/locale, different selling surfaces).+### Storefront access defaults++The store sets the fallback for **storefront access gating** — whether anonymous visitors may browse, see prices, or must sign in first — via `storefront_access` (`public`, `prices_hidden`, `login_required`) and the companion `guest_checkout` control. Each channel inherits these unless it sets its own value, so you can gate a whole store or just one channel (e.g. a `login_required` wholesale channel on an otherwise `public` store). The full behavior of each mode and how the Store API enforces it lives in [Channels → Storefront Access Gating](/developer/core-concepts/channels#storefront-access-gating).+## Store ResourcesEach store owns its own resources. Products, orders, channels, markets, and taxonomies in one store are independent from another.@@ -66,7 +74,7 @@ Each store owns its own resources. Products, orders, channels, markets, and taxo| [**Markets**](/developer/core-concepts/markets) | A store has many markets, each defining a geographic region with its own currency and locale || [**Orders**](/developer/core-concepts/orders) | An order belongs to one store and one channel || [**Products**](/developer/core-concepts/products) | A product belongs to one store. Its visibility across channels is controlled by [publications](/developer/core-concepts/channels#publishing-products-on-channels). |-| [**Taxonomies**](/developer/core-concepts/products#categories) | A taxonomy belongs to one store |+| [**Categories**](/developer/core-concepts/products#categories) | A category belongs to one store || [**Payment Methods**](/developer/core-concepts/payments) | A payment method belongs to one store || [**Shipping Methods**](/developer/core-concepts/shipments) | A shipping method belongs to one store || [**Promotions**](/developer/core-concepts/promotions) | A promotion belongs to one store |@@ -84,4 +92,5 @@ If you need one Spree backend to serve **multiple distinct merchant brands** —- [Markets](/developer/core-concepts/markets) — Multi-region commerce within a store- [Products](/developer/core-concepts/products) — Product catalog- [Orders](/developer/core-concepts/orders) — Order management and checkout+- [Wholesale Portal](/developer/storefront/nextjs/wholesale) — A gated B2B storefront surface built on channel access gating- [Admin SDK](/developer/sdk/admin/quickstart) — TypeScript client for the Admin API used to read and update store configurationdiff --git a/docs/developer/storefront/nextjs/architecture.mdx b/docs/developer/storefront/nextjs/architecture.mdxindex f85393f307..356705310d 100644--- a/docs/developer/storefront/nextjs/architecture.mdx+++ b/docs/developer/storefront/nextjs/architecture.mdx@@ -38,20 +38,29 @@ src/│ │ │ └── [slug]/ # Product details│ │ ├── t/[...permalink]/ # Category pages│ │ └── categories/ # Category overview-│ └── (checkout)/ # Checkout layout (no header/footer)-│ ├── checkout/[id]/ # Checkout flow-│ └── order-placed/[id]/ # Order confirmation+│ ├── (checkout)/ # Checkout layout (no header/footer)+│ │ ├── checkout/[id]/ # Checkout flow+│ │ └── order-placed/[id]/ # Order confirmation+│ └── (wholesale)/ # Opt-in B2B portal (gated — see Wholesale guide)+│ └── wholesale/+│ ├── page.tsx # Trade catalog+│ ├── products/[slug]/ # Wholesale PDP+│ ├── cart/ # Wholesale cart+│ ├── quick-order/ # SKU quick-order form+│ ├── apply/ # Trade-account application+│ └── _components/ # Gate, header, sign-in wall, pending, guest browse├── components/│ ├── cart/ # CartDrawer│ ├── checkout/ # AddressStep, DeliveryStep, PaymentStep, etc.│ ├── layout/ # Header, Footer, CountrySwitcher│ ├── navigation/ # Breadcrumbs-│ ├── products/ # ProductCard, ProductGrid, Filters, MediaGallery, VariantPicker+│ ├── products/ # ProductCard, ProductGrid, Filters, MediaGallery, HiddenPricePrompt│ └── search/ # SearchBar├── contexts/│ ├── AuthContext.tsx # Auth state│ ├── CartContext.tsx # Client-side cart state sync│ ├── CheckoutContext.tsx # Checkout flow state+│ ├── HiddenPricingContext.tsx # Prices-hidden signal for wholesale guests│ └── StoreContext.tsx # Store/locale/currency state├── hooks/│ ├── useCarouselProducts.ts # Product carousel data@@ -72,7 +81,11 @@ src/│ ├── payment.ts # Payment processing│ ├── products.ts # Product queries│ ├── categories.ts # Categories- │ └── utils.ts # Shared helpers (actionResult, withFallback)+ │ ├── wholesale.ts # Wholesale channel + catalog + quick-order+ │ ├── utils.ts # Shared helpers (actionResult, withFallback)+ │ └── … # One file per domain — see src/lib/data/+ ├── spree/ # Spree integration (client, cookies, auth refresh, middleware, surface)+ ├── wholesale.ts # Approval check + volume-pricing helpers└── utils/ # Client utilities├── address.ts # Address formatting├── cookies.ts # Cookie helpers@@ -81,6 +94,8 @@ src/└── product-query.ts # Product filter query builder```+The `(wholesale)` route group is an opt-in B2B portal, off unless a wholesale channel is configured. Its gating, surfaces, and pricing modes are covered in the [Wholesale Portal](/developer/storefront/nextjs/wholesale) guide.+## Authentication Flow1. User submits login form@@ -107,17 +122,9 @@ export async function getCustomer() {}```-## Multi-Region Support--The storefront supports multiple countries and currencies via URL segments:--```-/us/en/products # US store, English-/de/de/products # German store, German-/uk/en/products # UK store, English-```+## Multi-Region-A middleware (`src/proxy.ts`) uses `createSpreeMiddleware` from `src/lib/spree` to detect the visitor's country and locale, then redirects to the correct URL prefix. The `CountrySwitcher` component lets users change regions manually.+The storefront serves multiple countries, currencies, and languages from one deployment via `/{country}/{locale}` URL segments and an edge middleware that detects and persists the visitor's region. See the [Multi-Region](/developer/storefront/nextjs/multi-region) guide.## Server Actionsdiff --git a/docs/developer/storefront/nextjs/customization.mdx b/docs/developer/storefront/nextjs/customization.mdxindex ed1abe0317..04db923511 100644--- a/docs/developer/storefront/nextjs/customization.mdx+++ b/docs/developer/storefront/nextjs/customization.mdx@@ -1,35 +1,19 @@---title: Customization-description: Fork, customize, and extend the Spree Next.js Storefront+description: Customize and extend the Spree Next.js Storefront----## Forking the Starter+The storefront is yours to modify — the code ships in your project so you can restyle it, swap components, and change the data layer directly. Scaffold a project with [`create-spree-app`](/developer/storefront/nextjs/quickstart#installation), then edit the storefront under `apps/storefront/`.-The recommended approach is to fork the repository so you can customize freely while pulling upstream updates.+## Tracking Upstream Updates-### 1. Fork on GitHub--Go to [github.com/spree/storefront](https://github.com/spree/storefront) and click **Fork**.--### 2. Clone Your Fork--```bash-git clone https://github.com/YOUR_USERNAME/storefront.git-cd storefront-npm install-```--### 3. Add Upstream Remote+The storefront evolves upstream. To keep pulling improvements while you customize, own the code in your own Git repository (a fork of [spree/storefront](https://github.com/spree/storefront), or your own repo with the storefront as an upstream remote):```bash+# Point an "upstream" remote at the official storefrontgit remote add upstream https://github.com/spree/storefront.git-```--### 4. Pull Upstream Updates-When the official starter gets updates, pull them into your fork:--```bash+# Pull in the latest changesgit fetch upstreamgit merge upstream/main```@@ -138,66 +122,8 @@ export default async function YourNewPage() {## Transactional Emails-Customer-facing emails are rendered in the storefront using [react-email](https://react.email) and sent via [Resend](https://resend.com). The Spree backend delivers order/shipment/password events to the storefront via [webhooks](/developer/core-concepts/webhooks).--### Templates--Email templates are React components in `src/lib/emails/`:--| File | Event | Description |-|------|-------|-------------|-| `order-confirmation.tsx` | `order.completed` | Items, totals, addresses, delivery method |-| `order-canceled.tsx` | `order.canceled` | Cancellation notice with items |-| `shipment-shipped.tsx` | `order.shipped` | Tracking number and link |-| `password-reset.tsx` | `customer.password_reset_requested` | Reset button and fallback link |-| `newsletter-confirmation.tsx` | `newsletter_subscriber.subscription_requested` | Double opt-in confirmation link |--Customize templates by editing these files directly. They use `@react-email/components` for email-safe layout primitives.--### Previewing--```bash-npm run email:dev-```--Opens the react-email dev server with mock data for all templates at `http://localhost:3000`.--### Webhook Handler--The webhook route (`src/app/api/webhooks/spree/route.ts`) uses `createWebhookHandler` from `src/lib/spree/webhooks`:--```typescript-import { createWebhookHandler } from '@/lib/spree/webhooks'--export const POST = createWebhookHandler({- secret: process.env.SPREE_WEBHOOK_SECRET!,- handlers: {- 'order.completed': handleOrderCompleted,- 'order.canceled': handleOrderCanceled,- 'order.shipped': handleOrderShipped,- 'customer.password_reset_requested': handlePasswordReset,- 'newsletter_subscriber.subscription_requested': handleNewsletterConfirmation,- },-})-```--To add a new email type:--1. Create a template in `src/lib/emails/`-2. Add a handler function in `src/lib/webhooks/handlers.ts`-3. Register the event in `route.ts`-4. Subscribe to the event in Spree Admin → Webhooks--### Local Development--In dev, emails are written to `.next/emails/` as HTML files — no Resend key needed. Use [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/) to receive webhooks locally:--```bash-cloudflared tunnel --url http://localhost:3001-```--For full setup details, see [Sending out Emails](/developer/deployment/emails).+The storefront can render and send its own order, shipment, and account emails with react-email and Resend, driven by Spree webhooks. See the dedicated [Transactional Emails](/developer/storefront/nextjs/emails) guide.## Building a Custom Storefront-If you prefer to build from scratch instead of forking the starter, you can use the `@spree/sdk` package directly in any Next.js application. The storefront's `src/lib/spree/` directory contains reusable helpers for cookie-based auth, locale resolution, middleware, and webhook verification that you can copy into your own project.+If you prefer to build from scratch instead of using the starter, you can use the `@spree/sdk` package directly in any Next.js application. The storefront's `src/lib/spree/` directory contains reusable helpers for cookie-based auth, locale resolution, middleware, and webhook verification that you can copy into your own project.diff --git a/docs/developer/storefront/nextjs/deployment.mdx b/docs/developer/storefront/nextjs/deployment.mdxindex 6985d73482..8ee2de08b8 100644--- a/docs/developer/storefront/nextjs/deployment.mdx+++ b/docs/developer/storefront/nextjs/deployment.mdx@@ -5,28 +5,7 @@ description: Deploy the Spree Next.js Storefront to Vercel, Docker, or any Node.## Environment Variables-Set these variables in your hosting platform's dashboard or `.env` file.--### Required--| Variable | Description |-|----------|-------------|-| `SPREE_API_URL` | Your Spree API endpoint (e.g., `https://api.mystore.com`) |-| `SPREE_PUBLISHABLE_KEY` | Publishable API key from your Spree admin |--<Note>- These are server-side only variables — no `NEXT_PUBLIC_` prefix needed since all API calls happen in Server Actions.-</Note>--### Optional--| Variable | Description | Default |-|----------|-------------|---------|-| `GTM_ID` | Google Tag Manager container ID | _(disabled)_ |-| `SENTRY_DSN` | Sentry DSN for error tracking | _(disabled)_ |-| `SENTRY_ORG` | Sentry organization slug | _(none)_ |-| `SENTRY_PROJECT` | Sentry project slug | _(none)_ |-| `SENTRY_AUTH_TOKEN` | Sentry auth token (for source maps in CI) | _(none)_ |+At minimum, set `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` in your hosting platform's dashboard or `.env` file. See [Environment Variables](/developer/storefront/nextjs/environment-variables) for the full reference — analytics, error tracking, wholesale, emails, and SEO.## Production Build@@ -45,7 +24,13 @@ Vercel is the recommended deployment platform for Next.js applications.1. Push your code to GitHub2. Go to [vercel.com/new](https://vercel.com/new) and import your repository-3. Add environment variables (`SPREE_API_URL`, `SPREE_PUBLISHABLE_KEY`)+3. Add environment variables:+ - `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` (required)+ - `SPREE_WEBHOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` — for [transactional emails](/developer/storefront/nextjs/emails)+ - `GTM_ID` — optional, Google Tag Manager+ - `SENTRY_DSN`, `SENTRY_ORG`, `SENTRY_PROJECT`, `SENTRY_AUTH_TOKEN` — optional, error tracking with readable stack traces++ See the [Environment Variables reference](/developer/storefront/nextjs/environment-variables) for the full list.4. Click **Deploy**Vercel automatically detects the Next.js framework and configures the build settings.@@ -63,58 +48,52 @@ Every pull request gets a unique preview URL, making it easy to test storefront## Docker-Create a `Dockerfile` in your project root:+A multi-stage `Dockerfile` ships at the repo root. It uses Next.js standalone output to produce a small (~240 MB) image on `node:22-alpine`, runs as a non-root user, and exposes port `3001`.-```dockerfile-FROM node:20-alpine AS base--FROM base AS deps-WORKDIR /app-COPY package.json package-lock.json ./-RUN npm ci --production=false+<Note>+ `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` are required at **build time** — the storefront prerenders pages against the Spree API. Point them at a Spree instance reachable from wherever you run `docker build` (hosted Spree, a tunnel, or `host.docker.internal` for a local backend on Docker Desktop).+</Note>-FROM base AS builder-WORKDIR /app-COPY --from=deps /app/node_modules ./node_modules-COPY . .-RUN npm run build+Build and run:-FROM base AS runner-WORKDIR /app-ENV NODE_ENV=production+```bash+docker build \+ --build-arg SPREE_API_URL=https://your-spree.example.com \+ --build-arg SPREE_PUBLISHABLE_KEY=your_publishable_key \+ -t spree-storefront .-RUN addgroup --system --gid 1001 nodejs-RUN adduser --system --uid 1001 nextjs+docker run -p 3001:3001 --env-file .env.local spree-storefront+```-COPY --from=builder /app/public ./public-COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./-COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static+### Sentry source maps at build time-USER nextjs-EXPOSE 3000-ENV PORT=3000-ENV HOSTNAME="0.0.0.0"+`SENTRY_AUTH_TOKEN` is passed via a BuildKit secret so it never lands in image layers or the build cache. The other Sentry vars are regular build args:-CMD ["node", "server.js"]+```bash+SENTRY_AUTH_TOKEN=... docker build \+ --build-arg SPREE_API_URL=... \+ --build-arg SPREE_PUBLISHABLE_KEY=... \+ --build-arg SENTRY_DSN=... \+ --build-arg SENTRY_ORG=... \+ --build-arg SENTRY_PROJECT=... \+ --secret id=sentry_auth_token,env=SENTRY_AUTH_TOKEN \+ -t spree-storefront .```-<Note>- Enable standalone output in your `next.config.ts` for Docker deployments:-- ```typescript- const nextConfig = {- output: 'standalone',- }- ```-</Note>+### Building against a local Spree backend-Build and run:+On Docker Desktop (macOS/Windows), reach the host's Spree via `host.docker.internal`:```bash-docker build -t spree-storefront .-docker run -p 3000:3000 \- -e SPREE_API_URL=https://api.mystore.com \- -e SPREE_PUBLISHABLE_KEY=your_key \+docker build \+ --add-host=host.docker.internal:host-gateway \+ --build-arg SPREE_API_URL=http://host.docker.internal:3000 \+ --build-arg SPREE_PUBLISHABLE_KEY=your_publishable_key \+ -t spree-storefront .++docker run -p 3001:3001 \+ --add-host=host.docker.internal:host-gateway \+ --env-file .env.local \spree-storefront```@@ -135,7 +114,7 @@ npm run buildnpm start```-The server listens on port `3000` by default. Set the `PORT` environment variable to change it.+The server listens on port `3001`. Set the `PORT` environment variable to change it.## CI/CDdiff --git a/docs/developer/storefront/nextjs/emails.mdx b/docs/developer/storefront/nextjs/emails.mdxnew file mode 100644index 0000000000..a54e384b24--- /dev/null+++ b/docs/developer/storefront/nextjs/emails.mdx@@ -0,0 +1,86 @@+---+title: Transactional Emails+description: Render and send order, shipment, and account emails from the Spree Next.js Storefront with react-email, Resend, and Spree webhooks+---++The storefront can own its customer-facing transactional emails instead of the Spree backend. Emails are rendered with [react-email](https://react.email) and sent via [Resend](https://resend.com); the Spree backend delivers order, shipment, and account events to the storefront over [webhooks](/developer/core-concepts/webhooks).++```+Spree Backend → Webhook POST → /api/webhooks/spree → render email → send via Resend+(signed HMAC) (signature verified) (react-email) (or write to disk in dev)+```++## Templates++Email templates are React components in `src/lib/emails/`:++| File | Event | Description |+|------|-------|-------------|+| `order-confirmation.tsx` | `order.completed` | Items, totals, addresses, delivery method |+| `order-canceled.tsx` | `order.canceled` | Cancellation notice with items |+| `shipment-shipped.tsx` | `order.shipped` | Tracking number and link |+| `password-reset.tsx` | `customer.password_reset_requested` | Reset button and fallback link |++Customize a template by editing its file directly — they use `@react-email/components` for email-safe layout primitives.++## Previewing++Run the storefront in development and open [http://localhost:3001/dev/emails](http://localhost:3001/dev/emails):++```bash+npm run dev+```++Each template renders with sample data via `@react-email/render`. The route is gated to non-production environments.++## Configuration++Add these to `.env.local`:++```env+SPREE_WEBHOOK_SECRET=your_webhook_endpoint_secret_key+RESEND_API_KEY=re_your_resend_api_key # production only+EMAIL_FROM=Your Store <[email protected]> # production only+```++In development no `RESEND_API_KEY` is needed — emails are written to `.next/emails/` as HTML files with a `file://` link logged to the console.++## Webhook Handler++The webhook route (`src/app/api/webhooks/spree/route.ts`) wires events to handlers with `createWebhookHandler` from `src/lib/spree/webhooks`. Signature verification and event routing are handled for you:++```typescript+import { createWebhookHandler } from '@/lib/spree/webhooks'++const handler = createWebhookHandler({+ secret: process.env.SPREE_WEBHOOK_SECRET!,+ handlers: {+ 'order.completed': handleOrderCompleted,+ 'order.canceled': handleOrderCanceled,+ 'order.shipped': handleOrderShipped,+ 'customer.password_reset_requested': handlePasswordReset,+ },+})+```++To add a new email type:++1. Create a template in `src/lib/emails/`.+2. Add a handler function in `src/lib/webhooks/handlers.ts`.+3. Register the event in `route.ts`.+4. Subscribe to the event in **Spree Admin → Settings → Developers → Webhooks**.++## Setup++1. **Create a webhook endpoint** in Spree Admin → Settings → Developers → Webhooks. Subscribe to `order.completed`, `order.canceled`, `order.shipped`, and `customer.password_reset_requested`, and copy the secret key into `SPREE_WEBHOOK_SECRET`.++2. **Receive webhooks locally.** Expose the storefront with a public URL so Spree can reach it — the simplest option is a [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/):++ ```bash+ brew install cloudflared+ cloudflared tunnel --url http://localhost:3001+ ```++ Use the tunnel URL as the webhook endpoint URL in Spree Admin.++For the backend perspective on delivering these events, see [Sending out Emails](/developer/deployment/emails).diff --git a/docs/developer/storefront/nextjs/environment-variables.mdx b/docs/developer/storefront/nextjs/environment-variables.mdxnew file mode 100644index 0000000000..8cb859902d--- /dev/null+++ b/docs/developer/storefront/nextjs/environment-variables.mdx@@ -0,0 +1,92 @@+---+title: Environment Variables+description: Every environment variable the Spree Next.js Storefront reads, with defaults and when to set it+---++Configuration lives in `.env.local` (copy `.env.example` to start). Variables **without** a `NEXT_PUBLIC_` prefix are server-side only and never reach the browser; `NEXT_PUBLIC_` variables are inlined into the client bundle at build time, so only put non-secret values there.++## Required++| Variable | Description |+|----------|-------------|+| `SPREE_API_URL` | Your Spree API endpoint (e.g. `http://localhost:3000` in dev, `https://api.mystore.com` in production) |+| `SPREE_PUBLISHABLE_KEY` | Publishable API key from your Spree admin |++<Note>+ In a Docker build these two are also required at **build time** — the storefront prerenders pages against the Spree API. See [Deployment](/developer/storefront/nextjs/deployment).+</Note>++## Store defaults++Used by the middleware for initial redirects before API data loads, and as build-time fallbacks for sitemap/SEO generation.++| Variable | Description | Default |+|----------|-------------|---------|+| `NEXT_PUBLIC_DEFAULT_COUNTRY` | Default country ISO code — should match your store's `default_country_iso` | `us` |+| `NEXT_PUBLIC_DEFAULT_LOCALE` | Default locale code — should match your store's `default_locale` | `en` |+| `NEXT_PUBLIC_SITE_URL` | Public site URL, used for sitemap and `robots.txt` generation (e.g. `https://mystore.com`) | _(required for sitemap)_ |+| `NEXT_PUBLIC_STORE_NAME` | Store name used in metadata fallbacks | `Spree Store` |+| `NEXT_PUBLIC_STORE_DESCRIPTION` | Store description used in metadata fallbacks | _(sample text)_ |++## SEO & social++Optional overrides for site metadata and the Organization JSON-LD. When unset, values fall back to store settings from the Spree API.++| Variable | Description |+|----------|-------------|+| `STORE_SEO_TITLE` | Default `<title>` |+| `STORE_META_DESCRIPTION` | Default meta description |+| `STORE_META_KEYWORDS` | Default meta keywords |+| `STORE_TWITTER` | Twitter/X handle or URL |+| `STORE_FACEBOOK` | Facebook page URL |+| `STORE_INSTAGRAM` | Instagram URL |+| `STORE_LOGO_URL` | Logo URL for Organization JSON-LD |+| `STORE_SUPPORT_EMAIL` | Customer support email |++## Wholesale B2B portal++The [wholesale portal](/developer/storefront/nextjs/wholesale) is an opt-in addon, off by default.++| Variable | Description | Default |+|----------|-------------|---------|+| `SPREE_WHOLESALE_CHANNEL` | Enable switch — the code of a gated Spree channel to bind the `/wholesale` surface to. Unset means DTC-only: every wholesale entry point is hidden and the routes 404 | _(disabled)_ |+| `SPREE_WHOLESALE_PUBLISHABLE_KEY` | Channel-scoped publishable key for the wholesale surface. Optional — the channel header selects the channel, so this falls back to `SPREE_PUBLISHABLE_KEY` | _(falls back to `SPREE_PUBLISHABLE_KEY`)_ |++## Transactional emails++See the [Transactional Emails](/developer/storefront/nextjs/emails) guide for the full setup.++| Variable | Description | Default |+|----------|-------------|---------|+| `SPREE_WEBHOOK_SECRET` | Webhook endpoint secret key that signs incoming Spree webhooks | _(disabled)_ |+| `RESEND_API_KEY` | [Resend](https://resend.com) API key for sending emails in production | _(dev: writes to disk)_ |+| `EMAIL_FROM` | "From" address for transactional emails (e.g. `Store <[email protected]>`) | `[email protected]` |++## Payments++Publishable keys for client-side payment SDKs, read when the matching gateway is enabled. Set the key for whichever provider(s) you use.++| Variable | Description |+|----------|-------------|+| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key (`pk_…`) |++## Analytics++| Variable | Description | Default |+|----------|-------------|---------|+| `GTM_ID` | Google Tag Manager container ID (e.g. `GTM-XXXXXXX`). Leave empty to disable | _(disabled)_ |++## Error tracking (Sentry)++| Variable | Description | Default |+|----------|-------------|---------|+| `SENTRY_DSN` | Sentry DSN — set to enable error tracking (e.g. `https://[email protected]/0`) | _(disabled)_ |+| `SENTRY_ORG` | Sentry organization slug (for source map uploads) | _(none)_ |+| `SENTRY_PROJECT` | Sentry project slug (for source map uploads) | _(none)_ |+| `SENTRY_AUTH_TOKEN` | Sentry auth token (for source map uploads in CI) | _(none)_ |+| `SENTRY_SEND_DEFAULT_PII` | Send PII (IP addresses, cookies, user data) to Sentry server-side | `false` |+| `NEXT_PUBLIC_SENTRY_SEND_DEFAULT_PII` | Send PII to Sentry client-side | `false` |++<Warning>+ PII collection is disabled by default. Only set the `SENTRY_SEND_DEFAULT_PII` variables to `true` if you have appropriate user consent or a privacy policy covering this data.+</Warning>diff --git a/docs/developer/storefront/nextjs/multi-region.mdx b/docs/developer/storefront/nextjs/multi-region.mdxnew file mode 100644index 0000000000..30bcec23bf--- /dev/null+++ b/docs/developer/storefront/nextjs/multi-region.mdx@@ -0,0 +1,75 @@+---+title: Multi-Region+description: How the Spree Next.js Storefront serves multiple countries, currencies, and languages from a single deployment via URL segments and edge middleware+---++The storefront serves multiple countries, currencies, and languages from a single deployment. Region is encoded in the URL, detected automatically for first-time visitors by middleware, and mapped to a [Spree Market](/developer/core-concepts/markets) — the model that bundles a country, currency, and locale — so every server-side fetch resolves prices and content for the right region.++## URL structure++Every route is prefixed with a country and locale segment:++```+/us/en/products # US market, English+/de/de/products # German market, German+/uk/en/products # UK market, English+```++The `[country]` and `[locale]` segments are the first two dynamic params of the App Router tree (`src/app/[country]/[locale]/…`). Because region lives in the path, every URL is shareable and independently cacheable, and search engines index each region separately.++## The middleware++A visitor who lands on a bare path (no region prefix) is redirected to the correct `/{country}/{locale}/…` URL by an edge middleware. It's wired in `src/proxy.ts`:++```typescript+import { createSpreeMiddleware } from '@/lib/spree/middleware'+import { getDefaultCountry, getDefaultLocale } from '@/lib/store'++export const proxy = createSpreeMiddleware({+ defaultCountry: getDefaultCountry(),+ defaultLocale: getDefaultLocale(),+})++export const config = {+ matcher: ['/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*$).*)'],+}+```++`createSpreeMiddleware` (from `src/lib/spree`) does three things:++- **Redirects** bare paths to `/{country}/{locale}/…`.+- **Detects** the visitor's country and locale (see below).+- **Syncs** `spree_country` and `spree_locale` cookies with the URL segments, so server-side fetches via `getLocaleOptions()` resolve the same market the URL asks for.++Requests that already carry a `/{country}/{locale}` prefix pass through untouched — the middleware only refreshes the cookies to match.++### Detection chain++For a request without a region prefix, each value is resolved from the first source that has it:++| Value | Resolution order |+|-------|------------------|+| **Country** | `spree_country` cookie → `x-vercel-ip-country` / `cf-ipcountry` geo header → default |+| **Locale** | `spree_locale` cookie → `Accept-Language` header (primary tag) → default |++Geo headers are set by the hosting edge — `x-vercel-ip-country` on Vercel, `cf-ipcountry` behind Cloudflare. On a host that provides neither, detection falls back to `Accept-Language` for locale and the configured default for country. A returning visitor's cookie always wins, so a manual region change sticks.++### Configuration++`createSpreeMiddleware` accepts:++| Option | Description | Default |+|--------|-------------|---------|+| `defaultCountry` | Fallback country ISO when nothing else matches | `us` |+| `defaultLocale` | Fallback locale when nothing else matches | `en` |+| `staticRoutes` | Path prefixes to skip | `['/_next', '/api', '/dev', '/favicon.ico']` |++In the storefront these defaults come from `NEXT_PUBLIC_DEFAULT_COUNTRY` and `NEXT_PUBLIC_DEFAULT_LOCALE` (see [Environment Variables](/developer/storefront/nextjs/environment-variables)). The `matcher` in `proxy.ts` additionally excludes API routes, Next.js internals, and any path with a file extension, so the middleware only runs on page navigations.++## Switching regions++The `CountrySwitcher` component (in `src/components/layout/`) lets a visitor change region manually. Selecting a new region navigates to the matching URL prefix; the middleware then updates the `spree_country` / `spree_locale` cookies so the choice persists across future visits.++## How region reaches the data layer++Region-aware reads don't take a country/locale argument — they call `getLocaleOptions()` from `src/lib/spree`, which reads the `spree_country` / `spree_locale` cookies the middleware keeps in sync with the URL. That value is passed to `@spree/sdk`, which sends it to the Store API so prices, currency, and translated content come back for the right [market](/developer/core-concepts/markets). See [Architecture](/developer/storefront/nextjs/architecture) for the wider server-first data flow.diff --git a/docs/developer/storefront/nextjs/quickstart.mdx b/docs/developer/storefront/nextjs/quickstart.mdxindex 8545816710..fbe98e9dee 100644--- a/docs/developer/storefront/nextjs/quickstart.mdx+++ b/docs/developer/storefront/nextjs/quickstart.mdx@@ -34,19 +34,19 @@ The [Spree Storefront](https://github.com/spree/storefront) is a production-read## Installation-### Option 1: Fork the Repository (Recommended)+### Recommended: create-spree-app-Fork the repository on GitHub, then clone your fork:+The fastest way to get a full project — Spree backend, this Next.js storefront, and the `spree` CLI, wired together — is [`create-spree-app`](/developer/create-spree-app/quickstart):```bash-git clone https://github.com/YOUR_USERNAME/storefront.git-cd storefront-npm install+npx create-spree-app my-store```-This gives you a full copy you can customize freely while still being able to pull upstream updates.+The storefront is included by default (pass `--no-storefront` to skip it). It's scaffolded into `apps/storefront/` with its `.env.local` already pointing at the backend, so it boots against real data with no manual key wiring.-### Option 2: Clone Directly+### Standalone++To run the storefront on its own — against an existing Spree backend, or to work on the storefront repo directly — clone it and install:```bashgit clone https://github.com/spree/storefront.git@@ -54,6 +54,8 @@ cd storefrontnpm install```+Then follow [Configuration](#configuration) to point it at your Spree API. If you plan to customize and track upstream changes, [fork first](/developer/storefront/nextjs/customization#tracking-upstream-updates).+## ConfigurationCopy the environment file:@@ -83,6 +85,10 @@ npm run devOpen [http://localhost:3001](http://localhost:3001) in your browser.+<Note>+ Testing Apple Pay / Google Pay locally needs a public HTTPS URL. See [Wallet Payments in Development](/developer/storefront/nextjs/wallet-payments).+</Note>+## Production Build```bashdiff --git a/docs/developer/storefront/nextjs/testing.mdx b/docs/developer/storefront/nextjs/testing.mdxnew file mode 100644index 0000000000..21f3668fed--- /dev/null+++ b/docs/developer/storefront/nextjs/testing.mdx@@ -0,0 +1,85 @@+---+title: Testing+description: Run the Spree Next.js Storefront's unit tests with Vitest and its end-to-end suite with Playwright against a real Spree backend+---++The storefront ships two test layers: fast unit/integration tests with Vitest, and a browser end-to-end suite with Playwright that runs against a real Spree backend booted in Docker.++## Unit & integration (Vitest)++```bash+npm test # one-shot+npm run test:watch # watch mode+```++## End-to-end (Playwright)++The E2E suite drives a browser against a real Spree backend. `npm run e2e:up` boots the backend — Postgres, Redis, and the official `ghcr.io/spree/spree:latest` image from `e2e-backend/docker-compose.yml` — then seeds it and mints an API key through the official [`@spree/cli`](/developer/cli/quickstart) (`spree seed`, `spree sample-data`, `spree api-key create`), installed as a dev dependency. No `create-spree-app` setup is required.++```bash+# 1. Export a Stripe test-mode key pair from your own Stripe sandbox.+# Both keys must belong to the same account — Stripe no longer+# publishes a working sample secret key, and a mismatched pair makes+# the checkout payment step fail.+export STRIPE_PUBLISHABLE_KEY=pk_test_…+export STRIPE_SECRET_KEY=sk_test_…++# 2. Boot Spree + Postgres + Redis, seed sample data, register a Stripe+# payment gateway, mint a publishable key, and write .env.e2e.+npm run e2e:up++# 3. Run the suite. Playwright boots `next dev` against .env.e2e.+npm run test:e2e++# Optional: interactive UI mode.+npm run test:e2e:ui++# Tear everything down.+npm run e2e:down+```++The checkout test pays with card `4242 4242 4242 4242` through Stripe's [test mode](https://docs.stripe.com/keys). PaymentIntents land in whichever Stripe test account owns the keys you exported.++### CI++In CI, set `STRIPE_SECRET_KEY` as a repository secret and `STRIPE_PUBLISHABLE_KEY` as a repository variable (**Settings → Secrets and variables → Actions**). The E2E job skips itself on fork PRs, where GitHub never exposes repository secrets.++## Testing against a customized backend++<Note>+ By default the E2E suite runs against the stock official Spree image (`ghcr.io/spree/spree:latest`), so it verifies the storefront against a **vanilla Spree** — not a backend with your own extensions, serializers, or seed data.+</Note>++The E2E stack reads a `SPREE_IMAGE` env var and falls back to the stock image when it's unset. Set it to any image that exposes the Store API on the container's port `3000`, and the suite runs against that backend instead.++### Your own Spree image++If you already publish a customized Spree image:++```bash+SPREE_IMAGE=ghcr.io/your-org/your-spree:latest npm run e2e:up+npm run test:e2e+```++### A `create-spree-app` project's backend++A project scaffolded with [`create-spree-app`](/developer/create-spree-app/quickstart) has its customizable Spree in `backend/` (built from `backend/Dockerfile`) and this storefront in `apps/storefront/`. Build that backend into a local image and point the suite at it — this is what tests the storefront against the **exact Spree you deploy**, extensions and all:++```bash+# From the project root — build the customized backend image+docker build -t project-spree:e2e ./backend++# From apps/storefront — run E2E against it+cd apps/storefront+SPREE_IMAGE=project-spree:e2e npm run e2e:up+npm run test:e2e+npm run e2e:down+```++<Note>+ New `create-spree-app` projects wire this into the generated storefront CI workflow automatically — the workflow builds `backend/Dockerfile` and runs the storefront E2E against that image rather than stock Spree.+</Note>++### Interactive / manual++To click through the storefront against a running backend (no E2E harness), point it there directly: set `SPREE_API_URL` and `SPREE_PUBLISHABLE_KEY` in `.env.local` (see [Environment Variables](/developer/storefront/nextjs/environment-variables)) and run `npm run dev`.diff --git a/docs/developer/storefront/nextjs/wallet-payments.mdx b/docs/developer/storefront/nextjs/wallet-payments.mdxnew file mode 100644index 0000000000..7f17910346--- /dev/null+++ b/docs/developer/storefront/nextjs/wallet-payments.mdx@@ -0,0 +1,52 @@+---+title: Wallet Payments in Development+description: Test Apple Pay and Google Pay against a local Spree Next.js Storefront using a public HTTPS URL+---++Apple Pay and Google Pay require HTTPS **and a publicly-reachable URL** — Stripe verifies the payment method domain from the internet, so `localhost` and locally-trusted certificates (e.g. `mkcert` + `lvh.me`) won't pass domain verification. The simplest way to expose your local storefront with a valid public HTTPS URL is [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/).++## Setup++1. Install `cloudflared`:++ ```bash+ brew install cloudflared+ ```++2. Start the dev server normally (HTTP on port 3001):++ ```bash+ npm run dev+ ```++3. In a second terminal, expose it through a quick tunnel:++ ```bash+ cloudflared tunnel --url http://localhost:3001+ ```++ The output will contain a URL like `https://<random-words>.trycloudflare.com`.++4. Register that URL in your [Stripe Payment method domains](https://dashboard.stripe.com/settings/payment_methods/domains).++5. Open the tunnel URL in your browser and test the Express Checkout buttons in the cart.++## Stable tunnel URLs++`next.config.ts` already allows `*.trycloudflare.com` via `allowedDevOrigins`, so quick tunnels work out of the box. Every time you restart `cloudflared tunnel --url ...` you get a new random subdomain — if you need a stable URL (to avoid re-registering in Stripe on each run), set up a [named tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/#using-named-tunnels) on your own domain.++## The Spree backend must also be publicly reachable++The storefront's server-side fetches go to `SPREE_API_URL`, but image URLs and a few other backend-served paths (e.g. the Apple Pay domain-verification file under `/.well-known/apple-developer-merchantid-domain-association`) are fetched by the browser directly and must resolve from the public internet.++Point `SPREE_API_URL` at a hosted Spree (e.g. `*.spree.sh`, `*.vendo.dev`, your own staging) or expose your local Spree with another tunnel:++```bash+cloudflared tunnel --url http://localhost:3000+```++When tunneling a local Rails app, allow the tunnel host in the backend's `.env`:++```env+RAILS_DEVELOPMENT_HOSTS=.trycloudflare.com+```diff --git a/docs/developer/storefront/nextjs/wholesale.mdx b/docs/developer/storefront/nextjs/wholesale.mdxnew file mode 100644index 0000000000..dac5b83b81--- /dev/null+++ b/docs/developer/storefront/nextjs/wholesale.mdx@@ -0,0 +1,84 @@+---+title: Wholesale Portal+description: The opt-in B2B wholesale surface and how channel-backed surfaces work+---++## What the Wholesale Portal Is++The storefront ships an optional **wholesale portal** at `/wholesale` — a gated B2B surface for approved trade buyers. It runs on a separate Spree sales channel but shares the same storefront app and Spree backend as the public direct-to-consumer (DTC) store, so a single deployment serves both audiences: the open catalog for shoppers and a login-gated trade catalog with volume pricing for wholesale buyers.++The portal is an **opt-in addon**. It is off by default; a DTC-only storefront never renders any wholesale UI.++<Note>+The wholesale portal is a **reference implementation**, not a fixed feature. It demonstrates one shape — a gated B2B surface running *alongside* an open DTC store — but the same building blocks (channels, [surfaces](#surfaces-and-channel-switching), and [access gating](#gating-modes)) support the whole spectrum. You can invert the default and make the storefront closed or limited: gate the *primary* DTC channel with `login_required` or `prices_hidden` for a members-only or invite-only shop, drop the public catalog entirely and ship a login-first B2B storefront, or run several gated channels with no open surface at all. Treat this page as a worked example to adapt, not a prescription — the storefront is yours to reshape.+</Note>++## Surfaces and Channel Switching++A **surface** is a distinct sales context backed by its own Spree [channel](/developer/core-concepts/channels). The storefront models two out of the box — `dtc` (the public storefront) and `wholesale` (the trade portal) — but the mechanism is general: any channel on your backend can back its own surface.++The surface selects which SDK client a request goes through. A channel-bound client sends the channel code on every request via the `X-Spree-Channel` header, and the Store API [resolves the request against that channel](/developer/core-concepts/channels#resolution-at-request-time) — its catalog, pricing, and access rules. In the SDK this is the `channel` client option:++```ts+import { createClient } from '@spree/sdk'++const wholesaleClient = createClient({+ baseUrl: process.env.SPREE_API_URL,+ publishableKey: process.env.SPREE_PUBLISHABLE_KEY,+ channel: 'wholesale', // sent as X-Spree-Channel on every request+})+```++Alternatively, a **channel-bound publishable key** carries the channel server-side: when a key is scoped to a channel on the backend, the API assigns that channel to the request without needing the header. Either path works; the header is the simplest and is what the storefront uses by default.++Because each surface has its own client, cart cookies, and cache keys, a customer can hold an open DTC cart and an open wholesale cart at the same time without them mixing. The customer session (JWT) is shared — it's the same person signing in — so only the cart splits, never the auth.++To add your own channel-backed surface, follow the same pattern: create the channel on the backend, add a client bound to its code, and thread the surface through the routes that should target it.++## Enabling Wholesale++Wholesale turns on through a single environment variable:++- **`SPREE_WHOLESALE_CHANNEL`** — the enable switch. Set it to the code of a gated channel on your backend (e.g. `wholesale`). There is **no default**: when it is unset, the storefront runs DTC-only — the wholesale nav link, footer link, and homepage section are hidden, and every `/wholesale` route returns 404.+- **`SPREE_WHOLESALE_PUBLISHABLE_KEY`** — optional. The channel header alone selects the channel, so this falls back to `SPREE_PUBLISHABLE_KEY`. Set it only to bind a channel-scoped publishable key.++The backend must have a [channel](/developer/core-concepts/channels) whose code matches `SPREE_WHOLESALE_CHANNEL`. Its [`storefront_access`](/developer/core-concepts/channels#storefront-access-gating) posture decides how much a guest can see — the portal supports both `login_required` (guests are walled off entirely) and `prices_hidden` (guests browse the catalog but not prices). See [Gating Modes](#gating-modes) below. Spree installs seed a `login_required` wholesale channel by default; switching to `prices_hidden` is a single flag on that same channel — no new channel or seed data.++## How Gating Works End to End++Two independent checks gate the portal — one at the **channel** (how much of the catalog a guest may see), one at the **customer** (whether a buyer may transact at trade pricing). The channel check is set by the channel's [gating mode](#gating-modes); the customer check is always the same.++**Channel access** is enforced by the Store API, not the storefront — the storefront can't loosen it. Depending on the channel's `storefront_access` posture, a guest is either rejected outright (`login_required`) or served the catalog with money fields returned as `null` (`prices_hidden`). This is a general channel feature; see [Channels → Storefront Access Gating](/developer/core-concepts/channels#storefront-access-gating) for how it's resolved and enforced.++**Buyer approval.** Being logged in isn't enough; a buyer must be *approved*. Approval is membership in the **Wholesale** [customer group](/developer/core-concepts/pricing#customer-group-rule) — an admin adds an applicant to the group to approve them. The storefront reads `customer_groups` on `customers/me` and branches accordingly:++- **Guest** — sees the sign-in / apply wall (`login_required`), or the read-only catalog with sign-in-for-pricing prompts (`prices_hidden`).+- **Signed in, not in the group** — sees an application-pending state. Signing in never skips approval: an authenticated but unapproved buyer cannot transact under either mode.+- **Signed in and in the group** — gets the full portal: trade catalog, quick order, and the wholesale cart.++**Trade pricing** is unlocked by volume. The seeded model grants a trade price once a line reaches a minimum quantity of the same item (10 or more per item in the sample data). The applicable volume rule lives on a backend [Price List](/developer/core-concepts/pricing#price-lists); the storefront surfaces the trade price the API returns for a qualifying quantity.++## Gating Modes++A channel's `storefront_access` posture is one of three values. The wholesale portal supports the two gated modes; the third describes a fully public channel like DTC.++| Mode | Guest sees catalog | Guest sees prices | Guest can order |+|---|---|---|---|+| `login_required` | No — hard `401`, sign-in wall | No | No |+| `prices_hidden` | Yes — read-only | No — "sign in for pricing" | No — "sign in to order" |+| `public` | Yes | Yes | Yes (subject to guest checkout) |++**`login_required`** is the strictest posture and the seeded default. The Store API rejects any unauthenticated request to the channel with `401`, so a guest can't read wholesale catalog or pricing at all. The storefront shows the sign-in / apply wall in place of every gated page.++**`prices_hidden`** opens the catalog to guests while keeping pricing private. The channel doesn't reject unauthenticated requests, but the API serializes every money field as `null` for a guest. In the portal, a guest browses the catalog and product pages read-only: each price renders a **"sign in for pricing"** prompt, and add-to-cart becomes **"sign in to order."** Ordering surfaces (cart, quick order) still require sign-in — a guest is redirected to the sign-in flow rather than shown an empty wholesale cart. Approval is unchanged: signing in reveals list prices, and joining the Wholesale group unlocks trade pricing. This mode suits a trade catalog you want discoverable (for SEO or lead generation) without exposing negotiated pricing.++**`public`** is an ungated channel — the posture the DTC store runs on. It's listed here for completeness; a wholesale channel would not normally use it.++Switching a wholesale channel between the two supported modes is a single change to [`storefront_access`](/developer/core-concepts/channels#storefront-access-gating) on the backend — set on the channel, or inherited from the [store's default](/developer/core-concepts/stores#storefront-access-defaults). Nothing in the storefront needs redeploying — the portal reads the channel's posture at request time and adapts. Login and signup always run through the same approval flow regardless of mode.++## Related Documentation++- [Channels](/developer/core-concepts/channels) — The sales channel that backs the wholesale surface, and the general [Storefront Access Gating](/developer/core-concepts/channels#storefront-access-gating) mechanism the portal builds on+- [Stores](/developer/core-concepts/stores) — Store-level [defaults](/developer/core-concepts/stores#storefront-access-defaults) that channels inherit+- [Pricing](/developer/core-concepts/pricing) — [Price Lists](/developer/core-concepts/pricing#price-lists) and the [Customer Group Rule](/developer/core-concepts/pricing#customer-group-rule) behind approval and trade pricing+- [Store SDK: Configuration](/developer/sdk/configuration) — `setChannel` and the channel client option used to bind a surfacediff --git a/docs/docs.json b/docs/docs.jsonindex 181b76c5ba..a346bcb876 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -245,8 +245,13 @@"pages": ["developer/storefront/nextjs/quickstart","developer/storefront/nextjs/architecture",+ "developer/storefront/nextjs/multi-region","developer/storefront/nextjs/customization",+ "developer/storefront/nextjs/emails","developer/storefront/nextjs/wholesale",+ "developer/storefront/nextjs/wallet-payments",+ "developer/storefront/nextjs/testing",+ "developer/storefront/nextjs/environment-variables","developer/storefront/nextjs/deployment"]}diff --git a/packages/create-spree-app/CHANGELOG.md b/packages/create-spree-app/CHANGELOG.mdindex ee9f34ac67..406313bcba 100644--- a/packages/create-spree-app/CHANGELOG.md+++ b/packages/create-spree-app/CHANGELOG.md@@ -1,72 +1,83 @@# create-spree-app+## 1.1.4++### Patch Changes++- Generated projects now test the storefront against their own customized+ backend, not stock Spree. The storefront's CI workflow is relocated to the+ project root (as `storefront-ci.yml`, renamed so it doesn't shadow the backend+ check) and adapted to build `backend/Dockerfile` into a local image, which the+ end-to-end suite boots via the new `SPREE_IMAGE` override — so E2E exercises the+ exact Spree the project deploys, extensions and seed data included.+## 1.1.3### Patch Changes- Single-node deployment out of the box: the relocated `render.yaml` now-deploys the backend as a Docker service built from the repo root (verbatim-from the starter — no more `rootDir` rewriting), so the ejected backend and-your customized `apps/dashboard` ship in one image with the dashboard-served same-origin at `/dashboard`. New projects also get a root-`.dockerignore` keeping that build context to sources.+ deploys the backend as a Docker service built from the repo root (verbatim+ from the starter — no more `rootDir` rewriting), so the ejected backend and+ your customized `apps/dashboard` ship in one image with the dashboard+ served same-origin at `/dashboard`. New projects also get a root+ `.dockerignore` keeping that build context to sources.## 1.1.2### Patch Changes- The React Dashboard is no longer prompted for — it's a work-in-progress-Developer Preview, and a yes/no prompt reads as a recommendation. Include it-with the new `--react-dashboard` flag (or later via `spree add dashboard`);-the `--no-dashboard` flag is gone with the prompt.+ Developer Preview, and a yes/no prompt reads as a recommendation. Include it+ with the new `--react-dashboard` flag (or later via `spree add dashboard`);+ the `--no-dashboard` flag is gone with the prompt.- Cut the duplicate output when scaffolding with the React Dashboard: the-delegated `spree add dashboard` summary card is suppressed (its content-lives in the main card), and the success card plus generated README present-the dashboard's dev server as THE admin — the `cd apps/dashboard &&+ delegated `spree add dashboard` summary card is suppressed (its content+ lives in the main card), and the success card plus generated README present+ the dashboard's dev server as THE admin — the `cd apps/dashboard &&pnpm dev` command with the admin credentials and a dim classic-admin-pointer — instead of two admins where only the classic one carried-credentials. `spree dev` co-runs that dev server with the API (one command,-whole environment), so the printed URL is live as soon as the stack is up.-For testing unreleased CLIs, the `SPREE_CLI_VERSION` env var overrides the-scaffolded `@spree/cli` dependency spec (a range or a `file:` tarball path-— same name as the starter Dockerfile's ARG). The scaffolded pin's floor is-now `^2.4.4` — the CLI behavior the scaffold relies on; an older resolve-would reject the new flags and silently drop the dashboard phase. Projects scaffolded without the dashboard keep the classic-`/admin` block exactly as before. User-facing wording now calls the Rails-app what it is to a storefront/dashboard developer — the Spree API-("Customize the Spree API", "Start the Spree API") — ahead of the planned-`backend/` → `api/` directory rename. Requires `@spree/cli` 2.4.4.+ pointer — instead of two admins where only the classic one carried+ credentials. `spree dev` co-runs that dev server with the API (one command,+ whole environment), so the printed URL is live as soon as the stack is up.+ For testing unreleased CLIs, the `SPREE_CLI_VERSION` env var overrides the+ scaffolded `@spree/cli` dependency spec (a range or a `file:` tarball path+ — same name as the starter Dockerfile's ARG). The scaffolded pin's floor is+ now `^2.4.4` — the CLI behavior the scaffold relies on; an older resolve+ would reject the new flags and silently drop the dashboard phase. Projects scaffolded without the dashboard keep the classic+ `/admin` block exactly as before. User-facing wording now calls the Rails+ app what it is to a storefront/dashboard developer — the Spree API+ ("Customize the Spree API", "Start the Spree API") — ahead of the planned+ `backend/` → `api/` directory rename. Requires `@spree/cli` 2.4.4.## 1.1.1### Patch Changes- A finished `create-spree-app` run now always means a working app. The-optional storefront and React Dashboard phases used to abort the whole-scaffold on failure — before the final setup phase (`spree init`: fresh-image pull, seeded database, API keys) ever ran — leaving a project whose-first boot silently started a stale, locally cached Spree image. Those-phases now warn and continue with a recovery command, cleaning up their-partial `apps/` directory so the recovery command actually works, and setup-always runs. Project docs (README.md, CLAUDE.md, dependabot.yml) are-generated after those phases from their actual outcomes, so they never-document an app whose setup failed. When services can't start during-scaffolding (`--no-start`, Docker off), the first `spree dev` completes-setup automatically (requires `@spree/cli` 2.4.2), honoring the sample-data-choice now persisted in `.env` (`SPREE_SAMPLE_DATA`), and the printed next-steps plus the generated README reflect that — nobody has to know-`spree init` exists.+ optional storefront and React Dashboard phases used to abort the whole+ scaffold on failure — before the final setup phase (`spree init`: fresh+ image pull, seeded database, API keys) ever ran — leaving a project whose+ first boot silently started a stale, locally cached Spree image. Those+ phases now warn and continue with a recovery command, cleaning up their+ partial `apps/` directory so the recovery command actually works, and setup+ always runs. Project docs (README.md, CLAUDE.md, dependabot.yml) are+ generated after those phases from their actual outcomes, so they never+ document an app whose setup failed. When services can't start during+ scaffolding (`--no-start`, Docker off), the first `spree dev` completes+ setup automatically (requires `@spree/cli` 2.4.2), honoring the sample-data+ choice now persisted in `.env` (`SPREE_SAMPLE_DATA`), and the printed next+ steps plus the generated README reflect that — nobody has to know+ `spree init` exists.## 1.1.0### Minor Changes- Offer the React Dashboard (Developer Preview) as an optional component: a new-prompt (and `--no-dashboard` flag) scaffolds it into `apps/dashboard/` by-delegating to the project-local `spree add dashboard` (the CLI bundles the-starter template with version pins matching its release), and wires the-README, CLAUDE.md, and Dependabot config.+ prompt (and `--no-dashboard` flag) scaffolds it into `apps/dashboard/` by+ delegating to the project-local `spree add dashboard` (the CLI bundles the+ starter template with version pins matching its release), and wires the+ README, CLAUDE.md, and Dependabot config.New projects now default to **pnpm** when it's installed — it's what theSpree packages and docs are built around. An explicit invoking agentdiff --git a/packages/create-spree-app/package.json b/packages/create-spree-app/package.jsonindex 1c46450c55..25237aa8f0 100644--- a/packages/create-spree-app/package.json+++ b/packages/create-spree-app/package.json@@ -1,6 +1,6 @@{"name": "create-spree-app",- "version": "1.1.3",+ "version": "1.1.4","description": "Create a new Spree Commerce project with a single command","type": "module","bin": "./dist/index.js",diff --git a/packages/create-spree-app/src/storefront.ts b/packages/create-spree-app/src/storefront.tsindex b1bd7bfd6c..7f3a298a74 100644--- a/packages/create-spree-app/src/storefront.ts+++ b/packages/create-spree-app/src/storefront.ts@@ -10,6 +10,91 @@ export async function downloadStorefront(projectDir: string): Promise<void> {const storefrontDir = path.join(projectDir, 'apps', 'storefront')await execa('git', ['clone', '--depth', '1', STOREFRONT_REPO, storefrontDir], { stdio: 'ignore' })fs.rmSync(path.join(storefrontDir, '.git'), { recursive: true, force: true })++ prepareStorefrontTemplate(projectDir)+}++/** Local image tag the generated E2E workflow builds `backend/` into. */+const PROJECT_SPREE_IMAGE = 'project-spree:e2e'++/**+ * Tidy the freshly-cloned storefront for the nested `apps/storefront/` layout:+ * relocate its CI workflow to the project root (adapted to run from+ * apps/storefront, and to build the project's own `backend/` image for the E2E+ * suite instead of stock Spree), and drop the storefront's now-empty `.github`.+ *+ * @param projectDir absolute path to the wrapper project root+ */+export function prepareStorefrontTemplate(projectDir: string): void {+ const storefrontDir = path.join(projectDir, 'apps', 'storefront')+ const srcGithub = path.join(storefrontDir, '.github')++ // Relocate the CI workflow only when it exists — and create the destination+ // dir only then, so we never leave an empty root workflows/ behind.+ const ci = path.join(srcGithub, 'workflows', 'ci.yml')+ if (fs.existsSync(ci)) {+ const destWorkflows = path.join(projectDir, '.github', 'workflows')+ fs.mkdirSync(destWorkflows, { recursive: true })+ const content = fs.readFileSync(ci, 'utf-8')+ // Renamed so it doesn't collide with the backend's relocated `ci.yml`.+ fs.writeFileSync(+ path.join(destWorkflows, 'storefront-ci.yml'),+ adaptStorefrontWorkflow(content),+ )+ }++ // The storefront's `.github` isn't meaningful at the wrapper root; always+ // drop it so no stale, non-running copy is left behind (rmSync with force+ // is a no-op when it's absent).+ fs.rmSync(srcGithub, { recursive: true, force: true })+}++/**+ * Rewrite the storefront CI workflow for the wrapper project's nested layout:+ *+ * - rename it (`CI` → `Storefront CI`) so it doesn't shadow the backend's check;+ * - run every job from `apps/storefront/` via a per-job default;+ * - in the E2E job, build the project's own `backend/Dockerfile` into a local+ * image and boot the E2E stack against it (`SPREE_IMAGE`), so the storefront+ * is tested against the customized backend the project deploys — not stock+ * Spree.+ */+export function adaptStorefrontWorkflow(content: string): string {+ let result = content++ // Disambiguate the workflow name from the backend's "CI".+ result = result.replace(/^name:\s*CI\s*$/m, 'name: Storefront CI')++ // Run every job's `run:` steps from apps/storefront. Anchored on each+ // `runs-on:` so the default is inserted at each job's indentation.+ result = result.replace(+ /^([ \t]*)runs-on:.*$/gm,+ (line, indent) =>+ `${line}\n\n${indent}defaults:\n${indent} run:\n${indent} working-directory: apps/storefront`,+ )++ // The E2E "Boot Spree backend" step must run against the project's own+ // backend image. Insert a build step just before it (building the repo-root+ // `backend/` — checkout clones the whole project, so it's a sibling of+ // apps/storefront), and set SPREE_IMAGE on the boot step's env.+ result = result.replace(+ /^([ \t]*)- name: Boot Spree backend[^\n]*\n([ \t]*)run: (.*)$/m,+ (_match, stepIndent, runIndent, runCmd) => {+ const build =+ `${stepIndent}- name: Build project backend image\n` ++ // working-directory default targets apps/storefront, so reach the+ // sibling backend/ via the workspace root.+ `${runIndent}run: docker build -t ${PROJECT_SPREE_IMAGE} "$GITHUB_WORKSPACE/backend"\n`+ const boot =+ `${stepIndent}- name: Boot Spree backend (project backend image)\n` ++ `${runIndent}env:\n` ++ `${runIndent} SPREE_IMAGE: ${PROJECT_SPREE_IMAGE}\n` ++ `${runIndent}run: ${runCmd}`+ return `${build}${boot}`+ },+ )++ return result}export async function installRootDeps(projectDir: string, pm: PackageManager): Promise<void> {diff --git a/packages/create-spree-app/tests/storefront.test.ts b/packages/create-spree-app/tests/storefront.test.tsnew file mode 100644index 0000000000..892b2315f6--- /dev/null+++ b/packages/create-spree-app/tests/storefront.test.ts@@ -0,0 +1,146 @@+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { adaptStorefrontWorkflow, prepareStorefrontTemplate } from '../src/storefront'++// Trimmed mirror of the storefront's .github/workflows/ci.yml: a multi-job+// workflow named "CI" whose E2E job boots the stock Spree image via compose.+const STOREFRONT_CI = `name: CI++on:+ push:+ branches: [main]+ pull_request:++jobs:+ lint:+ name: Lint+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm ci+ - run: npm run lint++ e2e:+ name: E2E (Playwright + Spree)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - run: npm ci+ - name: Boot Spree backend (Postgres + Redis + latest Spree)+ run: docker compose -f e2e-backend/docker-compose.yml up -d --wait+ - name: Run Playwright tests+ run: npm run test:e2e+`++describe('adaptStorefrontWorkflow', () => {+ it('renames the workflow so it does not shadow the backend CI', () => {+ const result = adaptStorefrontWorkflow(STOREFRONT_CI)+ expect(result).toContain('name: Storefront CI')+ expect(result).not.toMatch(/^name:\s*CI\s*$/m)+ })++ it('runs every job from apps/storefront via a per-job default', () => {+ const result = adaptStorefrontWorkflow(STOREFRONT_CI)+ // Both jobs (lint + e2e) get the working-directory default.+ expect(result.match(/working-directory: apps\/storefront/g)?.length).toBe(2)+ expect(result).toContain(+ ' runs-on: ubuntu-latest\n' ++ '\n' ++ ' defaults:\n' ++ ' run:\n' ++ ' working-directory: apps/storefront',+ )+ })++ it('builds the project backend image before booting the E2E stack', () => {+ const result = adaptStorefrontWorkflow(STOREFRONT_CI)+ expect(result).toContain(+ '- name: Build project backend image\n' ++ ' run: docker build -t project-spree:e2e "$GITHUB_WORKSPACE/backend"',+ )+ // Build step comes before the boot step.+ expect(result.indexOf('Build project backend image')).toBeLessThan(+ result.indexOf('Boot Spree backend'),+ )+ })++ it('boots the E2E stack against the project image via SPREE_IMAGE', () => {+ const result = adaptStorefrontWorkflow(STOREFRONT_CI)+ expect(result).toContain(+ '- name: Boot Spree backend (project backend image)\n' ++ ' env:\n' ++ ' SPREE_IMAGE: project-spree:e2e\n' ++ ' run: docker compose -f e2e-backend/docker-compose.yml up -d --wait',+ )+ })++ it('leaves the Playwright run command unchanged', () => {+ const result = adaptStorefrontWorkflow(STOREFRONT_CI)+ expect(result).toContain('run: npm run test:e2e')+ })+})++describe('prepareStorefrontTemplate', () => {+ const tempDirs: string[] = []++ function seedClonedStorefront(): string {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'create-spree-app-storefront-'))+ tempDirs.push(projectDir)++ const workflows = path.join(projectDir, 'apps', 'storefront', '.github', 'workflows')+ fs.mkdirSync(workflows, { recursive: true })+ fs.writeFileSync(path.join(workflows, 'ci.yml'), STOREFRONT_CI)++ return projectDir+ }++ afterEach(() => {+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })+ tempDirs.length = 0+ })++ it('relocates the CI workflow to the project root as storefront-ci.yml', () => {+ const projectDir = seedClonedStorefront()+ prepareStorefrontTemplate(projectDir)++ const moved = path.join(projectDir, '.github', 'workflows', 'storefront-ci.yml')+ expect(fs.existsSync(moved)).toBe(true)+ const content = fs.readFileSync(moved, 'utf-8')+ expect(content).toContain('name: Storefront CI')+ expect(content).toContain('SPREE_IMAGE: project-spree:e2e')+ })++ it("drops the storefront's nested .github after relocating", () => {+ const projectDir = seedClonedStorefront()+ prepareStorefrontTemplate(projectDir)++ expect(fs.existsSync(path.join(projectDir, 'apps', 'storefront', '.github'))).toBe(false)+ })++ it('is a no-op when the storefront ships no workflows', () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'create-spree-app-storefront-'))+ tempDirs.push(projectDir)+ fs.mkdirSync(path.join(projectDir, 'apps', 'storefront'), { recursive: true })++ expect(() => prepareStorefrontTemplate(projectDir)).not.toThrow()+ expect(fs.existsSync(path.join(projectDir, '.github'))).toBe(false)+ })++ it('removes a nested .github even when it has no ci.yml, without creating an empty root workflows dir', () => {+ const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'create-spree-app-storefront-'))+ tempDirs.push(projectDir)+ // .github present but no workflows/ci.yml — e.g. only issue templates.+ const github = path.join(projectDir, 'apps', 'storefront', '.github')+ fs.mkdirSync(github, { recursive: true })+ fs.writeFileSync(path.join(github, 'FUNDING.yml'), 'github: [spree]\n')++ prepareStorefrontTemplate(projectDir)++ // Nested metadata is gone …+ expect(fs.existsSync(github)).toBe(false)+ // … and no empty root workflows directory was created.+ expect(fs.existsSync(path.join(projectDir, '.github', 'workflows'))).toBe(false)+ })+})