Skip to content

Capstone: a typed router

Relay needs a router for its HTTP endpoints: GET /hooks/:source/:id stores a webhook, POST /jobs/:jobId/retry requeues a job. With a plain router every handler reads req.params.sorce and finds out in production. Here the route string is the only place the param names are written, and the compiler reads them from there.

This lesson builds the router as a chain: createRouter().get(path, handler).post(path, handler). Each call changes the router’s type, so the handler gets the right params and the router knows which routes it holds.

  1. get(pattern, handler) and post(pattern, handler) each return a new router with the route added. The old router is not changed.
  2. In a handler, req.params is PathParams<typeof pattern>. For "/hooks/:source/:id" it is { source: string; id: string }.
  3. router.routes lists the registered keys, such as "GET /hooks/:source/:id". Its element type is the union of exactly those strings.
  4. router.handle(method, path, body) runs the first route that matches. It returns ok(reply), or err({ _tag: "NotFound", ... }) when nothing matches. It never throws.
  • Lesson 1: infer is how the params type reads the pattern. The router’s Result is the one from M3, and its error is a tagged value like the ones in M2.
  • Lesson 3: PathParams is a mapped type over the param names.
  • Lesson 4: PathParams itself, and the key type `GET ${P}`. The capstone starter gives you PathParams and matchRoute from that lesson, because the point here is how they plug into the router.
  • Lesson 7: a router is a chain of calls, each adding to the type. The type parameter Keys accumulates with Keys | `GET ${P}` , the same way a variadic tuple grows.

Two types carry the information. Router<Keys> records the route keys registered so far. Each get<P extends string> takes the pattern as a type parameter P, so the handler is (req: Request<P>) => Reply and the result is Router<Keys | `GET ${P}`>.

The runtime stores routes in one array, but routes have different P. Storing the handlers as they are would need P to be the same in all of them. Instead each route becomes an Entry with a run(path, body) function. run calls matchRoute(pattern, path) and the handler inside the closure, where P is still known, and returns Reply | null. The array holds closures that only mention strings.

interface Reply {
readonly status: number
readonly body: string
}
interface Entry<Key extends string> {
readonly key: Key
readonly method: "GET" | "POST"
readonly run: (path: string, body: string) => Reply | null
}

That is the same move as the overload in lesson 4: the typed promise stays outside, and the part that must handle many types at once sees only strings.

The starter gives you Result, Reply, NotFound, PathParams and matchRoute. Its router has only get, an untyped req.params, no routes and no post. Make Router generic over its keys, type the handler’s params from the pattern and add the missing parts. The rules at the top give the exact handle behavior.

In the Relay project the router sits in front of the queue. Handlers use req.params with no casts, and a misspelled param is rejected by the compiler:

src/server.ts
interface Reply {
readonly status: number
readonly body: string
}
type Simplify<T> = { [K in keyof T]: T[K] } & {}
type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : P
type ParamName<S extends string> = S extends `:${infer Name}` ? Name : never
type PathParams<P extends string> = Simplify<{ [K in ParamName<Segments<P>>]: string }>
declare function createRouter(): {
get<P extends string>(
pattern: P,
handler: (req: { params: PathParams<P>; body: string }) => Reply,
): { handle(method: "GET" | "POST", path: string, body?: string): unknown }
}
const router = createRouter().get("/hooks/:source/:id", (req) => ({
status: 200,
body: `stored ${req.params.id} from ${req.params.source}`,
}))
const result = router.handle("GET", "/hooks/github/42")

Replace the declare with an import of your own createRouter. Bun’s fetch handler would call router.handle(request.method, url.pathname) and turn the Result into a Response.

  • The route string is the single source of truth: PathParams<P> types req.params, and `GET ${P}` types the key.
  • A chain of calls changes the type step by step. Each method returns a new router with a bigger Keys union.
  • Closures hide the per-route type parameter, so one array can hold every route without a cast.
  • handle returns a Result with a tagged NotFound. An unknown path is a value, not an exception.
  • Computed types earn their place when a string is already the contract. Keep them to the one place where the strings are read.