Skip to content

Beginner · APIs and request handling · topic 8 of 54 · 25 min

Routing: sending each request to the right code

Explanation

Routing means looking at the method and path of a request and choosing the function that should handle it. A route table lists patterns like GET /users/:id, where :id is a path parameter that can be any value. Query strings carry extra options and are read with URLSearchParams.

What a router does

A route is one pair of a method and a path pattern, joined to a handler. A handler is the function that does the work for that route. A router is the code that takes each request, finds the matching route and calls its handler.

Think of it like this: A router is like the sorting desk in a post office. Each letter has a PIN code. The sorter looks at the PIN code and drops the letter into the right bag for that area. A router looks at the method and path, and drops the request into the right handler.

A route table

A route table is a simple list of routes. The router checks them from top to bottom and uses the first one that matches.

javascript
const routes = [
  { method: 'GET', pattern: '/products', handler: () => 'list products' },
  { method: 'POST', pattern: '/products', handler: () => 'create product' },
  { method: 'GET', pattern: '/products/:id', handler: () => 'read one product' },
];

for (const r of routes) console.log(r.method.padEnd(5), r.pattern);
Each route joins a method and a pattern to a handler function.

Path parameters

A path parameter is a part of the pattern that starts with a colon, like :id in /products/:id. It matches any value in that place, and the router saves the value under that name. For /products/42, the params are { id: "42" }.

  1. Split the pattern and the path on "/" and drop empty parts.
  2. If they have a different number of parts, it is not a match.
  3. Compare part by part. A pattern part starting with ":" matches anything; save the value under its name.
  4. Any other pattern part must be exactly equal to the path part.
  5. If every part matched, return the saved params. Otherwise return null.
javascript
function splitPath(path) {
  return path.split('/').filter(Boolean);
}

console.log(splitPath('/users/42/orders')); // [ 'users', '42', 'orders' ]
console.log(splitPath('/users/42/'));       // [ 'users', '42' ]
console.log(splitPath('/'));                // []
filter(Boolean) removes the empty strings that come from the slashes at the start and end.
Careful: Path parameters are always strings. "42" is not the number 42. Convert with Number(params.id) and check the result with Number.isInteger before you use it, or /products/abc will cause strange bugs.

Query strings

The query string is not part of the route. GET /products?category=rice and GET /products both go to the same route. The handler then reads the options with URLSearchParams.

javascript
const raw = '/products?category=rice&maxPrice=200';
const [path, queryText] = raw.split('?');
const query = new URLSearchParams(queryText);

console.log(path);                       // /products
console.log(query.get('category'));      // rice
console.log(Number(query.get('maxPrice'))); // 200
console.log(query.get('sort'));          // null
Split off the query first; route on the path; read options with URLSearchParams.
Tip: Order matters in a route table. Put fixed routes like GET /users/me above GET /users/:id, or the word "me" will be caught as an id.

Watch the lesson

Routing: sending each request to the right code · 1/6

Method + path = route

Routing means choosing which function handles a request, by looking at its method and path.

Prefer a video by a teacher? Find free videos on “how routing works in backend express route parameters tutorial” on YouTube ↗

In real life: How Express does routing

Express is the most used Node.js backend framework. Its routes look exactly like our table: a method, a pattern with :params, and a handler. Express fills req.params from the path and req.query from the query string, so the handler gets them ready to use. You will build this for real in module 3.

javascript
// runs on a server with Node.js and Express installed
const express = require('express');
const app = express();

app.get('/products/:id', (req, res) => {
  const id = Number(req.params.id);
  res.json({ id, currency: req.query.currency || 'INR' });
});

app.listen(3000);
The same idea in a real framework: method, pattern with :id, handler.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function splitPath(path) that returns the parts of a path between slashes, without empty parts. "/users/42/" gives ["users", "42"] and "/" gives [].

Task 2 · Code · Javascript

Write a function matchRoute(pattern, path). If the path fits the pattern, return an object of path parameters (an empty object {} when the pattern has none). If it does not fit, return null. Example: matchRoute("/users/:id", "/users/42") gives { id: "42" }.

Task 3 · Code · Javascript

Build a tiny router. matchRoute is given. Write route(routes, request): find the first route whose method equals request.method and whose pattern matches request.path. Call its handler with { ...request, params } and return what it returns. If no route matches, return { status: 404, body: "Not found" }.

Quick quiz

Question 1

1.What does a router do?

Question 2

2.For the pattern /shops/:shopId/items/:itemId and the path /shops/3/items/77, what are the params?

Question 3

3.Which route handles GET /products?sort=price?

Question 4

4.You have GET /users/:id above GET /users/me. What happens with GET /users/me?

Question 5

5.What does new URLSearchParams("page=2&q=dal").get("page") return?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: What an API is and how REST APIs are designed