Bun.serve(): uWebSockets C++ Engine & Zero-Copy HTTP Routing
- Last updated
- Prerequisites:
- Node.js `http.createServer`
- Fetch API `Request`/`Response`
- bun
- http-server
- bun-serve
- uwebsockets
- networking
- performance
Read at your depth
The practical view
`Bun.serve()` is Bun's built-in HTTP and WebSocket server: `Bun.serve({ port: 3000, fetch(req) { return new Response('Hello'); } })`. It uses standard Web `Request` and `Response` objects. It includes built-in static file routing, TLS/HTTPS support, Server-Sent Events (SSE), and native WebSocket handling with zero npm dependencies.
The same idea in other frameworks
`http.createServer((req, res) => res.end('Hello')).listen(3000);``Deno.serve({ port: 3000 }, (req) => new Response('Hello'));``Bun.serve({ port: 3000, fetch(req) { return new Response('Hello'); } });``http.HandleFunc("/", handler); http.ListenAndServe(":3000", nil)`Legacy vs modern
Node.js http.createServer vs Bun.serve Native Server
Node requires manual stream and socket wrapping; `Bun.serve` uses Web Standards with high-performance C++ networking.
http.createServer((req, res) => { res.writeHead(200); res.end('OK'); }).listen(3000); // ❌ Node stream APIBun.serve({ port: 3000, fetch(req) { return Response.json({ status: 'healthy' }); } }); // ✅ NEWInterview gotchas
Context
Interviewers test your knowledge of Bun's native WebSocket server integration.
The mechanical answer
`Bun.serve()` includes built-in WebSocket support using the `websocket` configuration object: `Bun.serve({ fetch(req, server) { if (server.upgrade(req)) return; return new Response('HTTP'); }, websocket: { open(ws) {}, message(ws, msg) {}, close(ws) {} } })`. The upgrade from HTTP to WebSocket happens in native C++ with zero npm dependencies.
Trap
You do not need to install `npm install ws` in Bun; use `server.upgrade(req)` directly.
Context
Checks knowledge of zero-copy static asset serving.
The mechanical answer
Yes. If `fetch()` returns a `new Response(Bun.file('public/index.html'))`, Bun detects the `BunFile` and uses OS `sendfile` syscalls to pipe the file directly from disk into the TCP socket, bypassing JavaScript memory allocation.
Trap
Do not read the file into a string with `await file.text()` before returning it; returning `new Response(Bun.file(...))` directly is required for zero-copy.