{"record":{"id":"72a11700a444605e","repo":"mastra-ai/mastra","slug":"server-failed-to-start-with-error-currentserver","errorCode":null,"errorMessage":"Server failed to start with error: ${currentServerProcess.stderr || currentServerProcess.stdout}","messagePattern":"Server failed to start with error: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/cli/src/commands/dev/dev.ts","lineNumber":187,"sourceCode":"        ...(getAnalytics()?.getDistinctId() ? { MASTRA_CLI_DISTINCT_ID: getAnalytics()!.getDistinctId() } : {}),\n        ...(startOptions?.https\n          ? {\n              MASTRA_HTTPS_KEY: startOptions.https.key.toString('base64'),\n              MASTRA_HTTPS_CERT: startOptions.https.cert.toString('base64'),\n            }\n          : {}),\n        ...(startOptions.factory ? { MASTRA_FACTORY_DEV: 'true' } : {}),\n        ...(factoryUiDist ? { MASTRACODE_UI_DIST: factoryUiDist } : {}),\n      },\n      stdio: ['inherit', 'pipe', 'pipe', 'ipc'],\n      reject: false,\n    }) as any as ChildProcess;\n\n    if (currentServerProcess?.exitCode && currentServerProcess?.exitCode !== 0) {\n      if (!currentServerProcess) {\n        throw new Error(`Server failed to start`);\n      }\n      throw new Error(\n        `Server failed to start with error: ${currentServerProcess.stderr || currentServerProcess.stdout}`,\n      );\n    }\n\n    // Filter server output to remove Studio message\n    if (currentServerProcess.stdout) {\n      currentServerProcess.stdout.on('data', (data: Buffer) => {\n        const output = data.toString();\n        if (!output.includes('Studio available') && !output.includes('👨‍💻') && !output.includes('Mastra API running')) {\n          process.stdout.write(output);\n        }\n      });\n    }\n\n    if (currentServerProcess.stderr) {\n      currentServerProcess.stderr.on('data', (data: Buffer) => {\n        const output = data.toString();\n        if (!output.includes('Studio available') && !output.includes('👨‍💻') && !output.includes('Mastra API running')) {","sourceCodeStart":169,"sourceCodeEnd":205,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/cli/src/commands/dev/dev.ts#L169-L205","documentation":"This error is thrown by the `mastra dev` CLI command when the spawned Hono dev server child process exits with a non-zero code before or during startup. The CLI surfaces the child process's stderr (falling back to stdout) in the message so the underlying server crash reason is visible. It is a wrapper error: the real cause is whatever the embedded server printed.","triggerScenarios":"Running `mastra dev` where the server child process sets exitCode !== 0; typically the bundled server fails at import time (bad mastra instance, TS compile/bundler error, port binding failure, broken tool/agent imports) and dies immediately.","commonSituations":"A syntax or import error in src/mastra files that bundling didn't catch; another process already listening on the port; an invalid DATABASE_URL or storage config throwing at module init; incompatible env vars expected by the server; a plugin/custom registerApiRoute throwing during bootstrap.","solutions":["Read the stderr text appended after 'Server failed to start with error:' — it contains the actual server-side exception and fix that first","Check that nothing else occupies the dev port and adjust PORT if needed","Run `mastra dev --debug` or build (`mastra build`) to surface bundler/import errors","Verify all mastra agents/tools/workflows construct successfully without network/DB dependencies failing at import time","Update @mastra/* packages to aligned versions — mismatched core/cli versions can crash the server at boot"],"exampleFix":"// before: server crashes on startup because env var is missing\nconst store = new PostgresStore({ connectionString: process.env.DATABASE_URL! });\n// after: fail fast with a clear message before the server boots\nconst connectionString = process.env.DATABASE_URL;\nif (!connectionString) throw new Error('DATABASE_URL is required to run mastra dev');\nconst store = new PostgresStore({ connectionString });","handlingStrategy":"try-catch","validationCode":"import { spawnSync } from 'node:child_process';\nconst port = Number(process.env.PORT ?? 4111);\nconst probe = spawnSync('node', ['-e', `require('net').createConnection(${port}).on('connect',()=>{console.error('in-use');process.exit(1)}).on('error',()=>process.exit(0))`]);\nif (probe.status === 1) throw new Error(`Port ${port} already in use; free it or set PORT before running mastra dev`);\nif (!process.env.DATABASE_URL) throw new Error('DATABASE_URL must be set before mastra dev');","typeGuard":"function hasStartupError(p: { exitCode: number | null } | null): p is { exitCode: number } & { stderr: string | null; stdout: string | null } {\n  return p !== null && typeof p.exitCode === 'number' && p.exitCode !== 0;\n}","tryCatchPattern":"try {\n  await dev({ port });\n} catch (err) {\n  const msg = err instanceof Error ? err.message : String(err);\n  const serverOutput = msg.replace('Server failed to start with error: ', '');\n  console.error('Dev server failed to boot. Server output:\\n' + serverOutput);\n  process.exitCode = 1;\n}","preventionTips":["Always read the stderr tail included in the error message before changing code","Keep mastra core/cli/deps versions aligned and run updates together","Ensure all module-level side effects (DB, storage, API clients) tolerate missing env or defer lazily","Check port availability / set PORT before launching in shared dev environments","Run `mastra build` in CI to catch bundling/import errors that crash the dev server"],"tags":["cli","dev-server","process-exit","startup"],"backgroundTag":"server-failed-to-start","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}