Skip to content
Run BunYour friendly Bun playground

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}`);
  • fetch(req) runs for every request. It gets a standard Request and returns a Response, the same classes as the browser’s fetch, so nothing here is Bun-specific except Bun.serve itself.
  • port defaults to 3000 (or the PORT environment variable), so you can leave it out.
  • server.url is 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.

Save the code as index.ts and run it with Bun:

Terminal window
bun index.ts
curl http://localhost:3000/hello

bun --hot index.ts reloads the handler when you save, without dropping the server.

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.