Skip to content

Bun.serve and typed routes

Relay’s HTTP layer so far is one fetch function with an if (url.pathname === ...) chain. It crashes when a body is not JSON, it answers errors with the text Internal Server Error, and the only way to test it is to start the real process on port 8080 and hope nothing else uses that port.

Bun.serve fixes the shape of this. A server is a set of routes, each one a function from Request to Response: the same two types as in lesson 1, now on the receiving end. This lesson builds Relay’s API on it and tests it with the client’s own fetch.

A server is a function from Request to Response

Section titled “A server is a function from Request to Response”
const server = Bun.serve({
port: 0,
fetch(request) {
const url = new URL(request.url)
return new Response(`you asked for ${url.pathname}`)
},
})
console.log(server.port, server.url.href)
await server.stop()

port: 0 asks the operating system for any free port. server.port and server.url tell you which one you got. Use port 0 in every test: two test files that both listen on 3000 fail at random, and a test that fails at random teaches nobody anything.

A handler may be async and may return a Promise<Response>. It receives the standard Request, so everything from lesson 1 applies: request.headers.get(...), await request.text().

A single fetch with an if-chain is where routing bugs live. Give Bun a routes object and it does the matching:

const server = Bun.serve({
port: 0,
routes: {
"/health": new Response("ok"),
"/jobs/:id": {
GET: (request) => Response.json({ id: request.params.id }),
DELETE: (request) => new Response(`deleted ${request.params.id}`),
},
},
fetch: () => Response.json({ error: "not_found" }, { status: 404 }),
})
await server.stop()

Each route value is a ready Response, a handler, or an object with one handler per HTTP method. Static routes win over parameter routes (/jobs/:id), and those win over wildcards (/api/*).

The params are typed from the route string. Bun’s types do for "/jobs/:id" what lesson 4 of M4 did by hand:

Bun.serve({
port: 0,
routes: {
"/hooks/:source/:id": (request) => {
const { source, id } = request.params // { source: string; id: string }
// @ts-expect-error: Property 'sorce' does not exist on this route's params
request.params.sorce
return new Response(`${source}/${id}`)
},
},
})

A typo in a param name fails to compile, and you did not write the type.

A handler should read like a short pipeline: check the input, do the work, build the response. The Relay webhook route uses all three pieces of the earlier lessons:

type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
declare function readText(request: Request, maxBytes: number): Promise<{ ok: true; text: string } | { ok: false }>
declare function decodeWebhook(text: string): DecodeResult<{ items: readonly { id: string }[] }>
const problem = (status: number, error: string, detail?: string): Response =>
Response.json(detail === undefined ? { error } : { error, detail }, { status })
export async function postHook(request: Request): Promise<Response> {
const body = await readText(request, 1_000_000)
if (!body.ok) return problem(413, "too_large")
const decoded = decodeWebhook(body.text)
if (!decoded.ok) return problem(400, "invalid_body", decoded.error)
return Response.json({ accepted: decoded.value.items.length }, { status: 202 })
}

problem is the whole error format: a status and a machine-readable error code, plus a human detail when it helps. Callers (like the client from lesson 1) can branch on error, and a dashboard can show detail. Do not put the text of an internal exception in either. An exception message such as disk full: /var/lib/relay tells an attacker about your machine.

Status codes carry meaning, so pick them on purpose: 202 accepted for later work, 400 the body is wrong, 404 no such thing, 413 too large, 500 our bug.

An exception in a handler is a bug. Without a handler for it Bun answers with a generic error page, and with a development flag it prints a stack to the client. Add an error function to answer every uncaught exception the same way:

const server = Bun.serve({
port: 0,
routes: {
"/boom": () => {
throw new Error("disk full: /var/lib/relay")
},
},
error(error) {
console.error(error) // the log has the detail
return Response.json({ error: "internal" }, { status: 500 }) // the client does not
},
fetch: () => Response.json({ error: "not_found" }, { status: 404 }),
})
await server.stop()

Errors you expect (a bad body, an unknown id) are returned as Responses, as above. error is the net under the ones you did not expect.

server.stop() stops accepting connections and waits for in-flight requests. Connections that are kept open on purpose (an event stream, a WebSocket, a keep-alive socket) keep it waiting, so stop(true) closes them. Use stop(true) in tests, and plain stop() when you want a graceful drain.

Server is Disposable, so using from M5 stops it at the end of the block:

{
using server = Bun.serve({ port: 0, fetch: () => new Response("hi") })
const res = await fetch(server.url)
console.log(res.status, await res.text())
} // the server is stopped here, and the port is free again

Server has the synchronous Symbol.dispose, not Symbol.asyncDispose, so using cannot wait for the connections to drain. When a test must wait until every connection is closed, await server.stop(true) in afterEach is clearer.

The server and the client are in the same process, so a test is: start on port 0, call it, assert on the Response, stop. No mocks. This tests routing, status codes and headers for real:

import { afterEach, expect, test } from "bun:test"
const servers: Bun.Server<undefined>[] = []
afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => server.stop(true)))
})
test("unknown paths are JSON 404s", async () => {
const server = Bun.serve({ port: 0, fetch: () => Response.json({ error: "not_found" }, { status: 404 }) })
servers.push(server)
const res = await fetch(new URL("/nowhere", server.url))
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: "not_found" })
})

Keep the server’s state outside the server, in a value the test passes in (the JobStore below). That is the functional core and imperative shell again: the handlers are a thin layer, and the logic they call can be tested without any HTTP at all. Test the logic directly, and test the HTTP layer for what only it can get wrong: routes, statuses, headers.

This is a local exercise: it needs real Bun and a real port. Copy the three files below into the Relay project from M1 lesson 1, in one folder such as src/networking/serve/. decode.ts is complete (it is lesson 2’s kit, plus readText from this lesson), so you only edit main.ts. Rename main.starter.ts to main.ts, then run bun test.

decode.ts
export type DecodeResult<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly error: string }
export type Decoder<T> = (input: unknown, path: string) => DecodeResult<T>
export type Infer<D> = D extends Decoder<infer T> ? T : never
const fail = (path: string, expected: string): DecodeResult<never> => ({ ok: false, error: `${path}: expected ${expected}` })
export const string: Decoder<string> = (input, path) =>
typeof input === "string" ? { ok: true, value: input } : fail(path, "string")
export const number: Decoder<number> = (input, path) =>
typeof input === "number" && Number.isFinite(input) ? { ok: true, value: input } : fail(path, "number")
export function literal<const V extends string | number | boolean>(expected: V): Decoder<V> {
return (input, path) => (input === expected ? { ok: true, value: expected } : fail(path, JSON.stringify(expected)))
}
export function array<T>(item: Decoder<T>): Decoder<T[]> {
return (input, path) => {
if (!Array.isArray(input)) return fail(path, "array")
const out: T[] = []
for (const [index, element] of input.entries()) {
const r = item(element, `${path}[${index}]`)
if (!r.ok) return r
out.push(r.value)
}
return { ok: true, value: out }
}
}
export function object<S extends Record<string, Decoder<unknown>>>(shape: S): Decoder<{ [K in keyof S]: Infer<S[K]> }>
export function object(shape: Record<string, Decoder<unknown>>): Decoder<Record<string, unknown>> {
return (input, path) => {
if (typeof input !== "object" || input === null || Array.isArray(input)) return fail(path, "object")
const out: Record<string, unknown> = {}
for (const [key, field] of Object.entries(shape)) {
const r = field(Object.hasOwn(input, key) ? Reflect.get(input, key) : undefined, `${path}.${key}`)
if (!r.ok) return r
out[key] = r.value
}
return { ok: true, value: out }
}
}
export function union<const Ds extends readonly Decoder<unknown>[]>(...variants: Ds): Decoder<Infer<Ds[number]>>
export function union(...variants: readonly Decoder<unknown>[]): Decoder<unknown> {
return (input, path) => {
for (const variant of variants) {
const r = variant(input, path)
if (r.ok) return r
}
return { ok: false, error: `${path}: no variant matched` }
}
}
export const webhookBody = object({
delivery: string,
items: array(object({ id: string, attempts: number })),
})
export type Webhook = Infer<typeof webhookBody>
export function parseJson<T>(text: string, decoder: Decoder<T>): DecodeResult<T> {
let json: unknown
try {
json = JSON.parse(text)
} catch {
return { ok: false, error: "body: not valid JSON" }
}
return decoder(json, "body")
}
export async function readText(request: Request, maxBytes: number): Promise<{ readonly ok: true; readonly text: string } | { readonly ok: false }> {
const declared = Number(request.headers.get("content-length") ?? 0)
if (declared > maxBytes) return { ok: false }
if (request.body === null) return { ok: true, text: "" }
const chunks: Uint8Array[] = []
let size = 0
for await (const chunk of request.body) {
size += chunk.byteLength
if (size > maxBytes) return { ok: false }
chunks.push(chunk)
}
return { ok: true, text: new TextDecoder().decode(Buffer.concat(chunks)) }
}
main.starter.ts (rename to main.ts)
// Relay's HTTP API, built on Bun.serve. Today it is one `fetch` function with an if-chain: it
// crashes on a bad body, answers errors with plain text and never limits the body size. Move it to
// `routes`, decode bodies with decode.ts (lesson 2's kit) and answer every error with JSON.
// The starter accepts everything and answers 200.
//
// Rules:
// - startApi(store, { maxBodyBytes }) starts Bun.serve on port 0 (the OS picks a free port) and
// returns the server. Tests read `server.url` and stop it with `server.stop(true)`.
// - POST /hooks/:source. The source must be "ci" or "cron", else 404 { error: "unknown_source" }.
// - The body is read with readText(request, maxBodyBytes). Too large: 413 { error: "too_large" }.
// - The text is JSON.parse'd, then decoded with webhookBody and the root path "body". Invalid JSON or
// a decode failure: 400 { error: "invalid_body", detail: <the message> }, e.g.
// detail "body.items[2].id: expected string". Invalid JSON has the detail "body: not valid JSON".
// - A valid body stores one Job per item with store.set(id, { id, source, attempts }) and answers
// 202 { accepted: <item count> }.
// - GET /jobs/:id answers 200 with the Job, or 404 { error: "not_found" }.
// - Anything else (unknown path, wrong method) answers 404 { error: "not_found" }, as JSON.
// - If a handler throws, answer 500 { error: "internal" }, as JSON. Never leak the message.
// - Every response has the content-type application/json.
import { parseJson, readText, webhookBody } from "./decode.ts"
export type Source = "ci" | "cron"
export interface Job {
readonly id: string
readonly source: Source
readonly attempts: number
}
export interface JobStore {
get(id: string): Job | undefined
set(id: string, job: Job): void
}
const isSource = (value: string): value is Source => value === "ci" || value === "cron"
const problem = (status: number, error: string, detail?: string): Response =>
Response.json(detail === undefined ? { error } : { error, detail }, { status })
export function startApi(store: JobStore, options: { readonly maxBodyBytes: number }): Bun.Server<undefined> {
return Bun.serve({
port: 0,
fetch: async (request) => {
const url = new URL(request.url)
const body: unknown = await request.json()
return new Response(`${request.method} ${url.pathname} ${JSON.stringify(body)}`)
},
})
}
main.test.ts
import { afterEach, expect, test } from "bun:test"
import { startApi, type Job, type JobStore } from "./main.ts"
const servers: Bun.Server<undefined>[] = []
afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => server.stop(true)))
})
function start(store: JobStore = memoryStore(), maxBodyBytes = 1024) {
const server = startApi(store, { maxBodyBytes })
servers.push(server)
return { server, url: (path: string) => new URL(path, server.url).href }
}
function memoryStore(): JobStore & { readonly jobs: Map<string, Job> } {
const jobs = new Map<string, Job>()
return { jobs, get: (id) => jobs.get(id), set: (id, job) => void jobs.set(id, job) }
}
const post = (url: string, body: string) => fetch(url, { method: "POST", body })
const goodBody = JSON.stringify({ delivery: "d1", items: [{ id: "j1", attempts: 0 }, { id: "j2", attempts: 2 }] })
test("a valid webhook is stored and answered with 202", async () => {
const store = memoryStore()
const api = start(store)
const res = await post(api.url("/hooks/ci"), goodBody)
expect(res.status).toBe(202)
expect(res.headers.get("content-type")).toContain("application/json")
expect(await res.json()).toEqual({ accepted: 2 })
expect(store.jobs.get("j2")).toEqual({ id: "j2", source: "ci", attempts: 2 })
})
test("an unknown source is 404 unknown_source", async () => {
const api = start()
const res = await post(api.url("/hooks/github"), goodBody)
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: "unknown_source" })
})
test("a body that fails decoding is 400 with the error path, and nothing is stored", async () => {
const store = memoryStore()
const api = start(store)
const bad = JSON.stringify({ delivery: "d1", items: [{ id: "j1", attempts: 0 }, { id: "j2", attempts: 0 }, { id: 7, attempts: 0 }] })
const res = await post(api.url("/hooks/cron"), bad)
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: "invalid_body", detail: "body.items[2].id: expected string" })
expect(store.jobs.size).toBe(0)
})
test("invalid JSON is 400, not a crash", async () => {
const api = start()
const res = await post(api.url("/hooks/ci"), "{oops")
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: "invalid_body", detail: "body: not valid JSON" })
})
test("a body over the limit is 413", async () => {
const api = start(memoryStore(), 64)
const res = await post(api.url("/hooks/ci"), goodBody.padEnd(500, " "))
expect(res.status).toBe(413)
expect(await res.json()).toEqual({ error: "too_large" })
})
test("a streamed body without a content-length is still limited", async () => {
const api = start(memoryStore(), 64)
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const chunk = new TextEncoder().encode("x".repeat(40))
controller.enqueue(chunk)
controller.enqueue(chunk)
controller.close()
},
})
const res = await fetch(api.url("/hooks/ci"), { method: "POST", body: stream })
expect(res.status).toBe(413)
})
test("GET /jobs/:id returns the job or 404", async () => {
const store = memoryStore()
const api = start(store)
store.set("j1", { id: "j1", source: "cron", attempts: 1 })
const found = await fetch(api.url("/jobs/j1"))
expect(found.status).toBe(200)
expect(await found.json()).toEqual({ id: "j1", source: "cron", attempts: 1 })
const missing = await fetch(api.url("/jobs/nope"))
expect(missing.status).toBe(404)
expect(await missing.json()).toEqual({ error: "not_found" })
})
test("an unknown path and a wrong method are JSON 404s", async () => {
const api = start()
const path = await fetch(api.url("/nowhere"))
expect(path.status).toBe(404)
expect(path.headers.get("content-type")).toContain("application/json")
expect(await path.json()).toEqual({ error: "not_found" })
const method = await fetch(api.url("/jobs/j1"), { method: "DELETE" })
expect(method.status).toBe(404)
expect(await method.json()).toEqual({ error: "not_found" })
})
test("a handler that throws is a JSON 500 that does not leak the message", async () => {
const broken: JobStore = {
get: () => undefined,
set: () => {
throw new Error("disk full: /var/lib/relay")
},
}
const api = start(broken)
const res = await post(api.url("/hooks/ci"), goodBody)
expect(res.status).toBe(500)
expect(await res.text()).toBe('{"error":"internal"}')
})

The starter has one fetch that reads the body with request.json() and answers 200 to everything. Move it to routes, decode with webhookBody, and answer every error as JSON. The test that makes the handler throw should also pass, without the message in the response.

  • Bun.serve({ port: 0, routes, fetch, error }): routes matches paths and methods, fetch is the fallback (also for wrong methods, there is no automatic 405), error catches what you did not expect.
  • Route params are typed from the route string: request.params.id, and a typo does not compile.
  • Answer every failure with the same JSON shape and the right status, and never leak an exception message.
  • Use port 0 in tests, call the server with fetch, and stop it with stop(true) (or using).