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.

Fix dashboard logins dying on CORS in scaffolded apps (#14310)

Damian Legawiecf145a98e1e33
diff --git a/CLAUDE.md b/CLAUDE.md
index 771b0b2122..b54c3bb8f2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -39,7 +39,7 @@ Multi-version plans (some phases shipped, some pending):
- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.
- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.
- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.
-- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — Vendure-style, no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (env carries only `VITE_SPREE_API_URL` — never secret keys), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.
+- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — Vendure-style, no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.
- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.
Pending design work (drafts, no implementation yet):
@@ -493,7 +493,7 @@ pnpm turbo dev --filter=@spree/dashboard-starter # http://localhost:5173 (prox
The starter is the canonical host — the same app `spree add dashboard` scaffolds — so local dev exercises the real consumer path (shell + plugin pipeline) while still hot-reloading `@spree/dashboard`/`-core`/`-ui` source through the workspace. `turbo dev` (not a bare `pnpm dev` inside the package) matters on a fresh clone: the starter's `vite.config.ts` resolves the compiled Node-side Vite entries (`@spree/dashboard/vite`, `@spree/dashboard-core/vite`) from `dist/`, and turbo's `^build` dependency produces them. After any full `pnpm build`, `cd packages/dashboard-starter && pnpm dev` works too.
-`VITE_SPREE_API_URL` overrides the backend URL (default `http://localhost:3000`). Sign in with the seed admin user (`[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`).
+`VITE_API_PROXY_TARGET` overrides the backend the dev proxy targets (default `http://localhost:3000`); don't use `VITE_SPREE_API_URL` in dev — it flips the SDK to absolute cross-origin URLs, bypassing the proxy. Sign in with the seed admin user (`[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`).
**When implementing a new admin feature:**
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index 1e3a854a81..b8000dfa8c 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,25 @@
# @spree/cli
+## 2.4.3
+
+### Patch Changes
+
+- Fix dashboard logins dying on CORS in scaffolded apps. `spree add
+dashboard` wrote `VITE_SPREE_API_URL=http://localhost:<port>` into
+`apps/dashboard/.env.local` — but that variable is the SDK's switch to
+absolute cross-origin URLs (meant for production deploys on a different
+origin), so requests bypassed the Vite dev proxy and the browser blocked
+them (`localhost:5173` → `localhost:3000` is cross-origin; the auth cookie
+is `SameSite=Lax` on top). The scaffold now writes `VITE_API_PROXY_TARGET`
+(the proxy target — the SPA stays same-origin, the SDK stays on relative
+URLs), the dashboard template's Vite config reads it (via `loadEnv` — Vite
+doesn't load `.env` files into `process.env` for configs), and the CLI
+writes or repairs `.env.local` automatically: on scaffold, on every
+`spree dev` boot, and on a `spree add dashboard` re-run — covering fresh
+clones (the file is gitignored) and projects scaffolded by older CLI
+versions. Repair rewrites only the broken line; everything else in the
+file is preserved.
+
## 2.4.2
### Patch Changes
diff --git a/packages/cli/package.json b/packages/cli/package.json
index eebf3f27a8..ca8390d28e 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "2.4.2",
+ "version": "2.4.3",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts
index 958cf1fc4e..a458569e8d 100644
--- a/packages/cli/src/commands/add.ts
+++ b/packages/cli/src/commands/add.ts
@@ -5,6 +5,7 @@ import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execa } from 'execa'
import pc from 'picocolors'
+import { isNotFound } from '../config.js'
import { DASHBOARD_PORT } from '../constants.js'
import { detectProject } from '../context.js'
import type { ProjectContext } from '../types.js'
@@ -61,14 +62,17 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption
const envPath = path.join(dashboardDir, '.env.local')
if (fs.existsSync(dashboardDir)) {
- if (fs.existsSync(envPath)) {
+ // Recovery: write a missing .env.local (interrupted earlier run) or
+ // repair a broken one (old scaffold output) — one gatekeeper for both.
+ const env = ensureDashboardDevEnv(ctx.projectDir, ctx.port)
+ if (env === 'untouched') {
p.log.warn(`${pc.bold('apps/dashboard/')} already exists. Nothing to do.`)
return
}
- // Recovery: directory present but env missing (interrupted earlier run).
- writeDashboardEnv(envPath, ctx.port)
ensureRenderBlueprintService(ctx.projectDir, detectPackageManager(ctx.projectDir, dashboardDir))
- p.log.info(`Wrote missing ${pc.bold('apps/dashboard/.env.local')}. Nothing else to do.`)
+ p.log.info(
+ `${env === 'written' ? 'Wrote missing' : 'Repaired'} ${pc.bold('apps/dashboard/.env.local')}. Nothing else to do.`,
+ )
return
}
@@ -114,7 +118,7 @@ export async function addDashboard(ctx: ProjectContext, opts: AddDashboardOption
p.note(
[
`Start it with:`,
- ` ${pc.cyan('cd apps/dashboard && ' + (opts.install ? '' : 'pnpm install && ') + 'pnpm dev')}`,
+ ` ${pc.cyan(`cd apps/dashboard && ${opts.install ? '' : 'pnpm install && '}pnpm dev`)}`,
'',
`Then open ${pc.bold(`http://localhost:${DASHBOARD_PORT}`)} and sign in`,
`with your admin email and password.`,
@@ -239,13 +243,61 @@ async function fetchTemplate(template: string, dst: string): Promise<void> {
fs.rmSync(path.join(dst, '.git'), { recursive: true, force: true })
}
+// Old scaffolds wrote the SDK's absolute-URL switch pointed at localhost —
+// requests then bypassed the dev proxy and died on CORS + the SameSite=Lax
+// cookie. A localhost value can only be that scaffold output, never a real
+// cross-origin production URL, so it's safe to migrate in place.
+const BROKEN_SCAFFOLD_ENV = /^VITE_SPREE_API_URL=(https?:\/\/localhost\S*)$/m
+
+/**
+ * Writes or repairs `apps/dashboard/.env.local` so dashboard dev works out
+ * of the box. Idempotent and cheap — called from `spree add dashboard`,
+ * first-run setup, and every `spree dev` boot, covering fresh clones (the
+ * file is gitignored) and old scaffolds (see {@link BROKEN_SCAFFOLD_ENV};
+ * only that line is rewritten — everything else in the file is user-managed
+ * and preserved).
+ */
+export function ensureDashboardDevEnv(
+ projectDir: string,
+ port: number,
+): 'written' | 'repaired' | 'untouched' {
+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
+ if (!fs.existsSync(path.join(dashboardDir, 'package.json'))) return 'untouched'
+
+ const envPath = path.join(dashboardDir, '.env.local')
+ let existing: string
+ try {
+ existing = fs.readFileSync(envPath, 'utf-8')
+ } catch (error) {
+ if (!isNotFound(error)) throw error // unreadable ≠ missing — never clobber
+ writeDashboardEnv(envPath, port)
+ return 'written'
+ }
+
+ if (!BROKEN_SCAFFOLD_ENV.test(existing)) return 'untouched'
+ fs.writeFileSync(
+ envPath,
+ existing.replace(BROKEN_SCAFFOLD_ENV, `VITE_API_PROXY_TARGET=http://localhost:${port}`),
+ )
+ return 'repaired'
+}
+
function writeDashboardEnv(envPath: string, port: number): void {
fs.writeFileSync(
envPath,
[
- '# URL of your Spree API server. No credentials belong in this file —',
- '# every VITE_-prefixed value is compiled into the client bundle.',
- `VITE_SPREE_API_URL=http://localhost:${port}`,
+ '# Dev-server proxy target — where Vite forwards /api and /rails (your',
+ '# Rails backend). The SPA stays same-origin with the API: the SDK uses',
+ '# relative URLs and the proxy bridges the port gap.',
+ '#',
+ '# Do NOT set VITE_SPREE_API_URL for local dev — it switches the SDK to',
+ '# absolute cross-origin URLs, which breaks on CORS and the SameSite=Lax',
+ '# auth cookie. Set it only when building for a deploy where the',
+ '# dashboard is hosted on a different origin than the API.',
+ '#',
+ '# No credentials belong in this file — every VITE_-prefixed value is',
+ '# compiled into the client bundle.',
+ `VITE_API_PROXY_TARGET=http://localhost:${port}`,
'',
].join('\n'),
)
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
index e6e25d81e8..cb61b8d34c 100644
--- a/packages/cli/src/commands/dev.ts
+++ b/packages/cli/src/commands/dev.ts
@@ -18,6 +18,7 @@ import {
primeBundleVolume,
watchAdminStylesheets,
} from '../docker.js'
+import { ensureDashboardDevEnv } from './add.js'
import { runFirstRunSetup } from './init.js'
export function registerDevCommand(program: Command): void {
@@ -38,6 +39,12 @@ export function registerDevCommand(program: Command): void {
process.exit(1)
}
+ // Every boot, not just first run: cheap and idempotent, and it's how
+ // projects scaffolded by older CLIs (broken .env.local) get repaired —
+ // they already completed setup, so the first-run path below never
+ // reaches them.
+ ensureDashboardDevEnv(ctx.projectDir, ctx.port)
+
// A project that was never set up gets the full first-run flow instead
// of a bare `up`: pull a fresh image (a mutable tag cached weeks ago by
// another project would otherwise boot an old Spree), seed the database,
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 29a1b5e6f6..88eab3b5f1 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -9,7 +9,7 @@ import { mintProjectCredentials, writeProjectSetupMarker } from '../config.js'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
import { detectProject, readSampleDataFromEnv } from '../context.js'
import { dockerCompose, primeBundleVolume, rakeTask, streamLogs } from '../docker.js'
-import { detectPackageManager } from './add.js'
+import { detectPackageManager, ensureDashboardDevEnv } from './add.js'
const HEALTH_CHECK_INTERVAL_MS = 3000
const HEALTH_CHECK_TIMEOUT_MS = 120_000
@@ -76,6 +76,7 @@ export async function runFirstRunSetup(flags: {
await installAppDeps(ctx.projectDir, 'storefront')
await installAppDeps(ctx.projectDir, 'dashboard')
+ ensureDashboardDevEnv(ctx.projectDir, ctx.port)
if (sampleData) {
s.start('Loading sample data...')
diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts
index 270dbc7e33..e7f53af269 100644
--- a/packages/cli/src/config.ts
+++ b/packages/cli/src/config.ts
@@ -77,7 +77,7 @@ export function configPath(): string {
}
/** True when a thrown fs error is "no such file" (vs a permission/IO fault). */
-function isNotFound(error: unknown): boolean {
+export function isNotFound(error: unknown): boolean {
return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
}
diff --git a/packages/cli/tests/add-dashboard.test.ts b/packages/cli/tests/add-dashboard.test.ts
index f97dbfc23c..aca9d30f1e 100644
--- a/packages/cli/tests/add-dashboard.test.ts
+++ b/packages/cli/tests/add-dashboard.test.ts
@@ -2,7 +2,11 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import { addDashboard, ensureRenderBlueprintService } from '../src/commands/add.js'
+import {
+ addDashboard,
+ ensureDashboardDevEnv,
+ ensureRenderBlueprintService,
+} from '../src/commands/add.js'
import type { ProjectContext } from '../src/types.js'
/**
@@ -50,7 +54,8 @@ describe('addDashboard', () => {
expect(fs.existsSync(path.join(dashboardDir, 'dist'))).toBe(false)
const env = fs.readFileSync(path.join(dashboardDir, '.env.local'), 'utf-8')
- expect(env).toContain('VITE_SPREE_API_URL=http://localhost:3999')
+ expect(env).toContain('VITE_API_PROXY_TARGET=http://localhost:3999')
+ expect(env).not.toMatch(/^VITE_SPREE_API_URL=/m)
expect(env).not.toMatch(/sk_/)
// gitignore.template restored to its real name
@@ -147,3 +152,55 @@ databases:
})
})
})
+
+describe('ensureDashboardDevEnv', () => {
+ let projectDir: string
+
+ beforeEach(() => {
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-env-repair-'))
+ fs.mkdirSync(path.join(projectDir, 'apps', 'dashboard'), { recursive: true })
+ fs.writeFileSync(
+ path.join(projectDir, 'apps', 'dashboard', 'package.json'),
+ '{"name":"dashboard"}\n',
+ )
+ })
+
+ afterEach(() => {
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ })
+
+ const envPath = () => path.join(projectDir, 'apps', 'dashboard', '.env.local')
+
+ it('writes .env.local when missing (fresh clone)', () => {
+ expect(ensureDashboardDevEnv(projectDir, 3999)).toBe('written')
+ expect(fs.readFileSync(envPath(), 'utf-8')).toContain(
+ 'VITE_API_PROXY_TARGET=http://localhost:3999',
+ )
+ })
+
+ it('repairs only the broken line, preserving user additions', () => {
+ fs.writeFileSync(
+ envPath(),
+ '# my notes\nVITE_SPREE_API_URL=http://localhost:3000\nVITE_MY_FLAG=1\n',
+ )
+ expect(ensureDashboardDevEnv(projectDir, 3999)).toBe('repaired')
+ const env = fs.readFileSync(envPath(), 'utf-8')
+ expect(env).toContain('# my notes')
+ expect(env).toContain('VITE_API_PROXY_TARGET=http://localhost:3999')
+ expect(env).toContain('VITE_MY_FLAG=1')
+ expect(env).not.toMatch(/^VITE_SPREE_API_URL=/m)
+ })
+
+ it('leaves a non-localhost VITE_SPREE_API_URL (real deploy config) untouched', () => {
+ const custom = 'VITE_SPREE_API_URL=https://api.mystore.com\nVITE_MY_FLAG=1\n'
+ fs.writeFileSync(envPath(), custom)
+ expect(ensureDashboardDevEnv(projectDir, 3999)).toBe('untouched')
+ expect(fs.readFileSync(envPath(), 'utf-8')).toBe(custom)
+ })
+
+ it('does nothing without an apps/dashboard app', () => {
+ fs.rmSync(path.join(projectDir, 'apps', 'dashboard'), { recursive: true })
+ expect(ensureDashboardDevEnv(projectDir, 3999)).toBe('untouched')
+ expect(fs.existsSync(envPath())).toBe(false)
+ })
+})
diff --git a/packages/dashboard-starter/.env.example b/packages/dashboard-starter/.env.example
index 9523a1f5eb..0dd421dfea 100644
--- a/packages/dashboard-starter/.env.example
+++ b/packages/dashboard-starter/.env.example
@@ -1,4 +1,12 @@
-# URL of your Spree API server. No credentials belong in this file —
-# admins sign in with email/password in the dashboard itself, and every
-# VITE_-prefixed value is compiled into the client bundle.
-VITE_SPREE_API_URL=http://localhost:3000
+# Dev-server proxy target — where Vite forwards /api and /rails (your
+# Rails backend). The SPA stays same-origin with the API: the SDK uses
+# relative URLs and the proxy bridges the port gap.
+#
+# Do NOT set VITE_SPREE_API_URL for local dev — it switches the SDK to
+# absolute cross-origin URLs, which breaks on CORS and the SameSite=Lax
+# auth cookie. Set it only when building for a deploy where the
+# dashboard is hosted on a different origin than the API.
+#
+# No credentials belong in this file — every VITE_-prefixed value is
+# compiled into the client bundle.
+VITE_API_PROXY_TARGET=http://localhost:3000
diff --git a/packages/dashboard-starter/README.md b/packages/dashboard-starter/README.md
index 578edc0aae..7c0e69ed9a 100644
--- a/packages/dashboard-starter/README.md
+++ b/packages/dashboard-starter/README.md
@@ -8,10 +8,12 @@ The host app for the [Spree React Dashboard](https://spreecommerce.org/docs/deve
```bash
pnpm install
-cp .env.example .env.local # point VITE_SPREE_API_URL at your Spree API
+cp .env.example .env.local # optional — VITE_API_PROXY_TARGET if your API isn't on :3000
pnpm dev # http://localhost:5173
```
+The dev server proxies `/api` to your Rails backend so the SPA stays same-origin — don't set `VITE_SPREE_API_URL` in dev (it switches the SDK to absolute cross-origin URLs, which breaks on CORS and the auth cookie).
+
Sign in with an admin account — authentication is interactive (JWT + refresh cookie). No API keys belong in `.env.local`: every `VITE_`-prefixed value is compiled into the client bundle.
## Install a dashboard plugin
diff --git a/packages/dashboard-starter/vite.config.ts b/packages/dashboard-starter/vite.config.ts
index 238f29444a..5ccf6e2c01 100644
--- a/packages/dashboard-starter/vite.config.ts
+++ b/packages/dashboard-starter/vite.config.ts
@@ -1,33 +1,36 @@
import { spreeDashboardPlugin } from '@spree/dashboard/vite'
import react from '@vitejs/plugin-react'
-import { defineConfig } from 'vite'
+import { defineConfig, loadEnv } 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`
- // marker), serves the `virtual:spree-dashboard-plugins` module that
- // src/main.tsx imports to activate them, and composes the shell's and
- // every plugin's file routes into src/routeTree.gen.ts on each dev
- // start/build — commit that file; its diff shows what an upgrade added.
- plugins: [spreeDashboardPlugin(), react()],
- // Proxy /api to the Rails server so the SPA is same-origin with the API in
- // dev — keeps the refresh-token cookie working under SameSite=Lax without
- // HTTPS. /rails covers Active Storage's Disk-service presigned URLs.
- server: {
- proxy: {
- '/api': {
- target: process.env.VITE_SPREE_API_URL || 'http://localhost:3000',
- changeOrigin: true,
- },
- '/rails': {
- target: process.env.VITE_SPREE_API_URL || 'http://localhost:3000',
- changeOrigin: true,
+export default defineConfig(({ mode }) => {
+ // loadEnv, not process.env: Vite doesn't load .env files before evaluating
+ // this config, and .env.local is where `spree` writes the proxy target.
+ const env = loadEnv(mode, process.cwd(), 'VITE_')
+ const proxyTarget = env.VITE_API_PROXY_TARGET || 'http://localhost:3000'
+
+ return {
+ // 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`
+ // marker), serves the `virtual:spree-dashboard-plugins` module that
+ // src/main.tsx imports to activate them, and composes the shell's and
+ // every plugin's file routes into src/routeTree.gen.ts on each dev
+ // start/build — commit that file; its diff shows what an upgrade added.
+ plugins: [spreeDashboardPlugin(), react()],
+ // Proxy /api to the Rails server so the SPA is same-origin with the API
+ // in dev — keeps the refresh-token cookie working under SameSite=Lax
+ // without HTTPS. /rails covers Active Storage's presigned URLs. Proxy
+ // target, not VITE_SPREE_API_URL — that switches the SDK to absolute
+ // cross-origin URLs and bypasses this proxy (see .env.example).
+ server: {
+ proxy: {
+ '/api': { target: proxyTarget, changeOrigin: true },
+ '/rails': { target: proxyTarget, changeOrigin: true },
},
},
- },
+ }
})
diff --git a/packages/dashboard/playwright.config.ts b/packages/dashboard/playwright.config.ts
index db97ed9864..dd05ca72ea 100644
--- a/packages/dashboard/playwright.config.ts
+++ b/packages/dashboard/playwright.config.ts
@@ -35,8 +35,7 @@ export default defineConfig({
webServer: [
{
// Vite dev — proxies `/api/*` to the test Rails per `vite.config.ts`,
- // overridden via `VITE_SPREE_API_URL` so the proxy targets the test
- // Rails port instead of the dev default.
+ // aimed at the test Rails port via `VITE_API_PROXY_TARGET` below.
command: `pnpm dev --port ${VITE_PORT}`,
url: `http://localhost:${VITE_PORT}`,
reuseExistingServer: false,
diff --git a/packages/dashboard/vite.config.ts b/packages/dashboard/vite.config.ts
index a6cc5ac8c3..d9bad3a3eb 100644
--- a/packages/dashboard/vite.config.ts
+++ b/packages/dashboard/vite.config.ts
@@ -1,6 +1,6 @@
import path from 'node:path'
import react from '@vitejs/plugin-react'
-import { defineConfig } from 'vite'
+import { defineConfig, loadEnv } from 'vite'
// Self-import of the shell's own Vite integration — the same composition
// hosts get from `@spree/dashboard/vite`. It wraps the TanStack Router
// generator, so the shell's committed routeTree.gen.ts is produced by the
@@ -8,61 +8,59 @@ import { defineConfig } from 'vite'
// example plugin's file routes).
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.
- //
- // Plugin selection: hosts normally omit `plugins` so auto-discovery picks up
- // every dep with the `spree.dashboard.plugin` marker. This monorepo copy
- // defaults to an explicit empty whitelist because our only marked dep is the
- // reference plugin (@spree/dashboard-plugin-example, a devDependency) —
- // opt in with VITE_EXAMPLE_PLUGIN=true to exercise the real discovery +
- // activation path end-to-end.
- plugins: [
- spreeDashboardPlugin({
- cssEntry: './src/styles.css',
- plugins: process.env.VITE_EXAMPLE_PLUGIN === 'true' ? undefined : [],
- }),
- react(),
- ],
- resolve: {
- alias: {
- '@': path.resolve(__dirname, './src'),
- },
- },
- // Proxy /api to the Rails server so the SPA is same-origin with the API in dev.
- // Same-origin keeps the refresh-token cookie working under SameSite=Lax without
- // needing HTTPS (production cross-origin uses SameSite=None; Secure).
- //
- // `VITE_API_PROXY_TARGET` is the proxy *target* — kept distinct from
- // `VITE_SPREE_API_URL` (which the SDK reads at build time to switch to
- // absolute URLs) so the E2E suite can keep dev's same-origin path even when
- // pointing at a different Rails port.
- server: {
- proxy: {
- '/api': {
- target:
- process.env.VITE_API_PROXY_TARGET ||
- process.env.VITE_SPREE_API_URL ||
- 'http://localhost:3000',
- changeOrigin: true,
+export default defineConfig(({ mode }) => {
+ // loadEnv, not process.env: Vite doesn't load .env files before evaluating
+ // this config — this way both shell env (E2E) and .env.local work.
+ const env = loadEnv(mode, process.cwd(), 'VITE_')
+ const proxyTarget = env.VITE_API_PROXY_TARGET || 'http://localhost:3000'
+
+ return {
+ // 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.
+ //
+ // Plugin selection: hosts normally omit `plugins` so auto-discovery picks
+ // up every dep with the `spree.dashboard.plugin` marker. This monorepo
+ // copy defaults to an explicit empty whitelist because our only marked dep
+ // is the reference plugin (@spree/dashboard-plugin-example, a
+ // devDependency) — opt in with VITE_EXAMPLE_PLUGIN=true to exercise the
+ // real discovery + activation path end-to-end.
+ plugins: [
+ spreeDashboardPlugin({
+ cssEntry: './src/styles.css',
+ plugins: process.env.VITE_EXAMPLE_PLUGIN === 'true' ? undefined : [],
+ }),
+ react(),
+ ],
+ resolve: {
+ alias: {
+ '@': path.resolve(__dirname, './src'),
},
- // Active Storage's Disk service issues presigned URLs against `/rails/active_storage/...`
- // on the Rails origin. Without proxying, the SPA's PUT from :5173 hits :3000
- // cross-origin and the browser blocks it ("Failed to fetch") because
- // ActiveStorage::DiskController doesn't speak CORS. Proxying keeps it same-origin.
- '/rails': {
- target:
- process.env.VITE_API_PROXY_TARGET ||
- process.env.VITE_SPREE_API_URL ||
- 'http://localhost:3000',
- changeOrigin: true,
+ },
+ // Proxy /api to the Rails server so the SPA is same-origin with the API in
+ // dev. Same-origin keeps the refresh-token cookie working under
+ // SameSite=Lax without needing HTTPS (production cross-origin uses
+ // SameSite=None; Secure).
+ //
+ // `VITE_API_PROXY_TARGET` is the proxy *target* — deliberately distinct
+ // from `VITE_SPREE_API_URL` (the SDK's build-time switch to absolute URLs,
+ // for deploys on a different origin): setting that in dev would bypass
+ // this proxy and break on CORS and the SameSite=Lax cookie. The E2E suite
+ // uses the proxy target to point at the test Rails port.
+ server: {
+ proxy: {
+ '/api': { target: proxyTarget, changeOrigin: true },
+ // Active Storage's Disk service issues presigned URLs against
+ // `/rails/active_storage/...` on the Rails origin. Without proxying,
+ // the SPA's PUT from :5173 hits :3000 cross-origin and the browser
+ // blocks it ("Failed to fetch") because ActiveStorage::DiskController
+ // doesn't speak CORS. Proxying keeps it same-origin.
+ '/rails': { target: proxyTarget, changeOrigin: true },
},
},
- },
+ }
})