Build a local HTTP API with Bun.serve: routes, methods, and 404 handling
Start Bun’s HTTP server with Bun.serve. Bun 1.2.3 and later support a routes table for fixed paths, parameters, and method-specific handlers; unmatched requests can go to fetch. This example is a local JSON API bound only to 127.0.0.1, not a public deployment recipe. Official docs checked 2026-11-20.
Start Bun’s HTTP server with Bun.serve. Bun 1.2.3 and later support a routes table for fixed paths, parameters, and method-specific handlers; unmatched requests can go to fetch. This example is a local JSON API bound only to 127.0.0.1, not a public deployment recipe. Official docs checked 2026-11-20.
Check the version
Assume Bun is installed. Route tables require Bun 1.2.3 or later:
bun --versionFor an older release, update Bun or use the fetch-only pattern supported by that version. Follow the official installation guidance for your operating system.
Define routes and handlers
Save as server.ts:
const server = Bun.serve({
hostname: "127.0.0.1",
port: 3000,
routes: {
"/health": () => Response.json({ ok: true }),
"/users/:id": {
GET: req => Response.json({ id: req.params.id }),
},
"/api/echo": {
POST: async req => {
const body = await req.json();
return Response.json({ received: body });
},
},
},
fetch(_req) {
return Response.json({ error: "Not found" }, { status: 404 });
},
});
console.log(`Listening on ${server.url}`);The health endpoint returns fixed JSON. The parameter route extracts id from the URL. The POST handler parses JSON and returns it. Handlers return a Response or Promise. fetch is the fallback for requests that do not match a declared route. Bun prioritizes exact paths, then parameter routes, then wildcards; check overlaps.
Bun documents 0.0.0.0 as the default hostname. This example explicitly uses 127.0.0.1 for local access. If you bind to other interfaces, review firewall, authentication, TLS, input validation, and exposure before deployment.
Run and check responses
bun run server.tsThe terminal should print an address similar to http://127.0.0.1:3000/. In another PowerShell terminal:
Invoke-RestMethod http://127.0.0.1:3000/health
Invoke-RestMethod http://127.0.0.1:3000/users/42
Invoke-RestMethod http://127.0.0.1:3000/api/echo -Method Post -ContentType application/json -Body '{"message":"hello"}'
Invoke-WebRequest http://127.0.0.1:3000/missingExpected bodies are { "ok": true }, { "id": "42" }, and { "received": { "message": "hello" } }. The last request returns 404 with the not-found JSON. Check both status and body. Stop the server with Ctrl+C.
Troubleshooting and next steps
If routes is rejected, check bun --version; the route table needs v1.2.3 or later.
If the port is busy, stop the process using 3000 or choose another port, then verify the printed URL.
If you get an unexpected 404, check path spelling, slashes, parameter names, and HTTP method. Unmatched requests use fetch.
If JSON parsing fails, send valid JSON with Content-Type: application/json. Validate input and return an appropriate 4xx response in production.
This is a routing example only. Design authentication, authorization, request limits, CORS, logging, error contracts, TLS, proxying, and graceful shutdown for the service. Some Bun transport protocols are marked experimental in the official docs; verify their status before relying on them.
References
[Bun HTTP server](https://bun.sh/docs/runtime/http/server)
[Bun routing](https://bun.sh/docs/runtime/http/routing)
[Common HTTP server usage](https://bun.sh/guides/http/server)
[Bun v1.4.1 release notes](https://bun.sh/blog/release-notes/bun-v1.4.1)