Bun.serve example: a hello world HTTP server
Bun.serve starts an HTTP server. This one answers every request with the same text. Press Run: the server starts in this page, in your browser, and the preview shows its answer.
const server = Bun.serve({
port: 3000,
fetch(req) {
const { pathname } = new URL(req.url);
return new Response(`Hello from Bun.serve! You asked for ${pathname}`);
},
});
console.log(`Listening on ${server.url}`);How it works
Section titled “How it works”fetch(req)runs for every request. It gets a standardRequestand returns aResponse, the same classes as the browser’sfetch, so nothing here is Bun-specific exceptBun.serveitself.portdefaults to 3000 (or thePORTenvironment variable), so you can leave it out.server.urlis the address the server listens on, handy for logging.
Change the path in the preview’s request bar, say to /about, and press Send: the handler reads it from req.url.
Run it locally
Section titled “Run it locally”Save the code as index.ts and run it with Bun:
bun index.tscurl http://localhost:3000/hellobun --hot index.ts reloads the handler when you save, without dropping the server.
In the playground
Section titled “In the playground”The playground runs Bun.serve in your browser: a service worker hands the preview’s requests to your server, so nothing goes over the network. For routing, see routes and a JSON API; everything Bun.serve supports here is listed under Bun APIs.
Was this page helpful?
Sends the rating and this page's address; nothing else unless you write it. Privacy
runbun is an independent project, not affiliated with or endorsed by Oven or Bun.