English

Bun.serveのroutesで、URLごとに処理を分ける方法

​​Bun​HTTP,TypeScript

Bun の Bun.serve では、routes に「URL のパス → 処理」の組を並べるだけで、URL ごとに処理を分けられます。Express のようなルーター用のパッケージを入れなくても、REST API のエンドポイントを /api/users や /api/users/:id のように書き分けられます。

ルートが増えてファイルを分けるときの書き方と、TypeScript での params の型の付け方から始めます。末尾のスラッシュ、大文字小文字、クエリ文字列がどのルートに当たるかは、curl で送った結果の表にまとめました。

補足

検証環境は Ubuntu 24.04(x86_64)、Bun 1.4.4、TypeScript 5.9.3(@types/bun 1.4.4)です。リクエストは curl 8.5.0 で送りました。ファイルを返すルート(Bun.file や { dir })、WebSocket、HTTPS、Windows と macOS は試していません。公式ドキュメントは、検証に使った版(タグ bun-v1.4.4)の元ファイルを GitHub で確認し、リンクもそこに張っています。

ルートを別のファイルに分けて、1つにまとめる

routes は普通のオブジェクトなので、ルートを別のファイルに書いておき、スプレッド構文(...)で取り込めます。まず、ユーザーに関するルートを routes/users.ts に分けました。

ts
import type { BunRequest } from "bun";

type User = { id: string; name: string };
const users: User[] = [{ id: "1", name: "たま" }];

// 別のファイルに分けたルート。req の型は BunRequest<"パス"> で書く
export const userRoutes = {
  "/api/users": {
    GET: () => Response.json(users),
    POST: async (req: BunRequest<"/api/users">) => {
      const { name } = (await req.json()) as { name: string };
      const user = { id: String(users.length + 1), name };
      users.push(user);
      return Response.json(user, { status: 201 });
    },
  },
  "/api/users/:id": {
    GET: (req: BunRequest<"/api/users/:id">) => {
      const user = users.find((u) => u.id === req.params.id);
      return user ? Response.json(user) : Response.json({ error: "not found" }, { status: 404 });
    },
  },
};

これを server.ts で取り込みます。ほかに、パラメーターが2つあるルート、* を使ったルート、クエリ文字列を読むルートも並べました。どのルートにも当たらなかったリクエストは fetch に回るので(公式ドキュメントにある fetch の説明)、そこで受け取ったパスを返すようにしています。

ts
import { userRoutes } from "./routes/users";

const server = Bun.serve({
  routes: {
    "/": new Response("トップページ\n"),

    // 別ファイルのルートを、スプレッド構文でまとめる
    ...userRoutes,

    // パラメーターは2つ以上でもよい
    "/orgs/:org/repos/:repo": (req) => Response.json(req.params),

    // * の部分は params に入らないので、URL から取り出す
    "/files/*": (req) => {
      const { pathname } = new URL(req.url);
      return Response.json({ rest: pathname.slice("/files/".length) });
    },

    // クエリ文字列は、ルートの決定には使われない
    "/search": (req) => {
      const q = new URL(req.url).searchParams.get("q");
      return Response.json({ q });
    },
  },

  fetch(req) {
    return new Response(`fetch に来た: ${new URL(req.url).pathname}\n`, { status: 404 });
  },
});

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

bun server.ts で起動して試すと、別ファイルのルートもそのまま動きました。POST で追加した「みけ」には、ID の 2 が付いています。

text
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/api/users'
[{"id":"1","name":"たま"}] [200]
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/api/users/1'
{"id":"1","name":"たま"} [200]
$ curl -s -X POST -d '{"name":"みけ"}' -w ' [%{http_code}]\n' http://localhost:3000/api/users
{"id":"2","name":"みけ"} [201]

curl の -w ' [%{http_code}]\n' は、本文のあとにステータスコードを表示させる指定です。

TypeScript で params に型を付ける

ルートのパスを Bun.serve の中に直接書いた場合は、TypeScript がパスの文字列から params の型を作ります(公式ドキュメントの、型付きのルートパラメーターの説明)。/orgs/:org/repos/:repo なら、req.params は { org: string; repo: string } です。

一方、さきほどのように別ファイルのオブジェクトに書くと、req の型は自動では決まりません。2つの書き方を TypeScript の型チェック(tsc)で確かめるため、わざと間違えたファイルを用意しました。

ts
// inline.ts:Bun.serve の中に直接書き、存在しない repoName を読む
Bun.serve({
  routes: {
    "/orgs/:org/repos/:repo": (req) => {
      return Response.json({ org: req.params.org, repo: req.params.repoName });
    },
  },
});
ts
// separate.ts:別のオブジェクトに書き、req に型を付けない
export const routes = {
  "/api/users/:id": (req) => Response.json({ id: req.params.id }),
};

strict: true の設定で tsc を実行すると、どちらもエラーになりました。

text
$ ./node_modules/.bin/tsc -p typecheck
typecheck/inline.ts(4,68): error TS2339: Property 'repoName' does not exist on type '{ org: string; repo: string; }'.
typecheck/separate.ts(2,22): error TS7006: Parameter 'req' implicitly has an 'any' type.

1つ目は、パラメーター名の打ち間違いを型チェックで見つけられることを示しています。2つ目は、別ファイルでは req が any 扱いになることを示しています。別ファイルに分けるときは、routes/users.ts のように req: BunRequest<"/api/users/:id"> と、パスと同じ文字列を型に書きます。BunRequest の params は、パスの中のパラメーター名をキーにした文字列のオブジェクトです(公式ドキュメントにある、BunRequest を簡略化した定義)。この書き方で、server.ts を含めた型チェックは通りました。

どの URL がどのルートに当たるか

server.ts に、少しずつ形を変えた URL を送りました。「fetch」と書いた行は、どのルートにも当たらず fetch の 404 が返ったものです。

送った URL 当たった先 結果
/api/users/1 /api/users/:id {"id":"1","name":"たま"}
/api/users/1/ fetch 末尾の / があると当たらない
/api/users/ fetch /api/users にも :id にも当たらない
/API/users fetch 大文字小文字は区別される
/api/users?sort=name /api/users クエリ文字列は無視して振り分ける
/api/users/1?x=1 /api/users/:id {"id":"1","name":"たま"}
/orgs/oven-sh/repos/bun /orgs/:org/repos/:repo {"org":"oven-sh","repo":"bun"}
/orgs/a/repos/b/issues fetch 後ろに続くパスがあると当たらない
/files/a/b/c.txt /files/* {"rest":"a/b/c.txt"}
/files/ /files/* {"rest":""}
/files fetch /files/* は /files 自体には当たらない
/search/?q=x fetch /search に末尾の / が付くと当たらない

末尾のスラッシュは、ほかの URL へリダイレクトされることもなく、別の URL として fetch に回りました。

クエリ文字列は new URL(req.url).searchParams で読みます。/search?q=%E7%8C%AB を送ると、デコードされた値が取れました。

text
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/search?q=%E7%8C%AB'
{"q":"猫"} [200]

* の部分の取り出し方と、/files も受けたいとき

* の部分が params に入るかを確かめるため、params とパスをそのまま返す wildcard.ts を作りました。/files も受けられるよう、別のルートを並べています。

ts
const server = Bun.serve({
  routes: {
    "/files": () => new Response("/files に当たった\n"),
    "/files/*": (req) => Response.json({ params: req.params, pathname: new URL(req.url).pathname }),
  },
});
console.log(`listening on ${server.url}`);
text
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/files'
/files に当たった
 [200]
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/files/'
{"params":{},"pathname":"/files/"} [200]
$ curl -s -w ' [%{http_code}]\n' 'http://localhost:3000/files/a/b/c.txt'
{"params":{},"pathname":"/files/a/b/c.txt"} [200]

params は空のオブジェクトで、* の部分は入っていませんでした。server.ts の /files/* のように、new URL(req.url).pathname から先頭の /files/ を取り除いて読みます。/files と /files/… の両方を受けたいときは、このように2つのルートを書くと、どちらも 200 になりました。

パラメーターの値は、デコードされてから入る

公式ドキュメントによると、パーセントエンコードされたパラメーターは自動でデコードされ、Unicode として正しくないものは置換文字(U+FFFD)になります(ルートパラメーターのデコードの説明)。params をそのまま JSON で返すルートで確かめた結果です。

text
$ curl -s 'http://localhost:3000/orgs/%E7%8C%AB/repos/x'
{"org":"猫","repo":"x"}
$ curl -s 'http://localhost:3000/orgs/a%20b/repos/x'
{"org":"a b","repo":"x"}
$ curl -s 'http://localhost:3000/orgs/a%2Fb/repos/x'
{"org":"a/b","repo":"x"}
$ curl -s 'http://localhost:3000/orgs/%FF/repos/x'
{"org":"�","repo":"x"}

a%2Fb を送ると、%2F は URL の区切りとしては扱われず、リクエストは :org のルートに当たりました。値には a/b と、スラッシュ入りの文字列が入っています。params の値を、ファイル名やほかの URL の一部に使うときは、/ が入ってくる前提で中身を確かめてから使います。

同じ位置に、名前の違うパラメーターを書いたとき

/users/:id と /users/:name/profile のように、同じ位置のパラメーター名が違っても、後ろに続くパスが違えば、両方とも使えました。

text
$ curl -s -w '[%{http_code}]\n' http://localhost:3000/users/42
id=42
[200]
$ curl -s -w '[%{http_code}]\n' http://localhost:3000/users/tama/profile
name=tama
[200]

一方、/users/:id と /users/:name を両方書くと、起動時にエラーや警告は出ませんでした。/users/42 には、あとに書いた /users/:name が答えています。

ts
const server = Bun.serve({
  routes: {
    "/users/:id": (req) => new Response(`id=${req.params.id}\n`),
    "/users/:name": (req) => new Response(`name=${req.params.name}\n`),
  },
});
console.log(`listening on ${server.url}`);
text
$ curl -s -w '[%{http_code}]\n' http://localhost:3000/users/42
name=42
[200]

この検証では、先に書いた /users/:id のハンドラーは呼ばれませんでした。このファイルを strict: true で tsc にかけても、エラーは出ませんでした。

注意

ルートを別ファイルに分けてスプレッド構文でまとめるときは、パラメーター名だけが違う同じ形のパスが、2か所に書かれていないかを確かめてください。

ログや認証など、共通の処理は関数で包む

複数のルートに同じ処理(ログ、認証の確認など)を足したいときは、ハンドラーを受け取って新しいハンドラーを返す関数を書きます。次の wrap.ts では、処理にかかった時間を出す withLog と、トークンを確かめる requireToken を作りました。型引数 P でパスの文字列を受け渡すので、包んだあとも req.params の型が残ります。

ts
import type { BunRequest } from "bun";

type Handler<P extends string> = (req: BunRequest<P>) => Response | Promise<Response>;

// ルートの関数を包んで、前後に共通の処理を足す
function withLog<P extends string>(handler: Handler<P>): Handler<P> {
  return async (req) => {
    const start = performance.now();
    const res = await handler(req);
    const ms = (performance.now() - start).toFixed(1);
    console.log(`${req.method} ${new URL(req.url).pathname} -> ${res.status} (${ms}ms)`);
    return res;
  };
}

function requireToken<P extends string>(handler: Handler<P>): Handler<P> {
  return (req) => {
    if (req.headers.get("authorization") !== "Bearer demo-token") {
      return Response.json({ error: "unauthorized" }, { status: 401 });
    }
    return handler(req);
  };
}

const server = Bun.serve({
  routes: {
    "/api/items/:id": {
      GET: withLog((req: BunRequest<"/api/items/:id">) => Response.json({ id: req.params.id })),
    },
    "/admin/*": withLog(requireToken(() => new Response("管理画面\n"))),
  },
});
console.log(`listening on ${server.url}`);

/admin/* に、トークンなしとトークンありでリクエストを送りました。demo-token は、この検証のために決めた値です。

text
$ curl -s -w ' [%{http_code}]\n' http://localhost:3000/admin/users
{"error":"unauthorized"} [401]
$ curl -s -H 'Authorization: Bearer demo-token' -w ' [%{http_code}]\n' http://localhost:3000/admin/users
管理画面
 [200]

/api/items/7 には、GET と HEAD(curl -sI)を送りました。

text
$ curl -s http://localhost:3000/api/items/7
{"id":"7"}
$ curl -sI http://localhost:3000/api/items/7
HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
content-length: 10

サーバー側には、4つのリクエストそれぞれについて、withLog のログが出ました。

text
GET /api/items/7 -> 200 (0.1ms)
HEAD /api/items/7 -> 200 (0.0ms)
GET /admin/users -> 401 (0.2ms)
GET /admin/users -> 200 (0.2ms)

/api/items/:id には GET しか書いていませんが、HEAD リクエストにも 200 が返り、ログを見ると GET のハンドラーが呼ばれていました。server.ts の /api/users/1 でも、HEAD には本文のない 200 が返り、content-length: 26 が付いていました。

​Posted by 86