日本語

How to Run a Small Web Server with Bun.serve

​​Bun​HTTP,TypeScript

With Bun.serve in Bun, you can start an HTTP server from a single TypeScript file without installing packages like Express. Per-path handling goes in routes, and you can also split handling by URL parts (such as :id) and by method (GET, POST) there.

This is useful when you want a quick small API server for testing, or a mock server for frontend development. This article uses an API for reading and writing memos as an example, and shows the code along with the responses it actually returned.

Note

The test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. I sent requests with curl 8.5.0. I did not test HTTPS (tls), WebSocket, HTTP/2 or HTTP/3, HTML imports, Windows, or macOS. I checked the official documentation against the source files at the tag used for testing (bun-v1.4.4) on GitHub, and the links point there.

Writing a memo API in a single file

The following server.ts is the entire server for this article. The memos are kept in an in-memory array, so they are lost when the server stops.

ts
type Memo = { id: number; text: string };
const memos: Memo[] = [{ id: 1, text: "牛乳を買う" }];

const server = Bun.serve({
  routes: {
    // If you only need to return fixed content, you can put a Response object directly here
    "/health": new Response("OK"),

    // Read the :id part with req.params.id
    "/hello/:name": (req) => new Response(`こんにちは、${req.params.name}さん\n`),

    // Split handling by method
    "/api/memos": {
      GET: () => Response.json(memos),
      POST: async (req) => {
        const body = (await req.json()) as { text?: string };
        if (!body.text) {
          return Response.json({ error: "text は必須です" }, { status: 400 });
        }
        const memo = { id: memos.length + 1, text: body.text };
        memos.push(memo);
        return Response.json(memo, { status: 201 });
      },
    },

    "/api/memos/:id": (req) => {
      const memo = memos.find((m) => m.id === Number(req.params.id));
      if (!memo) return Response.json({ error: "見つかりません" }, { status: 404 });
      return Response.json(memo);
    },
  },

  // Requests that match no route
  fetch() {
    return new Response("Not Found\n", { status: 404 });
  },
});

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

The three forms you will most often use for a routes value are: a Response object itself, a function that takes a Request and returns a Response, and a set of functions keyed by GET, POST, and so on (Server page in the official documentation). The returned value is a standard Web Response, so you can create JSON with Response.json(). Note that routes is an option available from Bun 1.2.3. Earlier versions require fetch.

When I started it with bun server.ts, the following single line was printed. If you don't specify a port, it listens on port 3000.

text
listening on http://localhost:3000/

Reading and writing with curl

First, /health, which returns a Response object as is. The headers show that an etag was added automatically.

text
$ curl -i http://localhost:3000/health
HTTP/1.1 200 OK
Content-Type: text/plain;charset=utf-8
etag: "5afa14a82295204f"
Date: Sat, 14 Nov 2026 08:13:30 GMT
Content-Length: 2

OK

A route that holds a fixed Response keeps returning the content it had when the server started. To change the content, call server.reload() (Routing page in the official documentation).

In /hello/:name, the :name part of the URL is stored in req.params.name. Even when Japanese text is sent percent-encoded, it was received as the decoded string.

text
$ curl http://localhost:3000/hello/neko
こんにちは、nekoさん

$ curl http://localhost:3000/hello/%E3%81%AD%E3%81%93
こんにちは、ねこさん

These are the results of sending GET and POST to /api/memos. When returned with Response.json(), Content-Type was application/json;charset=utf-8.

text
$ curl -i http://localhost:3000/api/memos
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Date: Sat, 14 Nov 2026 08:13:30 GMT
Content-Length: 35

[{"id":1,"text":"牛乳を買う"}]
$ curl -i -X POST -H "Content-Type: application/json" -d '{"text":"猫の爪を切る"}' http://localhost:3000/api/memos
HTTP/1.1 201 Created
Content-Type: application/json;charset=utf-8
Date: Sat, 14 Nov 2026 08:13:30 GMT
Content-Length: 36

{"id":2,"text":"猫の爪を切る"}

When I POSTed JSON without text, the server returned 400, as the code specifies. The added memo can be retrieved both from the list and by ID.

text
$ curl -i -X POST -H "Content-Type: application/json" -d '{}' http://localhost:3000/api/memos
HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=utf-8
Date: Sat, 14 Nov 2026 08:13:30 GMT
Content-Length: 32

{"error":"text は必須です"}
$ curl http://localhost:3000/api/memos
[{"id":1,"text":"牛乳を買う"},{"id":2,"text":"猫の爪を切る"}]
$ curl http://localhost:3000/api/memos/2
{"id":2,"text":"猫の爪を切る"}

Methods without a handler fall through to fetch

/api/memos only has GET and POST. When I sent DELETE to it, the server did not return 405 (Method Not Allowed). It returned the 404 written in fetch. This is the same response as /nothing, which matches no path.

text
$ curl -i -X DELETE http://localhost:3000/api/memos
HTTP/1.1 404 Not Found
content-type: text/plain;charset=utf-8
Date: Sat, 14 Nov 2026 08:13:30 GMT
Content-Length: 10

Not Found

I also tested a server with only routes and no fetch (where /api/memos has only GET). In this case, both DELETE and /nothing returned a 404 with an empty body.

text
$ curl -i -X DELETE http://localhost:3000/api/memos
HTTP/1.1 404 Not Found
Date: Sat, 14 Nov 2026 08:13:31 GMT
Content-Length: 0

If you want to tell API users that "this method is not allowed," you need to write that yourself, for example by adding a DELETE key that returns 405.

Routes are matched by specificity, not by the order written

Route patterns include fixed paths, parameterized paths like :id, and wildcards using *. According to the official documentation, the matching order is "fixed paths, then parameterized paths, then wildcards, then /*" (the section on route priority on the Routing page).

To check this, I prepared order.ts, with routes written deliberately from broadest to narrowest.

ts
const server = Bun.serve({
  routes: {
    "/*": () => new Response("/* に当たった\n"),
    "/api/*": () => new Response("/api/* に当たった\n"),
    "/api/users/:id": (req) => new Response(`/api/users/:id に当たった(id=${req.params.id})\n`),
    "/api/users/me": () => new Response("/api/users/me に当たった\n"),
  },
});
console.log(`listening on ${server.url}`);

These are the results when I sent requests to each path.

Requested path Matched route
/api/users/me /api/users/me
/api/users/42 /api/users/:id (id=42)
/api/users/42/posts /api/*
/api/other /api/*
/top /*

The /* written at the top never took over the other routes. A path that continues past :id, such as /api/users/42/posts, did not match /api/users/:id. It fell through to /api/*.

When an exception occurs, the default is a page with source code

The response to an exception thrown inside a handler changes greatly depending on the settings. I checked this with the following boom.ts.

ts
const server = Bun.serve({
  routes: {
    "/boom": () => {
      throw new Error("ここで失敗しました");
    },
  },
});
console.log(`listening on ${server.url} development=${server.development}`);

When I started it without any settings, it printed development=true. Bun.serve runs in development mode by default (Error handling page in the official documentation). In this mode, a request to /boom returned status 500 and 50,298 bytes of HTML. The page looks like this in a browser.

Bun's development-mode error page. It shows the error message, which is written in Japanese in the code and means "failed here", the file name and line number /boom.ts:4:17, and four lines of source code including the throw line
The page the browser receives when an exception occurs in development mode

The file name, line number, and source code up to the line that threw the exception are shown to the person who made the request, not just the error message. The HTML response also contained the path of the server's working directory.

Warning

Do not expose a server in development mode. In an environment that will be public, start it with NODE_ENV=production or set development: false. According to the official documentation, adding --production to bun run does not stop this page. That flag belongs to bun build and bun install, and bun run ignores it.

When I started the same file with NODE_ENV=production, it printed development=false, and the response contained only a short string.

text
$ curl -i http://localhost:3000/boom
HTTP/1.1 500 Internal Server Error
content-type: text/plain
Date: Sat, 14 Nov 2026 08:13:34 GMT
Content-Length: 21

Something went wrong!

If you want to decide the response content yourself, write an error handler. According to the explanation of the error handler in the official documentation, the Response returned by error is sent instead of the development-mode error page.

ts
const server = Bun.serve({
  routes: {
    "/boom": () => {
      throw new Error("ここで失敗しました");
    },
  },
  error(error) {
    console.error(`error handler: ${error.message}`);
    return Response.json({ error: "サーバーの中でエラーが起きました" }, { status: 500 });
  },
});
console.log(`listening on ${server.url} development=${server.development}`);

Even in development mode (development=true), the only thing returned was this JSON. The server log showed error handler: followed by the thrown message, which is the Japanese text meaning "failed here" from the code.

text
$ curl -i http://localhost:3000/boom
HTTP/1.1 500 Internal Server Error
Content-Type: application/json;charset=utf-8
Date: Sat, 14 Nov 2026 08:13:35 GMT
Content-Length: 60

{"error":"サーバーの中でエラーが起きました"}

In the first server.ts, when I POSTed broken JSON ({broken), req.json() threw a SyntaxError. The server returned status 500 with the development-mode error page HTML (49,995 bytes). When reading a request body, it is safer to wrap the code in try or handle the error in an error handler.

How the port is chosen, and how server.url behaves

default-port.ts is a file that starts the server without a port option and only prints the port number. When started as is, it used port 3000. With the environment variable PORT set, it used that number. According to the official documentation, the environment variables BUN_PORT, PORT, and NODE_PORT, as well as options like bun --port=4002, are also supported (the section on port configuration on the Server page).

text
$ bun default-port.ts
port=3000
$ PORT=8080 bun default-port.ts
port=8080

Specifying port: 0 picks an unused port. This is useful when starting a server in tests and you want to avoid port conflicts. When I started it twice, each run got a different number.

The following code prints the chosen port number and URL, and compares two ways of joining a path to server.url. APP_PORT is an environment variable I set up for this file.

ts
const server = Bun.serve({
  port: Number(process.env.APP_PORT ?? 3000),
  fetch: () => new Response("hi\n"),
});
console.log(`port=${server.port} url=${server.url}`);
console.log(`文字列でつなぐ: ${server.url}/users`);
console.log(`new URL で作る: ${new URL("/users", server.url)}`);
server.stop();
text
$ APP_PORT=0 bun port.ts
port=43339 url=http://localhost:43339/
文字列でつなぐ: http://localhost:43339//users
new URL で作る: http://localhost:43339/users
$ APP_PORT=0 bun port.ts
port=34541 url=http://localhost:34541/
文字列でつなぐ: http://localhost:34541//users
new URL で作る: http://localhost:34541/users

server.url is a URL that ends with /. If you join it with a template string, you get two slashes in a row. To add a path, write it like new URL("/users", server.url).

If another process is already using port 3000, the server fails at startup with an EADDRINUSE error and stops with exit code 1. (I replaced the path with /path/to/app.)

text
1 | const server = Bun.serve({
                       ^
error: Failed to start server. Is port 3000 in use?
 syscall: "listen",
   errno: 0,
    code: "EADDRINUSE"

      at /path/to/app/port.ts:1:20

Bun v1.4.4 (Linux x64)

Check whether an earlier server is still running, or restart with a different number by specifying PORT.

​Posted by 86