Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท HTTP Servers and APIs

Routes, Parameters and Method Handlers

Use the routes object in Bun.serve: static responses, :id parameters, wildcards, per-method handlers, a fallback fetch and 404/405 answers, with a runnable Node stand-in.

An if (url.pathname === ...) chain works for three endpoints and hurts at thirty. Bun.serve has a built-in router: the routes option maps URL patterns to handlers. Bun matches the most specific route first, fills in req.params, and falls back to your fetch function when nothing matches. No framework needed for most APIs.

The routes object

TypeScript
const server = Bun.serve({
  routes: {
    // static response: built once, served very fast
    "/": new Response("Welcome"),
    "/health": Response.json({ status: "ok" }),

    // handler function
    "/time": () => Response.json({ now: new Date().toISOString() }),

    // named parameter
    "/users/:id": (req) => Response.json({ id: req.params.id }),

    // several parameters
    "/posts/:year/:slug": (req) => Response.json(req.params),

    // wildcard: everything under /files/
    "/files/*": (req) => new Response("file path: " + new URL(req.url).pathname),
  },

  // anything that did not match a route
  fetch(req) {
    return new Response("Not Found", { status: 404 });
  },
});

Points to remember:

  • A static Response value is allocated once and reused for every request. Use it for health checks and fixed text, never for per-user content.
  • req.params is typed for you in TypeScript: for "/users/:id" it is { id: string }. Values are strings; convert with Number() and validate them.
  • * matches the rest of the path. Specific routes win over wildcards, so /files/readme beats /files/* if both exist.
  • Routes are exact: /health does not match /health/. Decide on a trailing slash policy and stick to it.

One handler per HTTP method

Give a route an object keyed by method instead of a function. A method you do not list gets an automatic 405 Method Not Allowed.

TypeScript
const todos = new Map<number, { id: number; title: string }>();
let nextId = 1;

Bun.serve({
  routes: {
    "/api/todos": {
      GET: () => Response.json([...todos.values()]),
      POST: async (req) => {
        const { title } = await req.json();
        const todo = { id: nextId++, title };
        todos.set(todo.id, todo);
        return Response.json(todo, { status: 201 });
      },
    },
    "/api/todos/:id": {
      GET: (req) => {
        const todo = todos.get(Number(req.params.id));
        return todo ? Response.json(todo) : new Response("Not found", { status: 404 });
      },
      DELETE: (req) => {
        todos.delete(Number(req.params.id));
        return new Response(null, { status: 204 });
      },
    },
  },
});

This is the whole shape of a small REST API. Status codes matter: 201 Created for a new resource, 204 No Content for a delete, 404 for a missing item, 400 for bad input.

A routing stand-in you can run

The adapter below is not Bun. It implements just enough of routes (static responses, :params, *, per-method objects, a fetch fallback, 405) on Node's http, so you can experiment with handler code that is identical to what you would run on Bun.

Node.js Routes with params and methods (Node 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.

Validate what comes from the URL

req.params.id is whatever the client typed. Number("abc") is NaN, and todos.get(NaN) quietly returns undefined. For real APIs check explicitly and answer 400:

TypeScript
function parseId(raw: string): number | null {
  return /^\d+$/.test(raw) ? Number(raw) : null;
}

A small helper like this removes a class of bugs. Libraries such as Zod can validate whole bodies, and you install them with the package manager like any npm package.

Organizing routes

Routes are plain objects, so you can build them in pieces and spread them together:

TypeScript
import { userRoutes } from "./routes/users";
import { postRoutes } from "./routes/posts";

Bun.serve({
  routes: { ...userRoutes, ...postRoutes },
});

Each file exports an object such as { "/api/users": { GET: listUsers } }. Handlers can live in their own modules and be unit-tested without starting a server, because they are just functions from Request to Response. The testing chapter uses exactly that.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the :id part of the route /users/:id in Bun?

    Bun fills req.params with the named segments of the matched route.
  2. 2. What does Bun answer when a route object has only GET and POST and the client sends DELETE?

    A method missing from a route's per-method object gets a 405 response.
  3. 3. Why is a static Response route unsuitable for per-user content?

    A static Response is created a single time and served repeatedly, so it must not depend on the request.
  4. 4. Which status code fits a successful DELETE that returns no body?

    204 No Content tells the client the action worked and there is nothing to read.

Summary

  • routes maps patterns to static responses, handler functions or per-method objects.
  • :name captures into req.params (strings); * is a wildcard; specific routes win.
  • Unlisted methods get 405; unmatched paths fall through to fetch.
  • Always validate parameters before using them.
  • Handlers are plain functions, so build routes from modules and test them without a server.

Next: Request Bodies: JSON, Forms and Uploads