/spree:spree-storefrontfrom spree
Provides architecture, patterns, and guidance for the Spree 6 Next.js storefront: adding pages, customizing checkout, fetching products, multi-region URLs, B2B portal, transactional emails, and Store API integration via @spree/sdk.
Ships in spree. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The Spree Next.js storefront is a separate app that talks to the Spree backend over the v3 Store API (/api/v3/store/*) using @spree/sdk 2.x. create-spree-app puts it in apps/storefront/ (next to server/ and apps/dashboard/); or fork https://github.com/spree/storefront. Next.js 16, React 19, Tailwind 4.
The storefront is optional — any frontend (Astro, Remix, React Native, …) can use the same Store API. This skill assumes the official storefront; the API contract is identical for any client.
Browser → Server Action (src/lib/data/*) → @spree/sdk → Spree Store API
httpOnly cookies (JWT, refresh token, cart token, country/locale) via src/lib/spree helpers
src/lib/data/). The browser never calls Spree directly; even the publishable key stays server-only (SPREE_PUBLISHABLE_KEY, no NEXT_PUBLIC_).src/lib/spree/ holds the integration: getClient(), cookie helpers, withAuthRefresh(), getLocaleOptions(), getCartOptions(), middleware, surfaces (DTC vs wholesale), webhooks.CartContext, CheckoutContext, …) hold UI state and call Server Actions — don't add SWR/React Query fetches against the Store API from the browser.// src/lib/data/customer.ts (pattern)
import { getClient, withAuthRefresh, setAccessToken, setRefreshToken } from '@/lib/spree'
export async function login(email: string, password: string) {
const { token, refresh_token, user } = await getClient().auth.login({ email, password })
await setAccessToken(token)
await setRefreshToken(refresh_token)
return { success: true, user }
}
export async function getCustomer() {
return withAuthRefresh((options) => getClient().customer.get(options))
}
Required env (.env.local): SPREE_API_URL, SPREE_PUBLISHABLE_KEY. Optional: NEXT_PUBLIC_DEFAULT_COUNTRY / NEXT_PUBLIC_DEFAULT_LOCALE, NEXT_PUBLIC_SITE_URL, SPREE_WHOLESALE_CHANNEL, SPREE_WHOLESALE_PUBLISHABLE_KEY, SPREE_WEBHOOK_SECRET, RESEND_API_KEY, EMAIL_FROM. NEXT_PUBLIC_* is only for values the browser genuinely needs (default region, Stripe/PayPal publishable keys).
import { createClient } from '@spree/sdk'
const spree = createClient({
baseUrl: process.env.SPREE_API_URL!,
publishableKey: process.env.SPREE_PUBLISHABLE_KEY!,
locale: 'en', // sent as x-spree-locale (also per request: { locale })
channel: 'online', // sent as X-Spree-Channel; omit for the store default
})
const { data, meta } = await spree.products.list({ expand: ['media', 'default_variant'] })
const product = await spree.products.get('cool-shirt', { expand: ['variants', 'media'] }) // slug or prod_ id
const cart = await spree.carts.create()
await spree.carts.items.create(cart.id, { variant_id: 'variant_k5nR8xLq', quantity: 1 }, { spreeToken: cart.token })
const orders = await spree.customer.orders.list({}, { token }) // logged-in customer (JWT)
product.name); relations are *_id fields or, with expand, nested objects (product.default_variant, product.primary_media, product.media[]). Prices come as Price objects (product.price.display_amount) — never compute money client-side.spreeToken (guest cart, x-spree-token) · + token JWT (customer). Types in @spree/sdk (also @spree/sdk/zod), webhook helpers in @spree/sdk/webhooks.prod_, variant_, cart_, or_, cust_, ful_). Carts use cart.id — cart.number is a deprecated mirror of id kept for 5.x clients (removed in 6.1).Spree 6 splits the mutable Cart (cart_…) from the immutable Order (or_…) created when the cart completes. There is no checkout state machine to advance: you update the cart (email, addresses, delivery rate, payment) in any order, and the cart reports what's still missing.
const cart = await spree.carts.get(cartId, { spreeToken })
cart.requirements
// [{ step: 'address', field: 'ship_address', code: 'ship_address_required', message: '…' },
// { step: 'delivery', field: 'delivery_method', code: 'delivery_method_required', message: '…' }, …]
requirements[] entries are { step, field, code, message }. Codes include line_items_required, email_required, ship_address_required, delivery_method_required, payment_required, po_number_required, guest_checkout_not_allowed, quantity_rule_violated, order_minimum_not_met, discontinued, out_of_stock. Steps (cart, address, delivery, payment) are advisory UI grouping — map them to checkout sections and show message. Completion is the only hard gate. Custom requirements come from the backend (Spree::Checkout::Registry.add_requirement, see spree-checkout).spree.carts.fulfillments.update(cartId, fulfillmentId, { selected_delivery_rate_id }, opts) returns the recalculated cart.spree.carts.paymentSessions.create(cartId, { payment_method_id }, opts) → provider data (client secret, drop-in token, redirect URL).spree.carts.paymentSessions.complete(cartId, sessionId, { session_result }, opts).spree.carts.complete(cartId, opts) → returns the Order (typed Order | OrderGroup — a multi-seller marketplace cart returns an ogrp_… group; narrow with isOrderGroup from @spree/sdk). It's idempotent: if a gateway webhook already completed the cart, it returns the existing result.
Non-session methods (check, COD, bank transfer): spree.carts.payments.create(...).carts.get — read the result with spree.orders.get(id, params, { spreeToken | token }). It accepts the or_… id or the original cart_… id, so the confirmation page (order-placed/[id]) can keep using the cart id as its handle. Order status is draft/placed/canceled, with separate payment_status and fulfillment_status.src/lib/data/checkout.ts, payment.ts (completeCheckoutOrder also tolerates 403/422 races), components/checkout/*, and the gateway gems (e.g. spree_stripe).Every route lives under src/app/[country]/[locale]/… (/us/en/products, /de/de/products), mapped to a Spree Market (country + currency + locale). src/proxy.ts (Next 16's middleware file) wires createSpreeMiddleware({ defaultCountry, defaultLocale, staticRoutes? }) from @/lib/spree/middleware, which:
/{country}/{locale}/…;spree_country cookie → x-vercel-ip-country / cf-ipcountry → default, and locale from spree_locale → Accept-Language → default;spree_country / spree_locale cookies with the URL.Data functions don't take region args — they call getLocaleOptions(), which reads those cookies and passes locale/country to the SDK. New pages go under src/app/[country]/[locale]/(storefront)/your-page/page.tsx to inherit the layout. CountrySwitcher changes region by navigating to a new prefix.
/wholesale is an opt-in B2B portal on a separate channel, enabled only when SPREE_WHOLESALE_CHANNEL is set to a gated channel's code (unset → all wholesale UI hidden, routes 404). A surface = a channel-bound SDK client (channel: 'wholesale' → X-Spree-Channel) with its own cart cookie and cache tags; the customer JWT is shared. The channel's storefront_access (login_required | prices_hidden | public) is enforced by the API (401, or money fields null); buyer approval = membership in the Wholesale customer group; trade prices come from backend price lists. Treat it as a reference you can adapt (members-only DTC, B2B-only store) — see spree-b2b.
The storefront can own customer emails (react-email templates in src/lib/emails/, sent via Resend; written to .next/emails/ in dev; preview at /dev/emails). The route src/app/api/webhooks/spree/route.ts uses createWebhookHandler from @/lib/spree/webhooks, which verifies X-Spree-Webhook-Signature (HMAC-SHA256 over "{timestamp}.{body}", timing-safe, 5-minute replay window) and dispatches by event name:
import { createWebhookHandler } from '@/lib/spree/webhooks'
const handler = createWebhookHandler({
secret: process.env.SPREE_WEBHOOK_SECRET!,
handlers: {
'order.placed': handleOrderPlaced,
'order.canceled': handleOrderCanceled,
'order.fulfilled': handleOrderFulfilled, // or 'fulfillment.fulfilled' for per-parcel emails
'customer.password_reset_requested': handlePasswordReset, // must be subscribed by name — `*` never receives it
},
// waitUntil, toleranceSeconds optional
})
export const POST = handler
order.placed (not order.completed), order.fulfilled / fulfillment.fulfilled (not order.shipped). The shipped storefront code still registers order.completed and order.shipped — deprecated aliases Spree 6.0 still sends alongside the new names and stops sending in 6.1. Switch handlers and endpoint subscriptions to the new names.order.placed with notify_customer: false; the purchase's confirmation belongs to order_group.completed — add a handler for it if you send order emails (see spree-marketplace).send_consumer_transactional_emails (false) so customers don't get two. That switch (and notify_customer: false on an order) only silences customer emails — the store's new-order notification to new_order_notifications_email still goes out whenever that address is set.SPREE_WEBHOOK_SECRET. For local testing expose the storefront (cloudflared tunnel --url http://localhost:3001).id), and an endpoint is disabled after 15 consecutive failed deliveries — return 2xx quickly, dedupe on event.id, and do slow work in waitUntil/a queue. Unhandled events return 200 { handled: false }.verifyWebhookSignature(body, signature, timestamp, secret) and type WebhookEvent<T> from @spree/sdk/webhooks. Full event list: spree-events-webhooks.pnpm test / pnpm test:watch (tests live next to code, e.g. src/lib/data/__tests__).STRIPE_PUBLISHABLE_KEY, STRIPE_SECRET_KEY), pnpm e2e:up (boots Postgres/Redis + ghcr.io/spree/spree:latest, seeds via @spree/cli, writes .env.e2e), pnpm test:e2e (:ui for interactive), pnpm e2e:down.SPREE_IMAGE=<image> pnpm e2e:up. In a create-spree-app project build it from the root with docker build . -f server/Dockerfile -t project-spree:e2e first; generated CI does this for you.| Want to… | Belongs in |
|---|---|
| Layout, copy, styling, a new content page | Storefront (src/app/[country]/[locale]/(storefront)/…, @theme tokens in src/app/globals.css) |
| Add a field to product/cart responses | Backend — model + serializer swap (spree-resource, spree-api-v3) |
| Change pricing | Backend — price lists / rules (spree-pricing) |
| Change how cart totals are calculated | Backend — Spree::Carts::RecalculateTotals (DI key cart_recalculate_totals_workflow) or a workflow hook (spree-order-totals, spree-workflows) |
| Add a checkout requirement (e.g. "accept terms") | Backend Spree::Checkout::Registry.add_requirement; storefront renders the new requirements[] code |
| Add a country / currency / language | Backend Markets; storefront just follows the URL + cookies |
| Customize the checkout UI | Storefront (components/checkout/*) |
| A/B test the PDP, client analytics | Storefront (src/lib/analytics) |
| Sync orders to a CRM/ERP | Backend subscriber on order.placed (spree-events-webhooks) |
| Customer email look & feel | Storefront emails (webhooks) or backend mailers — pick one owner |
Rule: anything customer-visible is storefront; anything that touches data, money, or business rules is backend, so every frontend gets the same behavior.
sk_…) never go in a storefront — not even server-side; the Store API uses publishable keys. Admin tasks belong in the dashboard or a backend job.updateTag(cartTag(surface))) — invalidate after cart mutations.requirements[], and handle carts.complete returning an error (code cart_cannot_complete) by re-reading the cart's requirements.carts.get after completion — use orders.get with the cart or order id.x-spree-locale, X-Spree-Channel), not Accept-Language; the storefront gets it from the URL segments via cookies.upstream remote and merge periodically; keep customizations in components/data files you own.node_modules/@spree/docs/dist/developer/storefront/nextjs/{architecture,customization,multi-region,wholesale,emails,environment-variables,testing,deployment,wallet-payments}.md; SDK: developer/sdk/quickstart.md. Online: https://spreecommerce.org/docs/developer/storefront/nextjs/architecturedeveloper/tutorial/storefront.mdsrc/lib/spree/, src/lib/data/, src/app/api/webhooks/spree/route.ts)spree-typescript-sdk, spree-api-v3, spree-checkout, spree-events-webhooks, spree-b2b, spree-i18n, spree-deployment.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub spree/agent-skills --plugin spree39 skills in this plugin
/spree-api-v3Use when the user is calling or debugging Spree 6's REST API v3 — the Store API (storefronts, mobile apps, customers), the Admin API (integrations, back-office tools) or the Seller API (marketplace sellers). Covers auth (publishable/secret keys, JWT audiences), scopes and permissions, prefixed IDs, the cart → order split, checkout `requirements[]`, order statuses, the `{data, meta}` envelope, expand/fields, Ransack filters, errors, idempotency, localization headers and rate limits. Common phrasings include "Spree API", "Store API", "Admin API", "publishable key", "secret key", "X-Spree-Api-Key", "X-Spree-Token", "API scopes", "403 required_scope", "cart_ vs or_", "complete cart", "cart 404 after checkout", "prefixed IDs", "expand", "Idempotency-Key", "429 rate limit", "v3 endpoint", "Admin API OpenAPI spec". For ADDING or documenting (OpenAPI) a new endpoint use spree-resource; for AI agents driving the store over MCP use spree-mcp; for roles/permissions internals use spree-auth-permissions./spree-auth-permissionsUse when the user is working on who can sign in to Spree 6 and what they may do — staff roles and permission keys, secret-key scopes, registering permission scopes for an extension, 403 errors with `required_permission` / `required_scope`, storefront ownership rules (`Spree::Storefront::AccessPolicy`), custom login strategies (SSO, OIDC, Auth0/Okta/Entra/Firebase), JWT audiences, or swapping the customer/admin user class. Common phrasings include "Spree roles", "staff permissions", "add a role", "read_orders permission", "Spree.permissions.register_scope", "API key scopes", "403 Missing permission", "who can see this order", "SSO for the dashboard", "OIDC login", "custom authentication strategy", "Spree.customer_class", "admin_user_class", "CanCanCan in Spree 6". Spree 6./spree-b2bUse when building B2B or wholesale commerce on Spree 6 — companies and buyer organizations (company trees, divisions, members, invitations, buying on a company's behalf), catalogs and negotiated pricing (owned price lists, assignment to companies or customer groups), customer groups, gated storefronts (`storefront_access` login_required / prices_hidden), the Next.js wholesale portal, minimum order quantity / order multiples / order minimums, PO numbers, orders on account (pay by invoice, staff-keyed draft orders, `payment_pending`) and freight shipping (cartons, pallets, unpriced freight rates). Common phrasings include "B2B", "wholesale", "build a B2B store", "pay by invoice", "net terms", "draft order for a company", "company account", "Spree::Company", "division", "negotiated prices", "customer-specific pricing", "price list per company", "MOQ", "order multiple", "case pack", "order minimum", "PO number", "login to see prices", "wholesale portal", "X-Spree-Channel", "freight", "pallet"./spree-catalogUse when the user is working with the Spree 6 product catalog — products, variants, option types/values, the default variant, product types (templates), categories vs collections, custom fields, media (images, video, media library), channel publications, search providers (database, spree_meilisearch, custom), digital assets, or catalog imports/exports. Common phrasings include "create a product", "add variants", "size and color options", "product type", "category tree", "collection", "brand", "custom field on products", "product images", "product video", "primary_media", "product not showing in store", "publish product on channel", "Meilisearch", "reindex", "custom search provider", "digital download", "master variant". Covers the catalog graph and how to read/write it from Ruby, the Admin SDK and `spree api`./spree-checkoutUse when the user is working on Spree 6 checkout — the Cart → Order split, checkout requirements and advisory steps, `Spree::Checkout::Registry` (add_requirement / register_step / base_steps), cart completion (`Spree::Carts::Complete`), `carts.complete` / `carts.add_item` workflow hooks, addresses, payment sessions, guest checkout, cart association/merge on login, or the Store API / `@spree/sdk` checkout sequence. Common phrasings include "checkout broken", "cart won't complete", "why can't this cart complete", "add a checkout step", "require a field before checkout", "require terms acceptance", "skip the delivery step", "order stuck", "double charge", "guest checkout", "cart not found after checkout", "merge carts on login", "custom checkout validation", "block checkout if…". Covers where each customization belongs and how completion guarantees idempotency./spree-cliUse when calling the Spree 6 Admin API from the command line or driving it programmatically as an agent — exploring endpoints, reading or mutating store data, and especially DEBUGGING (inspecting an order/product/customer, checking why a request failed, reproducing a 403/422). The `spree api` command group in `@spree/cli` is a `gh api`-style generic HTTP client: `spree api get|post|patch|delete <path>` plus offline discovery (`spree api endpoints`, `spree api schema`). Common phrasings include "spree api", "spree CLI", "call the admin API from the terminal", "spree api get", "inspect this order", "why is this Spree request failing", "list admin endpoints", "spree auth". Also covers the project-side dev commands agents reach for while debugging (`spree shell`, `spree test`, `spree console`, `spree add`, `spree plugin new`). For SDK/TypeScript integration use spree-typescript-sdk; for raw API protocol details use spree-api-v3.Other plugins' skills for the same job