Course outline · 0% complete

0/29 lessons0%

Course overview →

Routing: Tables and Dynamic Paths

lesson 3-2 · ~13 min · 9/29

From if-chains to a routing table

The if-chain from lesson 3-1 works, but at 30 routes it becomes a wall. Real routers use a routing table: a data structure mapping method + path to a handler function.

const routes = {
  "GET /hello": () => "Hello!",
  "POST /orders": () => "Order placed",
};

Looking up a route is now one line: build the key, check the table. Adding a route is adding a line of data, not more branching logic. This "replace code with data" move is one of the most useful habits in backend work.

Code exercise · javascript

Run this table-driven router. dispatch builds the key, finds the handler, and falls back to 404 when nothing matches.

Quiz

The table router above cannot serve GET /users/42, GET /users/43, and so on. Why not?

Dynamic segments: /users/:id

Every web framework supports path patterns like /users/:id. The :id part is a dynamic segment: it matches any value in that position and captures it as a param.

The matching algorithm is honest, simple string work:

  1. Split both pattern and path on /.
  2. If they have different lengths, no match.
  3. Walk the pieces together. A piece starting with : always matches and records params[name] = value. Any other piece must be equal, or there is no match.

So /users/:id vs /users/42 gives { id: "42" }, and /users/:id vs /orders/42 fails at piece one. Params are always strings, converting "42" to a number is your job later. Now build it, this function sits inside every framework you will ever use.

Code exercise · javascript

Your turn. Implement matchPath(pattern, path). Return an object of captured params when the path matches the pattern, or null when it does not. Follow the three-step algorithm from the text.

Code exercise · javascript

Your turn, the payoff. Combine the two ideas of this lesson: a routing table whose keys are patterns. dispatch walks the routes in order, uses matchPath (solved above) to test each pattern, and calls the first matching handler with the captured params. This little loop is, genuinely, the core of the router inside Express.