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.

Auto-open Admin Dashboard in browser when running `spree dev` (#14890)

Damian Legawiec57469fe727cf
diff --git a/.changeset/spree-dev-open-dashboard.md b/.changeset/spree-dev-open-dashboard.md
new file mode 100644
index 0000000000..b81b0ef42d
--- /dev/null
+++ b/.changeset/spree-dev-open-dashboard.md
@@ -0,0 +1,5 @@
+---
+"@spree/cli": minor
+---
+
+`spree dev` now opens the Admin Dashboard in the browser once it is ready. Pass `--no-open` to skip it.
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index 003e42c40f..8c2cf885a4 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -52,10 +52,11 @@ spree init --no-open # Skip opening browser
### `spree dev`
-Run the app in the foreground — streams web + worker logs; `Ctrl+C` stops them. The databases keep running for a fast next boot (`spree stop` shuts everything down).
+Run the app in the foreground — streams web + worker logs; `Ctrl+C` stops them. The databases keep running for a fast next boot (`spree stop` shuts everything down). The Admin Dashboard opens in your browser as soon as it is ready.
```bash
spree dev
+spree dev --no-open # Skip opening browser
```
### `spree stop`
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 970352402a..8184d6bceb 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -15,7 +15,7 @@ Run from your Spree project directory:
| Command | Description |
|---------|-------------|
-| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the Admin Dashboard dev server when `apps/dashboard` exists |
+| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the Admin Dashboard dev server when `apps/dashboard` exists and opens the dashboard in the browser once it is ready (`--no-open` skips it) |
| `spree stop` | Stop backend services |
| `spree upgrade` | Upgrade Spree — the server (image or gems), `@spree/*` packages, migrations and data backfills |
| `spree eject` | Switch from the prebuilt image to building from `backend/` |
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
index 7b0a5cb3e2..47ce91cb2b 100644
--- a/packages/cli/src/commands/dev.ts
+++ b/packages/cli/src/commands/dev.ts
@@ -18,7 +18,7 @@ import {
} from '../dashboard-server.js'
import { appServices, dockerCompose, hasProjectContainers, primeBundleVolume } from '../docker.js'
import { ensureDashboardDevEnv } from './add.js'
-import { runFirstRunSetup } from './init.js'
+import { openBrowser, runFirstRunSetup, waitForHealthy } from './init.js'
export function registerDevCommand(program: Command): void {
program
@@ -26,7 +26,8 @@ export function registerDevCommand(program: Command): void {
.description(
'Run the app in the foreground — the API, plus the Admin Dashboard dev server when apps/dashboard exists; Ctrl+C stops them',
)
- .action(async () => {
+ .option('--no-open', 'skip opening the dashboard in the browser once it is ready')
+ .action(async (flags: { open: boolean }) => {
const ctx = detectProject()
if (hasMonorepoSpreePath(ctx.projectDir)) {
@@ -79,7 +80,7 @@ export function registerDevCommand(program: Command): void {
}
if (neverSetUp) {
p.log.info('First run detected — completing setup automatically.')
- await runFirstRunSetup({ sampleData: true, open: true })
+ await runFirstRunSetup({ sampleData: true, open: flags.open })
return
}
}
@@ -128,6 +129,7 @@ export function registerDevCommand(program: Command): void {
process.on('SIGINT', ignoreSigint)
let result: { exitCode?: number }
let dashboard: ReturnType<typeof startDashboardDevServer> = null
+ const stopWaiting = new AbortController()
try {
// Prime the shared bundle_cache volume with web alone first so the
// foreground `up web worker` below doesn't race the cold-volume
@@ -145,6 +147,10 @@ export function registerDevCommand(program: Command): void {
// the finally covers non-signal exits.
dashboard = withDashboard ? startDashboardDevServer(ctx.projectDir) : null
+ if (flags.open) {
+ void openDashboardWhenReady(ctx.port, dashboard, stopWaiting.signal)
+ }
+
result = await dockerCompose(
['up', ...(await appServices(ctx.projectDir))],
ctx.projectDir,
@@ -154,6 +160,7 @@ export function registerDevCommand(program: Command): void {
},
)
} finally {
+ stopWaiting.abort()
dashboard?.stop()
process.off('SIGINT', ignoreSigint)
}
@@ -173,6 +180,29 @@ export function registerDevCommand(program: Command): void {
})
}
+/**
+ * Opens the dashboard once the API answers its health check — the dashboard
+ * is unusable before then — and, with a dashboard app, once Vite reports its
+ * URL. Runs alongside the foreground stack; a stack that stops first, an
+ * API that never becomes healthy, or a dashboard that never reports ready
+ * leaves the browser alone.
+ */
+async function openDashboardWhenReady(
+ port: number,
+ dashboard: ReturnType<typeof startDashboardDevServer>,
+ signal: AbortSignal,
+): Promise<void> {
+ try {
+ await waitForHealthy(port, signal)
+ } catch {
+ return
+ }
+ const url = dashboard ? await dashboard.url : `http://localhost:${port}/dashboard`
+ if (!url || signal.aborted) return
+
+ await openBrowser(url)
+}
+
/**
* Admin sign-in lines for the summary card. An admin only exists if `init`
* seeded one; otherwise the account is created through first-run setup, so
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 2510a87ed6..a2dfc7bf4c 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -1,6 +1,7 @@
import fs from 'node:fs'
import { platform } from 'node:os'
import path from 'node:path'
+import { setTimeout as sleep } from 'node:timers/promises'
import * as p from '@clack/prompts'
import type { Command } from 'commander'
import { execa, execaCommand } from 'execa'
@@ -256,7 +257,9 @@ export async function runFirstRunSetup(flags: {
// With the dashboard, wait for Vite to report ready (it auto-bumps the
// port when 5173 is taken) so the browser opens the real URL. Without
// one, open the built-in dashboard the summary names.
- const dashboardUrl = dashboard ? await dashboard.url : setupBase
+ const dashboardUrl = dashboard
+ ? ((await dashboard.url) ?? `http://localhost:${DASHBOARD_PORT}`)
+ : setupBase
// No admin was seeded, so the dashboard would only show a login form
// nobody can pass — open first-run setup instead and land the operator
// on the account form directly.
@@ -296,18 +299,19 @@ async function installAppDeps(projectDir: string, app: string): Promise<void> {
}
}
-async function waitForHealthy(port: number): Promise<void> {
+export async function waitForHealthy(port: number, signal?: AbortSignal): Promise<void> {
const url = `http://localhost:${port}/up`
const start = Date.now()
while (Date.now() - start < HEALTH_CHECK_TIMEOUT_MS) {
+ signal?.throwIfAborted()
try {
- const res = await fetch(url)
+ const res = await fetch(url, { signal })
if (res.ok) return
} catch {
// not ready yet
}
- await new Promise((resolve) => setTimeout(resolve, HEALTH_CHECK_INTERVAL_MS))
+ await sleep(HEALTH_CHECK_INTERVAL_MS, undefined, { signal })
}
throw new Error(`Spree did not become healthy within ${HEALTH_CHECK_TIMEOUT_MS / 1000}s`)
@@ -394,7 +398,7 @@ function resolveAdminCredentials(flags: { adminEmail?: string; adminPassword?: s
return { adminEmail, adminPassword }
}
-async function openBrowser(url: string): Promise<void> {
+export async function openBrowser(url: string): Promise<void> {
const os = platform()
const cmd = os === 'darwin' ? 'open' : os === 'win32' ? 'start' : 'xdg-open'
diff --git a/packages/cli/src/dashboard-server.ts b/packages/cli/src/dashboard-server.ts
index 63c35340ec..fa3aa892d0 100644
--- a/packages/cli/src/dashboard-server.ts
+++ b/packages/cli/src/dashboard-server.ts
@@ -4,7 +4,6 @@ import path from 'node:path'
import * as p from '@clack/prompts'
import pc from 'picocolors'
import { detectPackageManager } from './commands/add.js'
-import { DASHBOARD_PORT } from './constants.js'
export function hasDashboardApp(projectDir: string): boolean {
return fs.existsSync(path.join(projectDir, 'apps', 'dashboard', 'package.json'))
@@ -35,10 +34,10 @@ export function warnDashboardNotRunnable(projectDir: string): void {
export interface DashboardDevServer {
/**
* The URL Vite actually reports once ready (it auto-bumps the port when
- * 5173 is taken). Always settles — falls back to the default URL on
- * timeout, spawn failure, early exit, or stop().
+ * 5173 is taken). Always settles — null when readiness was never
+ * confirmed: timeout, spawn failure, early exit, or stop().
*/
- url: Promise<string>
+ url: Promise<string | null>
stop: () => void
}
@@ -74,20 +73,19 @@ export function startDashboardDevServer(projectDir: string): DashboardDevServer
shell: windows,
})
- const fallbackUrl = `http://localhost:${DASHBOARD_PORT}`
let settled = false
- let resolveUrl: (url: string) => void = () => {}
- const url = new Promise<string>((resolve) => {
+ let resolveUrl: (url: string | null) => void = () => {}
+ const url = new Promise<string | null>((resolve) => {
resolveUrl = resolve
})
- const settle = (value: string) => {
+ const settle = (value: string | null) => {
settled = true
clearTimeout(fallback)
resolveUrl(value)
}
// Vite is normally ready in well under a second; a generous fallback keeps
// `--open` from hanging if its output format ever changes.
- const fallback = setTimeout(() => settle(fallbackUrl), 30_000)
+ const fallback = setTimeout(() => settle(null), 30_000)
fallback.unref()
const forward = (stream: NodeJS.ReadableStream, out: NodeJS.WriteStream) => {
@@ -113,7 +111,7 @@ export function startDashboardDevServer(projectDir: string): DashboardDevServer
// A spawn failure (missing binary, PATH issues) emits 'error' — unhandled
// it would crash the CLI, the opposite of crash isolation.
child.on('error', (error) => {
- settle(fallbackUrl)
+ settle(null)
p.log.warn(
`Could not start the dashboard dev server (${error.message}) — start it manually with ` +
`${pc.bold(`cd apps/dashboard && ${pm} run dev`)}. The API keeps running.`,
@@ -121,7 +119,7 @@ export function startDashboardDevServer(projectDir: string): DashboardDevServer
})
child.on('exit', (code, signal) => {
- settle(fallbackUrl)
+ settle(null)
// Only a genuine crash warns: not our stop(), and not a signal exit —
// Ctrl+C reaches the child before stop() runs, as SIGINT (signal) or a
// 130 exit code depending on the package manager.
@@ -137,7 +135,7 @@ export function startDashboardDevServer(projectDir: string): DashboardDevServer
url,
stop: () => {
stopping = true
- settle(fallbackUrl)
+ settle(null)
if (child.exitCode !== null || child.killed) return
if (!windows && child.pid) {
// Signal the whole process group so Vite goes down with its wrapper.