{"id":"5207af9be95e6319","repo":"evanw/esbuild","slug":"cannot-use-the-serve-api-in-this-environment","errorCode":null,"errorMessage":"Cannot use the \"serve\" API in this environment","messagePattern":"Cannot use the \"serve\" API in this environment","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"lib/shared/common.ts","lineNumber":1080,"sourceCode":"\n        watch: (options = {}) => new Promise((resolve, reject) => {\n          if (!streamIn.hasFS) throw new Error(`Cannot use the \"watch\" API in this environment`)\n          const keys: OptionKeys = {}\n          const delay = getFlag(options, keys, 'delay', mustBeInteger)\n          checkForInvalidFlags(options, keys, `in watch() call`)\n          const request: protocol.WatchRequest = {\n            command: 'watch',\n            key: buildKey,\n          }\n          if (delay) request.delay = delay\n          sendRequest<protocol.WatchRequest, null>(refs, request, error => {\n            if (error) reject(new Error(error))\n            else resolve(undefined)\n          })\n        }),\n\n        serve: (options = {}) => new Promise((resolve, reject) => {\n          if (!streamIn.hasFS) throw new Error(`Cannot use the \"serve\" API in this environment`)\n          const keys: OptionKeys = {}\n          const port = getFlag(options, keys, 'port', mustBeValidPortNumber)\n          const host = getFlag(options, keys, 'host', mustBeString)\n          const servedir = getFlag(options, keys, 'servedir', mustBeString)\n          const keyfile = getFlag(options, keys, 'keyfile', mustBeString)\n          const certfile = getFlag(options, keys, 'certfile', mustBeString)\n          const fallback = getFlag(options, keys, 'fallback', mustBeString)\n          const cors = getFlag(options, keys, 'cors', mustBeObject)\n          const onRequest = getFlag(options, keys, 'onRequest', mustBeFunction)\n          checkForInvalidFlags(options, keys, `in serve() call`)\n\n          const request: protocol.ServeRequest = {\n            command: 'serve',\n            key: buildKey,\n            onRequest: !!onRequest,\n          }\n          if (port !== void 0) request.port = port\n          if (host !== void 0) request.host = host","sourceCodeStart":1062,"sourceCodeEnd":1098,"githubUrl":"https://github.com/evanw/esbuild/blob/6ff1d8b0d8c134e867a397eef39702a223ebef9e/lib/shared/common.ts#L1062-L1098","documentation":"serve() spins up an HTTP server inside esbuild's native binary that serves built output and (optionally) a static servedir. Like watch(), it depends on the Go binary binding to a network socket and a filesystem; in browser/wasm builds (hasFS:false) the guard at lib/shared/common.ts:1080 throws. The wasm runtime has no socket layer to bind.","triggerScenarios":"Calling ctx.serve({ port: 8000, servedir: '.' }) on a context from esbuild-wasm or the browser entrypoint. Calling serve() in Deno wasm mode.","commonSituations":"Building an in-browser IDE and wanting a 'preview server'. Migrating a Node dev-server script that mixed build + serve into a worker. Trying to serve files from inside a sandboxed edge function.","solutions":["Run serve() under the Node or Deno native entry (hasFS:true).","In the browser, serve output yourself by reading result.outputFiles and feeding them to your own HTTP layer, or skip the dev-server pattern.","If you only need to inspect output, drop serve() and use build({ write:false }) then read outputFiles."],"exampleFix":"// before (browser wasm)\nconst ctx = await esbuild.context({ entryPoints: ['app.ts'] });\nawait ctx.serve({ servedir: '.', port: 8000 });\n// after — run under node, or fetch output manually\nconst res = await esbuild.build({ entryPoints: ['app.ts'], write: false });\nserveMyself(res.outputFiles); // your own server","handlingStrategy":"validation","validationCode":"const hasFS = typeof process !== 'undefined' && !!process.versions?.node;\nif (hasFS) {\n  await ctx.serve({ port: 8000, servedir: '.' });\n} else {\n  throw new Error('serve() not available in this environment; use Node');\n}","typeGuard":"function canServe(): boolean {\n  return typeof process !== 'undefined' && typeof process.versions?.node === 'string';\n}","tryCatchPattern":"try {\n  await ctx.serve(opts);\n} catch (e) {\n  if (/Cannot use the \"serve\" API/.test(e.message)) {\n    // fall back to reading outputFiles and serving yourself\n  } else throw e;\n}","preventionTips":["Reserve serve() for the Node/Deno native entry.","In browser bundlers, expose outputFiles via your own HTTP layer.","Annotate shared configs with the host they target."],"tags":["environment","serve","filesystem","wasm"],"analyzedSha":"6ff1d8b0d8c134e867a397eef39702a223ebef9e","analyzedAt":"2026-08-03T19:42:38.433Z","schemaVersion":2}