Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท HTTP Servers and APIs

Your First Server with Bun.serve

Start an HTTP server with Bun.serve: the fetch handler, Request and Response, ports, hostname, error handling, server.stop and hot reload, with runnable Node stand-ins.

Bun ships an HTTP server in its standard library. You do not install Express or Fastify to answer a request: you call Bun.serve() and give it a function. That function receives a standard web Request and returns a standard web Response, the same objects you already know from the browser's fetch(). Anything you learn here also applies to Deno, Cloudflare Workers and Node's built-in fetch.

Bun is not available on this site's runners. The Bun code in this lesson is read-only. Where a result matters, we give you a small Node 24 stand-in that exposes a serve() function with the same shape, so you can run and change the handler code. It is labelled every time and is not Bun itself.

The smallest server

TypeScript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello from Bun!");
  },
});

console.log(`Listening on ${server.url}`);

Run it with bun run server.ts (or bun server.ts) and open http://localhost:3000. The process stays alive because a listening socket keeps the event loop busy. Three things to notice:

  • fetch is called once per HTTP request. It may be async, and it may return a Response or a promise for one.
  • Bun.serve() returns a Server object. server.url is a URL, server.port the real port and server.hostname the address.
  • There is no listen() call: the server starts as soon as Bun.serve() returns.

Port and hostname

If you leave port out, Bun checks the BUN_PORT, PORT and NODE_PORT environment variables and falls back to 3000. Pass port: 0 to let the operating system pick a free port, which is ideal for tests. The default hostname listens on all interfaces; pass hostname: "127.0.0.1" to accept local connections only.

TypeScript
const server = Bun.serve({
  port: Number(Bun.env.PORT ?? 8080),
  hostname: "127.0.0.1",
  fetch: () => new Response("ok"),
});

Reading the request

req is a normal Request. Parse the URL with new URL(req.url) to get the path and query string, and read req.method and req.headers for the rest:

TypeScript
Bun.serve({
  fetch(req) {
    const url = new URL(req.url);
    if (url.pathname === "/hello") {
      const name = url.searchParams.get("name") ?? "world";
      return new Response(`Hello, ${name}!`);
    }
    if (url.pathname === "/ping") {
      return Response.json({ pong: true, method: req.method });
    }
    return new Response("Not found", { status: 404 });
  },
});

Response.json(data) serializes the data and sets Content-Type: application/json. A new Response(body, { status, headers }) gives full control. Bun adds Content-Length, Date and similar headers for you.

Try the handler style

The stand-in below runs the same kind of fetch handler on Node's http module. It is not Bun: it is a 15-line adapter that turns an incoming Node request into a web Request, calls your function and sends the Response back. Change the handler and re-run.

Node.js A fetch handler on Node (stand-in for Bun.serve)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Errors in a handler

If your handler throws, Bun answers 500 Internal Server Error and, in development mode, shows an error page with the stack. Add an error handler to produce your own response and to log the problem:

TypeScript
Bun.serve({
  fetch(req) {
    throw new Error("boom");
  },
  error(err) {
    console.error(err);
    return new Response("Something went wrong", { status: 500 });
  },
});

The development option defaults to true unless NODE_ENV is production. In production never send stack traces to the client.

Node.js Catching handler errors (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stopping and reloading

server.stop() stops accepting new connections and waits for running requests; server.stop(true) closes active connections immediately. For development, bun --hot server.ts reloads your code without restarting the process: Bun keeps the same server and swaps the fetch function, so open sockets survive. bun --watch restarts the whole process on every change. Prefer --hot for servers.

You can also use the module-default style, which Bun recognizes when a file's default export has a fetch method:

TypeScript
export default {
  port: 3000,
  fetch(req: Request) {
    return new Response("default export server");
  },
};

The next lessons build on this: routes and parameters replace the if chain, and request bodies show how to read JSON and forms.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the function passed as fetch to Bun.serve receive and return?

    Bun.serve uses the standard web Request and Response classes, the same ones used by the browser's fetch API.
  2. 2. Which port value asks the operating system for any free port?

    Port 0 means pick any free port. Read the actual number from server.port.
  3. 3. Which development flag keeps the same server and swaps your code without restarting the process?

    --hot reloads modules in place and keeps the process (and sockets) alive; --watch restarts the whole process.
  4. 4. What happens if the fetch handler throws and there is no error handler?

    Bun turns an uncaught error in the handler into a 500 response. An error handler lets you control that response.

Summary

  • Bun.serve({ fetch }) starts a server immediately; fetch(req) returns a Response.
  • Port defaults to PORT/BUN_PORT or 3000; port: 0 picks a free one; read server.url.
  • Use new URL(req.url) for path and query, Response.json() for JSON.
  • Add an error handler to control 500 responses.
  • bun --hot reloads code without dropping the server; server.stop() shuts it down.

Next: Routes, Parameters and Method Handlers