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.

Serve the dashboard from the Spree server: single-node by default

Damian Legawiec5ce1305ab27f
diff --git a/docs/developer/dashboard/deployment.mdx b/docs/developer/dashboard/deployment.mdx
index c872686f45..e690cf7cde 100644
--- a/docs/developer/dashboard/deployment.mdx
+++ b/docs/developer/dashboard/deployment.mdx
@@ -1,62 +1,78 @@
---
title: Deploying the dashboard
sidebarTitle: Deployment
-description: Ship the React Dashboard to production — a static build served from a CDN or reverse proxy, with the API's CORS and cookie settings to match.
+description: Ship the React Dashboard to production — served by the Spree server itself (the default), or as a static build on a CDN.
---
-The dashboard deploys as **static files**. `pnpm build` produces `dist/` — HTML, JS, CSS — and any static host can serve it; there is no Node server in production. The API URL is baked in at build time:
-
-```bash
-cd apps/dashboard
-VITE_SPREE_API_URL=https://api.mystore.com pnpm build
-```
+The dashboard deploys as **static files**. `vite build` produces `dist/` — HTML, JS, CSS — there is no Node server in production. What varies is who serves those files.
<Warning>
`VITE_`-prefixed values are compiled into the client bundle — never put credentials in them. The dashboard authenticates admins interactively (JWT in memory + an httpOnly refresh cookie); no API keys are involved.
</Warning>
-## Pick a topology
+## Single node — the default
+
+The Spree server serves the dashboard itself at **`/dashboard`**: one container, one origin, zero CORS or cookie configuration. The official Spree Docker image ships with the stock dashboard baked in — deploy the image anywhere Docker runs (Render, Railway, AWS, Azure, your own host) and `https://your-api-host/dashboard` just works.
+
+Under the hood: `Spree::Config.dashboard_dist_path` (or the `SPREE_DASHBOARD_DIST_PATH` env var) points at a built `dist/` directory, and Spree serves it with SPA semantics — every dashboard route falls back to `index.html`, hashed assets get immutable caching. The bundle is built with a **relative API base** (`VITE_SPREE_API_URL` unset) and `base: /dashboard/`, so the same image works on every host and environment with no rebuild.
+
+### 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
+```
+
+`VITE_BASE_PATH=/dashboard/` makes asset URLs resolve under the mount; leave `VITE_SPREE_API_URL` unset so API calls stay origin-relative.
+
+## Static host / CDN — the alternative
-**Cross-origin (dashboard and API on different domains)** — the default for static hosts (Render, Cloudflare Pages, Netlify, S3+CloudFront). Three requirements:
+For edge-served assets or an independent dashboard release cadence, deploy `dist/` to a static host on its own domain:
+
+```bash
+cd apps/dashboard
+VITE_SPREE_API_URL=https://api.mystore.com pnpm build
+```
+
+This is the **cross-origin** topology, with three requirements:
1. **HTTPS on both sides.** The refresh cookie is issued with `SameSite=None; Secure` in production, and browsers drop `Secure` cookies over HTTP. There is no insecure-production mode.
2. **Allowed Origins.** Add the dashboard's URL (e.g. `https://dashboard.mystore.com`) to **Settings → Allowed Origins** in the Spree admin — the API rejects cross-origin requests until then.
-3. **SPA fallback.** Every path must rewrite to `index.html` so the router owns the URL (`/* → /index.html` on your host).
+3. **SPA fallback.** Every path must rewrite to `index.html` so the router owns the URL (`/* → /index.html` on your host: `_redirects` on Netlify, `vercel.json` rewrites, `try_files $uri /index.html;` on nginx).
-**Same-origin (one domain, reverse proxy)** — serve `dist/` and proxy `/api/*` and `/rails/*` to the Rails server from the same origin, mirroring what the Vite dev proxy does. No CORS entries, `SameSite=Lax` cookies, one certificate — the simpler security posture if you already run nginx/Caddy or an ingress.
+A middle ground also works: serve `dist/` and proxy `/api/*` + `/rails/*` to Rails from one domain behind your own nginx/Caddy/ingress — same-origin simplicity without baking the bundle into the image.
## Render
-If your project deploys to Render via the Blueprint that `create-spree-app` places at the project root, `spree add dashboard` registers the dashboard automatically — it appends a static-site service to `render.yaml`:
+If your project deploys to Render via the Blueprint that `create-spree-app` places at the project root, `spree add dashboard` wires the single-node topology automatically: it extends the backend service's `buildCommand` to also build `apps/dashboard` (Render's Ruby runtime includes Node, and the full repo is available during the build) and adds one env var so the server serves the result:
```yaml
-- type: web
- name: spree-dashboard
- runtime: static
- rootDir: apps/dashboard
- buildCommand: corepack enable pnpm && pnpm install && pnpm build
- staticPublishPath: dist
- routes:
- - type: rewrite
- source: /*
- destination: /index.html
- envVars:
- - key: VITE_SPREE_API_URL
- sync: false
+buildCommand: bundle install && … && (cd ../apps/dashboard && corepack enable pnpm && pnpm install && VITE_BASE_PATH=/dashboard/ pnpm build)
+envVars:
+ - key: SPREE_DASHBOARD_DIST_PATH
+ value: ../apps/dashboard/dist
```
-Static sites on Render are CDN-served with the SPA rewrite built in, so only the two cross-origin steps remain manual:
+That's the whole setup — one service, one origin, **your customized dashboard** (it builds from your `apps/dashboard`, not the stock bundle) at `https://your-service.onrender.com/dashboard`. No `VITE_SPREE_API_URL`, no Allowed Origins entry, no extra service. Redeploys rebuild on every push.
-1. **Set `VITE_SPREE_API_URL`** when Render prompts for it (that's what `sync: false` does) — the backend's public URL, e.g. `https://spree-abc123.onrender.com` or your custom API domain.
-2. **Add the dashboard's Render URL to Allowed Origins** in the Spree admin after the first deploy.
-
-Redeploys rebuild automatically on push, and each Render environment (staging, production) builds its own bundle with its own API URL.
+If you prefer the dashboard on Render's CDN instead, add a static-site service by hand using the cross-origin recipe above.
## Any other static host
-The same three ingredients, by hand: build with `VITE_SPREE_API_URL` set, upload `dist/`, configure the `/* → /index.html` rewrite (`_redirects` on Netlify, `vercel.json` rewrites on Vercel, `try_files $uri /index.html;` on nginx). Then add the origin to Allowed Origins.
+The same three ingredients, by hand: build with `VITE_SPREE_API_URL` set, upload `dist/`, configure the `/* → /index.html` rewrite. Then add the origin to Allowed Origins.
+
+## Checklist (cross-origin only)
-## Checklist
+Single-node deployments skip all of this — one origin needs none of it.
- [ ] `VITE_SPREE_API_URL` points at the production API (baked at build time — one build per environment)
- [ ] HTTPS on the dashboard *and* the API
diff --git a/docs/plans/5.6-project-layout-and-dashboard.md b/docs/plans/5.6-project-layout-and-dashboard.md
index db443e9639..88b9e6011e 100644
--- a/docs/plans/5.6-project-layout-and-dashboard.md
+++ b/docs/plans/5.6-project-layout-and-dashboard.md
@@ -161,6 +161,17 @@ VITE_SPREE_API_URL=http://localhost:3000
No credentials. The dashboard authenticates admins interactively — email/password exchanged for a JWT held in memory plus an httpOnly refresh cookie (`5.5-admin-auth-cookie-refresh.md`). `VITE_`-prefixed variables are baked into the client bundle at build time, so secrets must never appear in this file. Integrations that need a secret API key mint one with `spree api-key create`, independent of the dashboard scaffold.
+### Single-node hosting (default deployment) *(implemented: Rails host + basepath)*
+
+The default production topology is **single node**: the Spree server serves the built dashboard at `/dashboard`, same origin as the Admin API — no CORS, `SameSite=Lax` cookies, one deployable. The pieces:
+
+- **Rails host** *(implemented)*: `Spree::Api::DashboardAppController` serves `Spree::Config.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.
+- **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`).
+- **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**: when the Classic Admin retires, the SPA moves from `/dashboard` to `/admin` and this becomes the default admin delivery. The static/CDN topology (see the deployment docs) remains the alternative for customized dashboards on independent release cadences.
+
### Scaffolding flow changes (`create-spree-app`)
**Prompts (interactive):**
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index c65a90563b..2dedd77f68 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -87,11 +87,16 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption
writeDashboardEnv(envPath, ctx.port)
const pm = detectPackageManager(ctx.projectDir, dashboardDir)
- if (ensureRenderBlueprintService(ctx.projectDir, pm) === 'added') {
+ const blueprint = ensureRenderBlueprintService(ctx.projectDir, pm)
+ if (blueprint === 'amended') {
p.log.info(
- `Added a static-site service to ${pc.bold('render.yaml')}. At deploy, set ` +
- `${pc.cyan('VITE_SPREE_API_URL')} to the backend's public URL and add the ` +
- `dashboard's URL to Allowed Origins in the Spree admin.`,
+ `Amended ${pc.bold('render.yaml')}: the backend service now builds the dashboard ` +
+ `and serves it at ${pc.cyan('/dashboard')} — same origin, nothing else to configure.`,
+ )
+ } else if (blueprint === 'unrecognized') {
+ p.log.warn(
+ `${pc.bold('render.yaml')} exists but doesn't match the starter Blueprint — ` +
+ `left untouched. See the dashboard deployment docs to wire it up manually.`,
)
}
@@ -147,64 +152,65 @@ function resolveBundledTemplate(): string {
}
/**
- * Register the dashboard as a static-site service in the project's Render
- * Blueprint, when one exists (create-spree-app relocates spree-starter's
- * render.yaml to the project root). Static sites on Render are CDN-served
- * with SPA rewrites, which is exactly the dashboard's production shape:
- * `vite build` → `dist/`, no Node server. Two things stay manual by design:
- * `VITE_SPREE_API_URL` (`sync: false` makes Render prompt — the backend's
- * public URL isn't knowable here) and the Allowed Origins entry on the
- * Spree side (the API rejects cross-origin calls until the merchant adds
- * the dashboard's URL).
+ * Fold the dashboard into the project's Render Blueprint as **single node**:
+ * the backend web service builds `apps/dashboard` in its own build step
+ * (Render's Ruby runtime includes Node; the repo is fully cloned even with
+ * `rootDir: backend`, so `../apps/dashboard` is reachable) and serves it at
+ * /dashboard via `SPREE_DASHBOARD_DIST_PATH`. Same origin as the API — no
+ * CORS entries, no `VITE_SPREE_API_URL`, nothing manual after deploy.
+ *
+ * The amendment anchors on the starter Blueprint's shape (a `buildCommand:`
+ * running `bundle install`, followed by that service's `envVars:`). A
+ * hand-customized Blueprint where those anchors are missing is left
+ * untouched — returns 'unrecognized' so the caller can point at the
+ * deployment docs instead of guessing.
*
- * Idempotent: an existing `spree-dashboard` service is left untouched.
+ * Idempotent: a Blueprint already carrying SPREE_DASHBOARD_DIST_PATH is
+ * left as-is.
*/
export function ensureRenderBlueprintService(
projectDir: string,
pm: string,
-): 'added' | 'present' | 'no-blueprint' {
+): 'amended' | 'present' | 'no-blueprint' | 'unrecognized' {
const renderYamlPath = path.join(projectDir, 'render.yaml')
if (!fs.existsSync(renderYamlPath)) return 'no-blueprint'
const content = fs.readFileSync(renderYamlPath, 'utf-8')
- if (content.includes('name: spree-dashboard')) return 'present'
+ if (content.includes('SPREE_DASHBOARD_DIST_PATH')) return 'present'
- const buildCommand =
+ const dashboardBuild =
pm === 'pnpm'
- ? 'corepack enable pnpm && pnpm install && pnpm build'
+ ? 'corepack enable pnpm && pnpm install && VITE_BASE_PATH=/dashboard/ pnpm build'
: pm === 'yarn'
- ? 'yarn install && yarn build'
- : 'npm install && npm run build'
+ ? 'yarn install && VITE_BASE_PATH=/dashboard/ yarn build'
+ : 'npm install && VITE_BASE_PATH=/dashboard/ npm run build'
+
+ // 1. Extend the Rails build to also build the dashboard (subshell keeps the
+ // working directory intact for any commands appended later).
+ const buildCommandRe = /^([ \t]*)buildCommand:.*bundle install.*$/m
+ const buildMatch = buildCommandRe.exec(content)
+ if (!buildMatch) return 'unrecognized'
+
+ let next = content.replace(
+ buildCommandRe,
+ (line) => `${line} && (cd ../apps/dashboard && ${dashboardBuild})`,
+ )
+
+ // 2. Point the server at the built dist. Anchor on the first `envVars:`
+ // after the build command — the same service's env block. The path is
+ // resolved relative to the service's working directory (rootDir).
+ const envVarsRe = /^([ \t]*)envVars:[ \t]*$/m
+ const afterBuild = next.slice(next.indexOf('buildCommand:'))
+ const envMatch = envVarsRe.exec(afterBuild)
+ if (!envMatch) return 'unrecognized'
- const service = `
- # React Dashboard (Developer Preview) — a static site built from
- # apps/dashboard. After the first deploy:
- # 1. Set VITE_SPREE_API_URL to the backend's public URL (Render prompts).
- # 2. Add the dashboard's URL to Allowed Origins in the Spree admin so the
- # API accepts its cross-origin requests and auth cookies.
- - type: web
- name: spree-dashboard
- runtime: static
- rootDir: apps/dashboard
- buildCommand: ${buildCommand}
- staticPublishPath: dist
- routes:
- - type: rewrite
- source: /*
- destination: /index.html
- envVars:
- - key: VITE_SPREE_API_URL
- sync: false
-`
+ const envIndent = `${envMatch[1]} `
+ const envEntry = `${envIndent}# Serve the dashboard built above at /dashboard (single node — same\n${envIndent}# origin as the API, so no CORS or cookie configuration).\n${envIndent}- key: SPREE_DASHBOARD_DIST_PATH\n${envIndent} value: ../apps/dashboard/dist\n`
+ const envVarsIndex = next.indexOf('buildCommand:') + envMatch.index + envMatch[0].length
+ next = `${next.slice(0, envVarsIndex)}\n${envEntry.replace(/\n$/, '')}${next.slice(envVarsIndex)}`
- // Keep the service inside the `services:` array: insert before the
- // top-level `databases:` key when present, else append.
- const databasesMatch = /^databases:/m.exec(content)
- const next = databasesMatch
- ? `${content.slice(0, databasesMatch.index)}${service}\n${content.slice(databasesMatch.index)}`
- : `${content.trimEnd()}\n${service}`
fs.writeFileSync(renderYamlPath, next)
- return 'added'
+ return 'amended'
}
/**
diff --git a/packages/cli/tests/add-dashboard.test.ts b/packages/cli/tests/add-dashboard.test.ts
index d7263d427d..f97dbfc23c 100644
--- a/packages/cli/tests/add-dashboard.test.ts
+++ b/packages/cli/tests/add-dashboard.test.ts
@@ -76,12 +76,21 @@ describe('addDashboard', () => {
expect(fs.readFileSync(envPath, 'utf-8')).toContain('http://localhost:3999')
})
- describe('Render Blueprint registration', () => {
+ describe('Render Blueprint single-node amendment', () => {
+ // The starter Blueprint shape after create-spree-app relocates it.
const BLUEPRINT = `services:
- type: web
name: spree
runtime: ruby
rootDir: backend
+ plan: free
+ buildCommand: bundle install && bundle exec rails assets:precompile && bundle exec rails db:prepare
+ startCommand: bundle exec puma -C config/puma.rb
+ envVars:
+ - key: DATABASE_URL
+ fromDatabase:
+ name: spree-db
+ property: connectionString
- type: redis
name: spree-redis
@@ -90,29 +99,35 @@ databases:
- name: spree-db
`
- it('adds a static-site service inside the services array', async () => {
+ it('extends the backend service to build and serve the dashboard', async () => {
fs.writeFileSync(path.join(projectDir, 'render.yaml'), BLUEPRINT)
await addDashboard(ctx(), { template: templateDir, install: false })
const content = fs.readFileSync(path.join(projectDir, 'render.yaml'), 'utf-8')
- expect(content).toContain('name: spree-dashboard')
- expect(content).toContain('runtime: static')
- expect(content).toContain('rootDir: apps/dashboard')
- expect(content).toContain('staticPublishPath: dist')
- expect(content).toContain('destination: /index.html')
- expect(content).toContain('sync: false')
- // Stays inside the services array — before the top-level databases key.
- expect(content.indexOf('spree-dashboard')).toBeLessThan(content.indexOf('databases:'))
+ // Build step appended to the Rails buildCommand, dashboard built with
+ // the sub-path base and no absolute API URL (origin-relative).
+ expect(content).toContain(
+ 'bundle exec rails db:prepare && (cd ../apps/dashboard && corepack enable pnpm && pnpm install && VITE_BASE_PATH=/dashboard/ pnpm build)',
+ )
+ // Served by the same service — env var inside the backend's envVars.
+ expect(content).toContain('- key: SPREE_DASHBOARD_DIST_PATH')
+ expect(content).toContain('value: ../apps/dashboard/dist')
+ expect(content.indexOf('SPREE_DASHBOARD_DIST_PATH')).toBeLessThan(
+ content.indexOf('DATABASE_URL'),
+ )
+ // No cross-origin machinery: no static site, no VITE_SPREE_API_URL.
+ expect(content).not.toContain('VITE_SPREE_API_URL')
+ expect(content).not.toContain('runtime: static')
})
it('is idempotent and picks the build command from the project lockfile', async () => {
fs.writeFileSync(path.join(projectDir, 'render.yaml'), BLUEPRINT)
fs.writeFileSync(path.join(projectDir, 'package-lock.json'), '{}')
- expect(ensureRenderBlueprintService(projectDir, 'npm')).toBe('added')
+ expect(ensureRenderBlueprintService(projectDir, 'npm')).toBe('amended')
const once = fs.readFileSync(path.join(projectDir, 'render.yaml'), 'utf-8')
- expect(once).toContain('buildCommand: npm install && npm run build')
+ expect(once).toContain('npm install && VITE_BASE_PATH=/dashboard/ npm run build')
expect(ensureRenderBlueprintService(projectDir, 'npm')).toBe('present')
expect(fs.readFileSync(path.join(projectDir, 'render.yaml'), 'utf-8')).toBe(once)
@@ -123,15 +138,12 @@ databases:
expect(fs.existsSync(path.join(projectDir, 'render.yaml'))).toBe(false)
})
- it('appends at the end when there is no databases key', () => {
- fs.writeFileSync(
- path.join(projectDir, 'render.yaml'),
- 'services:\n - type: web\n name: spree\n',
- )
- expect(ensureRenderBlueprintService(projectDir, 'pnpm')).toBe('added')
- const content = fs.readFileSync(path.join(projectDir, 'render.yaml'), 'utf-8')
- expect(content).toContain('name: spree-dashboard')
- expect(content).toContain('corepack enable pnpm && pnpm install && pnpm build')
+ it('leaves an unrecognized Blueprint untouched', () => {
+ const custom = 'services:\n - type: web\n name: my-thing\n runtime: docker\n'
+ fs.writeFileSync(path.join(projectDir, 'render.yaml'), custom)
+
+ expect(ensureRenderBlueprintService(projectDir, 'pnpm')).toBe('unrecognized')
+ expect(fs.readFileSync(path.join(projectDir, 'render.yaml'), 'utf-8')).toBe(custom)
})
})
})
diff --git a/packages/dashboard-starter/src/main.tsx b/packages/dashboard-starter/src/main.tsx
index 39e0c3864b..0195d9ff6f 100644
--- a/packages/dashboard-starter/src/main.tsx
+++ b/packages/dashboard-starter/src/main.tsx
@@ -15,7 +15,9 @@ import './styles.css'
// it — its diff on upgrades shows exactly which admin pages changed.
import { routeTree } from './routeTree.gen'
-const router = createDashboardRouter(routeTree)
+// basepath mirrors Vite's `base` so sub-path mounts (/dashboard on the
+// single-node topology) route correctly; '/' in dev and root deploys.
+const router = createDashboardRouter(routeTree, { basepath: import.meta.env.BASE_URL })
// Registers the composed router program-wide so <Link> and navigation are
// type-checked against the real route tree — shell, host, and plugin routes.
diff --git a/packages/dashboard-starter/vite.config.ts b/packages/dashboard-starter/vite.config.ts
index 5a9380fbe2..238f29444a 100644
--- a/packages/dashboard-starter/vite.config.ts
+++ b/packages/dashboard-starter/vite.config.ts
@@ -3,6 +3,10 @@ import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
export default defineConfig({
+ // Sub-path mounting for the single-node topology (Rails serves the build at
+ // /dashboard): build with VITE_BASE_PATH=/dashboard/ so asset URLs resolve.
+ // Unset (dev, CDN root deploys) Vite defaults to '/'.
+ base: process.env.VITE_BASE_PATH,
// spreeDashboardPlugin bundles Tailwind, injects @source directives for
// every Spree dashboard package, auto-discovers installed dashboard
// plugins (package.json deps carrying the `spree.dashboard.plugin`
diff --git a/packages/dashboard/src/create-router.ts b/packages/dashboard/src/create-router.ts
index 49f45762ac..0081c21b76 100644
--- a/packages/dashboard/src/create-router.ts
+++ b/packages/dashboard/src/create-router.ts
@@ -26,11 +26,23 @@ import {
* augmentations merge program-wide, so the shell declaring its own would
* conflict with the host's composed tree.
*/
-export function createDashboardRouter<TRouteTree extends AnyRoute>(routeTree: TRouteTree) {
+export interface DashboardRouterOptions {
+ /**
+ * Path prefix when the dashboard is served from a sub-path (the single-node
+ * topology mounts it at `/dashboard`). Pass `import.meta.env.BASE_URL` so it
+ * always matches the Vite `base` the app was built with.
+ */
+ basepath?: string
+}
+
+export function createDashboardRouter<TRouteTree extends AnyRoute>(
+ routeTree: TRouteTree,
+ { basepath }: DashboardRouterOptions = {},
+) {
// Cast because the shell's root route requires no router context, which
// TypeScript cannot prove through the generic tree parameter. The return
// type stays parameterized by TRouteTree — that's what makes links typed.
- const options = { routeTree } as RouterConstructorOptions<
+ const options = { routeTree, basepath } as RouterConstructorOptions<
TRouteTree,
'never',
false,
diff --git a/packages/dashboard/src/main.tsx b/packages/dashboard/src/main.tsx
index cd14092bbf..ddd4598f2d 100644
--- a/packages/dashboard/src/main.tsx
+++ b/packages/dashboard/src/main.tsx
@@ -12,7 +12,9 @@ import 'virtual:spree-dashboard-plugins'
import './styles.css'
import { routeTree } from './routeTree.gen'
-const router = createDashboardRouter(routeTree)
+// basepath mirrors Vite's `base` so sub-path mounts (/dashboard on the
+// single-node topology) route correctly; '/' in dev and root deploys.
+const router = createDashboardRouter(routeTree, { basepath: import.meta.env.BASE_URL })
declare module '@tanstack/react-router' {
interface Register {
diff --git a/packages/dashboard/vite.config.ts b/packages/dashboard/vite.config.ts
index 1cd6d46ab2..a6cc5ac8c3 100644
--- a/packages/dashboard/vite.config.ts
+++ b/packages/dashboard/vite.config.ts
@@ -9,6 +9,10 @@ import { defineConfig } from 'vite'
import { spreeDashboardPlugin } from './src/vite'
export default defineConfig({
+ // Sub-path mounting for the single-node topology: the official Docker image
+ // builds with VITE_BASE_PATH=/dashboard/ so asset URLs resolve under the
+ // Rails-served mount. Unset (dev, CDN root deploys) Vite defaults to '/'.
+ base: process.env.VITE_BASE_PATH,
// The plugin bundles `@tailwindcss/vite`, so we don't register it separately.
// `cssEntry` defaults to `./src/styles.css`, which matches our entry — pass
// it here only as a hint for readers of this config.
diff --git a/spree/api/app/controllers/spree/api/dashboard_app_controller.rb b/spree/api/app/controllers/spree/api/dashboard_app_controller.rb
new file mode 100644
index 0000000000..7eaa4ee641
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/dashboard_app_controller.rb
@@ -0,0 +1,61 @@
+module Spree
+ module Api
+ # Serves a built React Dashboard (`vite build` output) at /dashboard — the
+ # single-node topology: the SPA and the Admin API share one origin, so no
+ # CORS entries and Lax cookies. The dist directory comes from
+ # `Spree::Config.dashboard_dist_path` (the official Docker image sets it
+ # via SPREE_DASHBOARD_DIST_PATH); when unset, /dashboard 404s.
+ #
+ # SPA semantics: real files are served with long-lived caching (Vite's
+ # `assets/` are content-hashed, so they're immutable); every other path
+ # falls back to index.html with no-cache so deploys take effect on the
+ # next navigation. No authentication — the bundle is public client code;
+ # the SPA authenticates its API calls itself.
+ class DashboardAppController < ActionController::API
+ def show
+ root = dist_root
+ return head :not_found unless root
+
+ if (file = resolve_file(root, params[:path].to_s))
+ response.headers['Cache-Control'] = cache_control_for(params[:path].to_s)
+ send_file file, disposition: 'inline'
+ elsif (index = root.join('index.html')).file?
+ response.headers['Cache-Control'] = 'no-cache'
+ send_file index, type: 'text/html', disposition: 'inline'
+ else
+ head :not_found
+ end
+ end
+
+ private
+
+ def dist_root
+ path = Spree::Config.dashboard_dist_path.presence || ENV.fetch('SPREE_DASHBOARD_DIST_PATH', nil)
+ return if path.blank?
+
+ root = Pathname.new(path).expand_path
+ root if root.directory?
+ end
+
+ # Resolve a request path to a real file inside the dist directory,
+ # rejecting anything that escapes it (`..`, absolute paths, symlinks
+ # pointing outside are covered by the expanded-path prefix check).
+ def resolve_file(root, relative_path)
+ return if relative_path.blank?
+
+ candidate = root.join(relative_path).expand_path
+ return unless candidate.to_s.start_with?("#{root}#{File::SEPARATOR}")
+
+ candidate if candidate.file?
+ end
+
+ def cache_control_for(relative_path)
+ if relative_path.start_with?('assets/')
+ 'public, max-age=31536000, immutable'
+ else
+ 'public, max-age=3600'
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 7a9b025edd..724dc31989 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -383,4 +383,11 @@ Spree::Core::Engine.add_routes do
end
end
end
+
+ # Hosted React Dashboard (single-node topology). Serves the built SPA from
+ # `Spree::Config.dashboard_dist_path`; 404s when unconfigured. `format: false`
+ # keeps asset extensions (.js, .css, .svg) inside the splat instead of being
+ # parsed as a response format.
+ get '/dashboard', to: 'api/dashboard_app#show', as: :dashboard_app
+ get '/dashboard/*path', to: 'api/dashboard_app#show', format: false
end
diff --git a/spree/api/spec/requests/spree/api/dashboard_app_spec.rb b/spree/api/spec/requests/spree/api/dashboard_app_spec.rb
new file mode 100644
index 0000000000..01f3fcba35
--- /dev/null
+++ b/spree/api/spec/requests/spree/api/dashboard_app_spec.rb
@@ -0,0 +1,79 @@
+require 'spec_helper'
+
+RSpec.describe 'Hosted React Dashboard', type: :request do
+ let(:dist) { Dir.mktmpdir }
+
+ before do
+ File.write(File.join(dist, 'index.html'), '<html>dashboard shell</html>')
+ FileUtils.mkdir_p(File.join(dist, 'assets'))
+ File.write(File.join(dist, 'assets', 'app-abc123.js'), 'console.log("bundle")')
+ File.write(File.join(dist, 'favicon.svg'), '<svg/>')
+ end
+
+ after do
+ FileUtils.remove_entry(dist)
+ Spree::Config.dashboard_dist_path = nil
+ end
+
+ context 'when dashboard_dist_path is not configured' do
+ it 'returns 404' do
+ get '/dashboard'
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context 'when dashboard_dist_path is configured' do
+ before { Spree::Config.dashboard_dist_path = dist }
+
+ it 'serves index.html at the root with no-cache' do
+ get '/dashboard'
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to include('dashboard shell')
+ expect(response.headers['Cache-Control']).to eq('no-cache')
+ end
+
+ it 'serves hashed assets as immutable' do
+ get '/dashboard/assets/app-abc123.js'
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to include('bundle')
+ # Rails normalizes Cache-Control directive order — assert on parts.
+ expect(response.headers['Cache-Control']).to include('max-age=31536000')
+ expect(response.headers['Cache-Control']).to include('immutable')
+ end
+
+ it 'serves non-hashed root files with a short cache' do
+ get '/dashboard/favicon.svg'
+
+ expect(response).to have_http_status(:ok)
+ expect(response.headers['Cache-Control']).to include('max-age=3600')
+ end
+
+ it 'falls back to index.html for SPA routes' do
+ get '/dashboard/store_abc/orders'
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to include('dashboard shell')
+ expect(response.headers['Cache-Control']).to eq('no-cache')
+ end
+
+ it 'does not serve files outside the dist directory' do
+ secret = File.expand_path(File.join(dist, '..', "spree-secret-#{Process.pid}.txt"))
+ File.write(secret, 'top secret')
+
+ get '/dashboard/%2e%2e/' + File.basename(secret)
+
+ expect(response.body).not_to include('top secret')
+ ensure
+ FileUtils.rm_f(secret)
+ end
+
+ it 'returns 404 when the configured directory does not exist' do
+ Spree::Config.dashboard_dist_path = File.join(dist, 'missing')
+
+ get '/dashboard'
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index 61d7f66010..3c415ee67d 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -43,6 +43,12 @@ module Spree
preference :company, :boolean, default: false, deprecated: 'Use the company_field_enabled preference in the Spree::Store model' # Request company field for billing and shipping addr
preference :currency, :string, default: 'USD', deprecated: true
preference :credit_to_new_allocation, :boolean, default: false
+ # Directory holding a built React Dashboard (`vite build` output). When
+ # set (or via the SPREE_DASHBOARD_DIST_PATH env var, which the official
+ # Docker image uses), the app serves the SPA at /dashboard — the
+ # single-node topology: same origin as the Admin API, so no CORS or
+ # cookie configuration. Unset, /dashboard 404s.
+ preference :dashboard_dist_path, :string, default: nil
preference :disable_migration_check, :boolean, default: false # when turned on disables the startup warning about missing engine migrations
preference :enable_legacy_default_price, :boolean, default: false # when enabled, keeps the legacy DefaultPrice concern active (has_one :default_price, variant.price= delegation, check_price validation). Disable (default) to use set_price exclusively.
preference :disable_sku_validation, :boolean, default: false # when turned off disables the built-in SKU uniqueness validation