Bun.serve and Built-in Clients
24. How do you define routes in Bun.serve?
Pass a routes object. Per the HTTP server docs, values can be a static Response, a handler, or an object keyed by HTTP method, with :param segments read from req.params and /* wildcards.
An optional fetch handler serves anything the routes miss.
const server = Bun.serve({
routes: {
"/health": new Response("ok"),
"/users/:id": {
GET: async (req) => Response.json(await getUser(req.params.id)),
DELETE: async (req) => {
await deleteUser(req.params.id);
return new Response(null, { status: 204 });
},
},
"/api/*": Response.json({ error: "not found" }, { status: 404 }),
},
fetch() {
return new Response("not found", { status: 404 });
},
});
console.log(`listening on ${server.url}`);
Defaults to know: the port comes from $BUN_PORT, $PORT or $NODE_PORT, otherwise 3000, and the hostname is 0.0.0.0. server.reload() swaps fetch, error, routes and websocket without a restart. server.stop() lets in-flight requests finish, while stop(true) closes everything, which matters for graceful shutdown on SIGTERM.
25. Find the bug: a server-sent events endpoint that drops clients.
Bun.serve({
routes: {
"/events": () => {
const stream = new ReadableStream({
async start(controller) {
for await (const event of subscribe("orders")) {
controller.enqueue(`data: ${JSON.stringify(event)}\n\n`);
}
},
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
},
},
});
Bug: Bun.serve closes connections after 10 seconds of inactivity by default. A quiet 10 seconds with no order makes the server drop the connection, and clients reconnect in a loop.
It works in a busy staging environment and fails on a quiet night in production.
Fix: take the server as the second handler argument and call server.timeout(req, 0) for this request, or raise idleTimeout (maximum 255 seconds) and send a comment line such as : ping more often than the timeout.
A strong candidate also cancels the subscription when the client disconnects, through the stream's cancel() callback or req.signal, so the server does not leak one subscriber per dropped client.
26. How do WebSockets and pub/sub work in Bun.serve?
Call server.upgrade(req, { data }) inside a handler, and supply a websocket object with open, message and close handlers. upgrade returns a boolean, and a handler that upgrades returns nothing.
Per-connection state goes in data, which is available as ws.data.
const server = Bun.serve({
fetch(req, server) {
const room = new URL(req.url).searchParams.get("room") ?? "lobby";
if (server.upgrade(req, { data: { room } })) return;
return new Response("upgrade failed", { status: 400 });
},
websocket: {
open(ws) {
ws.subscribe(ws.data.room);
},
message(ws, message) {
server.publish(ws.data.room, message);
},
},
});
A senior candidate knows topic pub/sub runs inside one process. Across several instances it needs Redis or another broker, and Bun's built-in Redis client can fill that role.
Upgrades work only over HTTP/1.1, and since 1.4.4 the close event fires only after the closing handshake, which changes the timing of cleanup code.
27. Find the bug: a search endpoint on Bun.SQL.
import { sql } from "bun";
export async function searchOrders(customerId: string, sort: string) {
const rows = await sql.unsafe(
`SELECT id, total FROM orders WHERE customer_id = '${customerId}' ORDER BY ${sort}`
);
return rows.map((r) => ({ id: r.id, total: r.total + 0 }));
}
Bugs:
- SQL injection:
sql.unsafe runs the string as given. Both customerId and sort come from the request.
- Column name from input: a tagged template binds values, not identifiers, so
sort needs an allow list.
- Type surprise: if
total is bigint (int8), the Bun.SQL docs say PostgreSQL returns it as a string by default, so r.total + 0 concatenates to "12500".
const SORTS = { newest: sql`created_at DESC`, total: sql`total DESC` } as const;
export async function searchOrders(customerId: string, sort: keyof typeof SORTS) {
return sql`
SELECT id, total::numeric::float8 AS total
FROM orders WHERE customer_id = ${customerId}
ORDER BY ${SORTS[sort] ?? SORTS.newest}`;
}
Values in a tagged template are bound as parameters. A candidate may also choose new SQL({ bigint: true }) and return BigInt, which is safer for money in minor units.
28. How do Bun.SQL connections, transactions and adapters work?
import { sql, SQL } from "bun" gives a default client configured from the environment and a constructor for others.
The URL protocol picks the adapter: postgres:// for PostgreSQL, mysql:// for MySQL, mariadb:// for MariaDB, and sqlite:// or :memory: for SQLite.
A plain filename such as "app.db" needs { adapter: "sqlite" }, or Bun reads it as a PostgreSQL host.
await sql.begin(async (tx) => {
const [order] = await tx`INSERT INTO orders ${sql({ customer_id: id, total })} RETURNING id`;
await tx.savepoint(async (sp) => {
await sp`UPDATE inventory SET qty = qty - 1 WHERE sku = ${sku}`;
});
return order;
});
Defaults worth knowing: max is 10 connections, connectionTimeout 30 seconds, idleTimeout and maxLifetime off, and no connection opens until the first query.
If the callback throws, Bun rolls back and sql.begin rejects. sql.reserve() takes a dedicated connection for session-level work such as advisory locks.
A strong candidate sizes max against the database's connection limit times the number of instances, and runs migrations with .simple(), which allows several statements but no parameters.
29. How does Bun's S3 client work, and where does it fit?
Bun.s3 is a default S3Client configured from the environment, and s3.file(key) returns a lazy S3File that extends Blob.
Per the S3 docs, credentials come from S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_REGION, S3_ENDPOINT and S3_BUCKET, falling back to the AWS_ names.
It works with AWS S3, Cloudflare R2, Google Cloud Storage, MinIO and other S3-compatible stores.
import { s3 } from "bun";
const report = s3.file(`reports/${id}.csv`);
await report.write(csv, { type: "text/csv" });
// presigned GET URL; the default expiry is 24 hours
const url = report.presign({ expiresIn: 900 });
// large uploads stream as multipart
const writer = s3.file("exports/big.ndjson").writer({ partSize: 5 * 1024 * 1024, retry: 3 });
for await (const line of rows()) writer.write(line + "\n");
await writer.end();
A strong candidate sets expiresIn on every presigned URL instead of accepting the 24-hour default, and returns presigned PUT URLs so browsers upload straight to the bucket.
They also know the limits: the client covers objects and listing (up to 1,000 keys per list call), not bucket policies or lifecycle rules, which still need the AWS SDK or infrastructure code.