Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Add spree build --production with customized-dashboard baking

Damian Legawiec6db2b605056c
diff --git a/docs/developer/dashboard/deployment.mdx b/docs/developer/dashboard/deployment.mdx
index 4d13fa7891..719285eb09 100644
--- a/docs/developer/dashboard/deployment.mdx
+++ b/docs/developer/dashboard/deployment.mdx
@@ -18,21 +18,22 @@ Under the hood, the **`spree_dashboard` gem** (in the Gemfile of the starter and
### Custom dashboard, single node
-The official image contains the *stock* dashboard. Once you've customized yours (`spree eject` + your own pages/plugins in `apps/dashboard/`), bake your build into your own image with a multi-stage Dockerfile — the Node toolchain lives only in the build stage:
-
-```dockerfile
-FROM node:22-slim AS dashboard
-WORKDIR /dashboard
-COPY apps/dashboard/ .
-RUN corepack enable pnpm && pnpm install \
- && VITE_BASE_PATH=/dashboard/ pnpm build
-
-# …in the final Rails stage:
-COPY --from=dashboard /dashboard/dist /rails/dashboard
-ENV SPREE_DASHBOARD_DIST_PATH=/rails/dashboard
+The official image contains the *stock* dashboard. Once you've customized yours (your own pages/plugins in `apps/dashboard/`), bake your build into your own image:
+
+```bash
+spree build --production # optionally --tag registry/repo:tag
+```
+
+The command detects `apps/dashboard/`, selects the Dockerfile's `custom` dashboard stage (`--build-arg DASHBOARD_SOURCE=custom`), and passes your app as a named build context — the Node toolchain lives only in that throw-away stage, and the final image is Rails plus your built `dist/` served at `/dashboard`. Without the CLI, the equivalent is:
+
+```bash
+docker build backend/ -f backend/Dockerfile \
+ --build-arg DASHBOARD_SOURCE=custom \
+ --build-context dashboard-src=./apps/dashboard \
+ -t my-shop-spree:latest
```
-`VITE_BASE_PATH=/dashboard/` makes asset URLs resolve under the mount; leave `VITE_SPREE_API_URL` unset so API calls stay origin-relative.
+Inside the stage the build runs with `VITE_BASE_PATH=/dashboard/` (asset URLs resolve under the mount) and `VITE_SPREE_API_URL` unset (API calls stay origin-relative). Projects **without** `apps/dashboard/` build exactly what plain `docker build backend/` produces — and if your `backend/Dockerfile` predates dashboard support, the command warns instead of silently shipping the stock dashboard over your customized one.
## Static host / CDN — the alternative
diff --git a/docs/plans/5.6-project-layout-and-dashboard.md b/docs/plans/5.6-project-layout-and-dashboard.md
index 8ac0ef2839..f9c41ea84d 100644
--- a/docs/plans/5.6-project-layout-and-dashboard.md
+++ b/docs/plans/5.6-project-layout-and-dashboard.md
@@ -168,7 +168,7 @@ The default production topology is **single node**: the Spree server serves the
- **Rails host** *(implemented)*: the **`spree_dashboard` gem** (opt-in via Gemfile; the successor slot to `spree_admin` at 6.0) serves `Spree::Dashboard.dist_path` (env fallback `SPREE_DASHBOARD_DIST_PATH`) at `/dashboard` with SPA semantics — path fallback to `index.html` (no-cache), `assets/` immutable, traversal-guarded, 404 when unconfigured. Deliberately host-only for the preview: vendoring the prebuilt stock dist inside the gem (`vendor/dist` fallback — zero-toolchain admin for gems-only Rails apps, dashboard version locked to the gem release) is an explicit **6.0 GA decision**, when the release cadences converge and the stock-admin merchant segment matters; during the preview it would couple fast dashboard iteration to gem releases for an audience that customizes immediately.
- **Basepath** *(implemented)*: builds take `VITE_BASE_PATH=/dashboard/` (Vite `base`), and `createDashboardRouter(routeTree, { basepath: import.meta.env.BASE_URL })` keeps the router aligned. `VITE_SPREE_API_URL` stays unset → the SDK emits origin-relative URLs, so one bundle works on every host/environment with no per-env rebuild.
- **Official image** *(pending, spree-starter repo)*: a multi-stage Dockerfile build — a Node stage extracts the stock dashboard template from the published `@spree/cli` tarball, `pnpm install`s the pinned `@spree/dashboard*` packages from npm, builds with `VITE_BASE_PATH=/dashboard/`; the final Rails stage copies only `dist/` and sets `SPREE_DASHBOARD_DIST_PATH`. No Node in the final image. Known caveat: the template pins `^0.x` carets with no lockfile, so image rebuilds can drift across dashboard patch releases — acceptable for the preview; exact-version build args are the later mitigation.
-- **Ejected projects**: same stage shape, but `COPY apps/dashboard/` from the build context instead of extracting the template (requires widening the eject build context or compose `additional_contexts` — the wrapper's compose currently builds from `./backend`).
+- **Customized dashboards in self-built images** *(implemented)*: the starter Dockerfile selects its dashboard stage via `ARG DASHBOARD_SOURCE` (`stock` default extracts the CLI-embedded template; `custom` builds a `dashboard-src` named build context — BuildKit resolves stages lazily, so plain `docker build backend/` needs no extra flags and never evaluates the custom stage). `spree build --production` wires it: detects `apps/dashboard`, stages a filtered copy (named contexts don't apply .dockerignore) and passes the build-arg + context; warns when the Dockerfile predates dashboard support instead of silently baking stock over a customized app; projects without `apps/dashboard` build identically to plain `docker build backend/`. Note `spree eject` needed no changes — it drives the dev compose (`target: dev`), where the dashboard runs on Vite, not from a baked dist.
- **Render** *(implemented)*: `spree add dashboard` amends the project Blueprint's backend service instead of adding a static site — appends the dashboard build to `buildCommand` (Render's Ruby runtime includes Node; the repo is fully cloned even with `rootDir: backend`) and sets `SPREE_DASHBOARD_DIST_PATH=../apps/dashboard/dist`. Single service, builds the user's customized dashboard, zero manual steps. Unrecognized (hand-edited) Blueprints are left untouched with a docs pointer.
- **6.0**: the SPA stays at `/dashboard` permanently — `/admin` remains reserved for the Classic Admin (whether it retires or someone keeps maintaining it), so the dashboard URL is stable across upgrades with no route migration and no collision. `spree_dashboard` still becomes the default admin *delivery* at 6.0; only the path never changes. The static/CDN topology (see the deployment docs) remains the alternative for customized dashboards on independent release cadences.
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 86ada49f10..2f42f20552 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -1,3 +1,5 @@
+import fs from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
@@ -12,87 +14,209 @@ export function registerBuildCommand(program: Command): void {
.description('Rebuild the dev image (after Dockerfile / .ruby-version changes)')
.option('--reset-bundle', 'also wipe the bundle_cache volume to re-seed gems')
.option('--yes', 'skip confirmation prompts (for CI)')
- .action(async (flags: { resetBundle?: boolean; yes?: boolean }) => {
- const ctx = detectProject()
-
- if (hasMonorepoSpreePath(ctx.projectDir)) {
- p.cancel(
- [
- 'This project uses SPREE_PATH for monorepo development.',
- `Use ${pc.bold('pnpm server:build')} from the monorepo root instead of ${pc.bold('spree build')}.`,
- 'It builds against the edge compose overlay the running stack was started with.',
- ].join('\n'),
- )
- process.exit(1)
+ .option(
+ '--production',
+ 'build the production image instead — includes apps/dashboard when present',
+ )
+ .option('--tag <tag>', 'image tag for --production (default: <project>-spree:latest)')
+ .action(
+ async (flags: {
+ resetBundle?: boolean
+ yes?: boolean
+ production?: boolean
+ tag?: string
+ }) => {
+ if (flags.production) {
+ await buildProductionImage(detectProject().projectDir, flags.tag)
+ return
+ }
+ await buildDevImage(flags)
+ },
+ )
+}
+
+async function buildDevImage(flags: { resetBundle?: boolean; yes?: boolean }): Promise<void> {
+ const ctx = detectProject()
+
+ if (hasMonorepoSpreePath(ctx.projectDir)) {
+ p.cancel(
+ [
+ 'This project uses SPREE_PATH for monorepo development.',
+ `Use ${pc.bold('pnpm server:build')} from the monorepo root instead of ${pc.bold('spree build')}.`,
+ 'It builds against the edge compose overlay the running stack was started with.',
+ ].join('\n'),
+ )
+ process.exit(1)
+ }
+
+ // Always build against the active docker-compose.yml — the same file
+ // `spree dev` runs. After `spree eject` that contains a `build:` section
+ // pointing at ./backend; before eject, it's a prebuilt-image stack and
+ // there's nothing to rebuild.
+ if (!isEjectedProject(ctx.projectDir)) {
+ console.error(
+ `\n${pc.red('Error:')} docker-compose.yml has no \`build:\` section. ` +
+ `Run ${pc.bold('spree eject')} first to switch to a build-from-source stack.\n`,
+ )
+ process.exit(1)
+ }
+
+ if (flags.resetBundle) {
+ if (!flags.yes) {
+ const confirmed = await p.confirm({
+ message:
+ 'Wipe the bundle_cache volume? Any gems added via `spree bundle add` since the last image build will be lost.',
+ initialValue: false,
+ })
+ if (p.isCancel(confirmed) || !confirmed) {
+ p.cancel('Build cancelled.')
+ process.exit(0)
}
+ }
- // Always build against the active docker-compose.yml — the same file
- // `spree dev` runs. After `spree eject` that contains a `build:` section
- // pointing at ./backend; before eject, it's a prebuilt-image stack and
- // there's nothing to rebuild.
- if (!isEjectedProject(ctx.projectDir)) {
- console.error(
- `\n${pc.red('Error:')} docker-compose.yml has no \`build:\` section. ` +
- `Run ${pc.bold('spree eject')} first to switch to a build-from-source stack.\n`,
- )
- process.exit(1)
+ const s = p.spinner()
+ s.start('Wiping bundle_cache volume...')
+ try {
+ // `down` without -v preserves postgres/redis/meilisearch/storage volumes.
+ await dockerCompose(['down'], ctx.projectDir, { stdio: 'ignore' })
+ const projectName = await resolveComposeProjectName(ctx.projectDir)
+ const volumeName = `${projectName}_bundle_cache`
+ // Check before removal so we can report missing-volume distinctly
+ // from a real failure (wrong permissions, daemon issue).
+ const exists = await volumeExists(volumeName, ctx.projectDir)
+ if (exists) {
+ await execa('docker', ['volume', 'rm', volumeName], {
+ cwd: ctx.projectDir,
+ stdio: 'ignore',
+ })
+ s.stop('bundle_cache volume wiped.')
+ } else {
+ s.stop(`bundle_cache volume not present (looked for ${volumeName}).`)
}
+ } catch (error) {
+ s.stop('Failed to wipe bundle_cache volume.')
+ throw error
+ }
+ }
- if (flags.resetBundle) {
- if (!flags.yes) {
- const confirmed = await p.confirm({
- message:
- 'Wipe the bundle_cache volume? Any gems added via `spree bundle add` since the last image build will be lost.',
- initialValue: false,
- })
- if (p.isCancel(confirmed) || !confirmed) {
- p.cancel('Build cancelled.')
- process.exit(0)
- }
- }
+ console.log(`\n${pc.bold('Rebuilding dev image...')}\n`)
+ await dockerCompose(['build', 'web', 'worker'], ctx.projectDir, {
+ stdio: 'inherit',
+ })
- const s = p.spinner()
- s.start('Wiping bundle_cache volume...')
- try {
- // `down` without -v preserves postgres/redis/meilisearch/storage volumes.
- await dockerCompose(['down'], ctx.projectDir, { stdio: 'ignore' })
- const projectName = await resolveComposeProjectName(ctx.projectDir)
- const volumeName = `${projectName}_bundle_cache`
- // Check before removal so we can report missing-volume distinctly
- // from a real failure (wrong permissions, daemon issue).
- const exists = await volumeExists(volumeName, ctx.projectDir)
- if (exists) {
- await execa('docker', ['volume', 'rm', volumeName], {
- cwd: ctx.projectDir,
- stdio: 'ignore',
- })
- s.stop('bundle_cache volume wiped.')
- } else {
- s.stop(`bundle_cache volume not present (looked for ${volumeName}).`)
- }
- } catch (error) {
- s.stop('Failed to wipe bundle_cache volume.')
- throw error
- }
- }
+ p.note(
+ [
+ `Image rebuilt. Start the stack with ${pc.bold('spree dev')}.`,
+ flags.resetBundle
+ ? `On next boot, gems will re-seed into a fresh ${pc.dim('bundle_cache')} volume.`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ 'Build complete',
+ )
+}
- console.log(`\n${pc.bold('Rebuilding dev image...')}\n`)
- await dockerCompose(['build', 'web', 'worker'], ctx.projectDir, {
- stdio: 'inherit',
- })
+/**
+ * What `spree build --production` will run, computed without touching Docker
+ * — exported for tests. When the project carries a customized dashboard
+ * (`apps/dashboard`) AND the backend Dockerfile supports source selection
+ * (the `DASHBOARD_SOURCE` build arg from spree-starter), the plan stages a
+ * filtered copy of the app (no node_modules/build output — Docker named
+ * contexts don't apply .dockerignore) and selects the `custom` dashboard
+ * stage. Older projects hit neither branch and build exactly what
+ * `docker build backend/` would — nothing changes for them.
+ */
+export function planProductionBuild(
+ projectDir: string,
+ tag?: string,
+): {
+ args: string[]
+ imageTag: string
+ dashboard: 'custom' | 'stock-or-none' | 'unsupported-dockerfile'
+ stagedDashboardDir?: string
+} {
+ const backendDir = path.join(projectDir, 'backend')
+ const dockerfile = path.join(backendDir, 'Dockerfile')
+ if (!fs.existsSync(dockerfile)) {
+ throw new Error('No backend/Dockerfile found. Is this a create-spree-app project?')
+ }
- p.note(
- [
- `Image rebuilt. Start the stack with ${pc.bold('spree dev')}.`,
- flags.resetBundle
- ? `On next boot, gems will re-seed into a fresh ${pc.dim('bundle_cache')} volume.`
- : '',
- ]
- .filter(Boolean)
- .join('\n'),
- 'Build complete',
- )
- })
+ const imageTag =
+ tag ??
+ `${path
+ .basename(projectDir)
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]/g, '')}-spree:latest`
+
+ const args = ['build', backendDir, '-f', dockerfile, '-t', imageTag]
+
+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
+ if (!fs.existsSync(path.join(dashboardDir, 'package.json'))) {
+ return { args, imageTag, dashboard: 'stock-or-none' }
+ }
+
+ if (!fs.readFileSync(dockerfile, 'utf-8').includes('DASHBOARD_SOURCE')) {
+ return { args, imageTag, dashboard: 'unsupported-dockerfile' }
+ }
+
+ const staged = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-dashboard-src-'))
+ fs.cpSync(dashboardDir, staged, {
+ recursive: true,
+ filter: (src) => {
+ const base = path.basename(src)
+ return base !== 'node_modules' && base !== 'dist' && base !== '.tanstack'
+ },
+ })
+ args.push('--build-arg', 'DASHBOARD_SOURCE=custom', '--build-context', `dashboard-src=${staged}`)
+ return { args, imageTag, dashboard: 'custom', stagedDashboardDir: staged }
+}
+
+/**
+ * Build the production image (the Dockerfile's final stage) — the one you
+ * push to a registry and run on Render/Railway/AWS/anywhere. Unlike the dev
+ * flow this needs no compose file and no prior `spree eject`.
+ */
+async function buildProductionImage(projectDir: string, tag?: string): Promise<void> {
+ let plan: ReturnType<typeof planProductionBuild>
+ try {
+ plan = planProductionBuild(projectDir, tag)
+ } catch (err) {
+ console.error(`\n${pc.red('Error:')} ${err instanceof Error ? err.message : String(err)}\n`)
+ process.exit(1)
+ }
+
+ if (plan.dashboard === 'custom') {
+ p.log.info(`Including your dashboard from ${pc.bold('apps/dashboard/')} (built in-image).`)
+ } else if (plan.dashboard === 'unsupported-dockerfile') {
+ p.log.warn(
+ `${pc.bold('apps/dashboard/')} exists, but ${pc.bold('backend/Dockerfile')} predates ` +
+ `dashboard support (no DASHBOARD_SOURCE build arg) — the image will NOT include your ` +
+ `dashboard. Update the Dockerfile from the spree-starter template to bake it in.`,
+ )
+ }
+
+ console.log(`\n${pc.bold(`Building production image ${plan.imageTag}...`)}\n`)
+ try {
+ await execa('docker', plan.args, { cwd: projectDir, stdio: 'inherit' })
+ } finally {
+ if (plan.stagedDashboardDir) {
+ fs.rmSync(plan.stagedDashboardDir, { recursive: true, force: true })
+ }
+ }
+
+ p.note(
+ [
+ `Run it: ${pc.cyan(`docker run --rm -p 3000:3000 ${plan.imageTag}`)}`,
+ `Push it: ${pc.cyan(`docker tag ${plan.imageTag} <registry>/<repo> && docker push <registry>/<repo>`)}`,
+ plan.dashboard !== 'unsupported-dockerfile'
+ ? `Dashboard: served at ${pc.bold('/dashboard')} when the image includes one.`
+ : '',
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ 'Production image built',
+ )
}
async function resolveComposeProjectName(projectDir: string): Promise<string> {
diff --git a/packages/cli/tests/build-production.test.ts b/packages/cli/tests/build-production.test.ts
new file mode 100644
index 0000000000..df0c839b06
--- /dev/null
+++ b/packages/cli/tests/build-production.test.ts
@@ -0,0 +1,99 @@
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { planProductionBuild } from '../src/commands/build.js'
+
+/**
+ * Pure planning logic for `spree build --production` — the safety contract:
+ * projects without apps/dashboard (or with a pre-dashboard Dockerfile) build
+ * exactly what `docker build backend/` would.
+ */
+describe('planProductionBuild', () => {
+ let projectDir: string
+ const staged: string[] = []
+
+ beforeEach(() => {
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-prod-build-'))
+ fs.mkdirSync(path.join(projectDir, 'backend'))
+ })
+
+ afterEach(() => {
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ for (const dir of staged.splice(0)) fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ function writeDockerfile(content: string) {
+ fs.writeFileSync(path.join(projectDir, 'backend', 'Dockerfile'), content)
+ }
+
+ function writeDashboardApp() {
+ const dir = path.join(projectDir, 'apps', 'dashboard')
+ fs.mkdirSync(path.join(dir, 'src'), { recursive: true })
+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"dashboard"}\n')
+ fs.writeFileSync(path.join(dir, 'src', 'main.tsx'), '// entry\n')
+ fs.mkdirSync(path.join(dir, 'node_modules', 'left-over'), { recursive: true })
+ fs.mkdirSync(path.join(dir, 'dist'))
+ fs.writeFileSync(path.join(dir, 'dist', 'stale.js'), '')
+ }
+
+ it('throws without a backend Dockerfile', () => {
+ expect(() => planProductionBuild(projectDir)).toThrow(/backend\/Dockerfile/)
+ })
+
+ it('builds plain when the project has no dashboard app', () => {
+ writeDockerfile('FROM ruby\n')
+
+ const plan = planProductionBuild(projectDir, 'shop:1')
+
+ expect(plan.dashboard).toBe('stock-or-none')
+ expect(plan.args).toEqual([
+ 'build',
+ path.join(projectDir, 'backend'),
+ '-f',
+ path.join(projectDir, 'backend', 'Dockerfile'),
+ '-t',
+ 'shop:1',
+ ])
+ expect(plan.stagedDashboardDir).toBeUndefined()
+ })
+
+ it('builds plain and flags a Dockerfile without dashboard support', () => {
+ writeDockerfile('FROM ruby\n')
+ writeDashboardApp()
+
+ const plan = planProductionBuild(projectDir)
+
+ expect(plan.dashboard).toBe('unsupported-dockerfile')
+ expect(plan.args).not.toContain('--build-context')
+ expect(plan.args).not.toContain('--build-arg')
+ })
+
+ it('selects the custom stage and stages a filtered dashboard copy', () => {
+ writeDockerfile('ARG DASHBOARD_SOURCE=stock\nFROM ruby\n')
+ writeDashboardApp()
+
+ const plan = planProductionBuild(projectDir)
+ if (plan.stagedDashboardDir) staged.push(plan.stagedDashboardDir)
+
+ expect(plan.dashboard).toBe('custom')
+ expect(plan.args).toContain('DASHBOARD_SOURCE=custom')
+ const contextArg = plan.args[plan.args.indexOf('--build-context') + 1]
+ expect(contextArg).toBe(`dashboard-src=${plan.stagedDashboardDir}`)
+
+ // Staged copy carries source but never host artifacts.
+ const stagedDir = plan.stagedDashboardDir as string
+ expect(fs.existsSync(path.join(stagedDir, 'package.json'))).toBe(true)
+ expect(fs.existsSync(path.join(stagedDir, 'src', 'main.tsx'))).toBe(true)
+ expect(fs.existsSync(path.join(stagedDir, 'node_modules'))).toBe(false)
+ expect(fs.existsSync(path.join(stagedDir, 'dist'))).toBe(false)
+ })
+
+ it('derives a sanitized default tag from the project directory', () => {
+ writeDockerfile('FROM ruby\n')
+
+ const plan = planProductionBuild(projectDir)
+
+ expect(plan.imageTag).toMatch(/^[a-z0-9_-]+-spree:latest$/)
+ })
+})
diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.ts
index 06952c23dc..4332b3e822 100644
--- a/packages/create-spree-app/src/templates/readme.ts
+++ b/packages/create-spree-app/src/templates/readme.ts
@@ -105,6 +105,7 @@ This project uses [\`@spree/cli\`](https://spreecommerce.org/docs/developer/cli/
| \`spree stop\` | Stop backend services |
| \`spree update\` | Pull latest Spree image and restart (runs migrations automatically) |
| \`spree eject\` | Switch from prebuilt image to building from \`backend/\` |
+| \`spree build --production\` | Build the production image — includes \`apps/dashboard\` when present |
| \`spree logs\` | View web server logs |
| \`spree logs worker\` | View background jobs logs |
| \`spree console\` | Open Rails console |