beprodready
Build Your Own HTTP Server

Stage 2: The Router

stage 2 of 4 · ~25 min · runs in your browser

Every framework's app.get("/users/:id", handler) is a tiny pattern matcher. Build it.

Implement createRouter() returning:

  • add(method, pattern, handler) — register a route; pattern segments starting with : are parameters (/users/:id/posts/:postId)
  • handle(method, path) — find the matching route and return handler({ params }); return { status: 404 } if no pattern matches, and { status: 405 } if a pattern matches but with the wrong method (real servers distinguish "no such resource" from "wrong verb").

Matching rules: exact segment count, literal segments must equal, : segments capture. First registered match wins.

tests (5)

routes a literal path

captures path parameters

unknown path is 404

wrong method is 405, not 404

first registered match wins

createRouter.js