Routing

How a server decides which code handles a given URL and HTTP method.

What is it?

A backend does many things: list users, create orders, delete comments. Every request arrives with a path (like /users or /orders/42) and a method (GET, POST, PUT, DELETE...). Together they say what the caller wants, and the server uses them to pick which function runs.

That mapping from "method + path" to a handler function is routing. Each single mapping (like "GET /users runs this function") is a route.

Explain like I'm 10

A router is like the directory board in an office lobby: you say who you want to see and why (a delivery or a meeting), and it tells you which floor and room to go to. Without it, you'd knock on every door in the building.

Examples

Basic routes by method and path

app.get("/users", (req, res) => {
  res.json(allUsers);
});

app.post("/users", (req, res) => {
  const newUser = createUser(req.body);
  res.status(201).json(newUser);
});

app.delete("/users/:id", (req, res) => {
  deleteUser(req.params.id);
  res.status(204).end();
});

The same path, /users, does different things depending on the HTTP method. Routing tells them apart.

Route parameters and query strings

// GET /products/17?color=red
app.get("/products/:id", (req, res) => {
  const productId = req.params.id;   // "17"
  const color = req.query.color;     // "red"
  res.json(findProduct(productId, color));
});

Route parameters (:id) capture parts of the path. Query strings (?color=red) carry optional extras after a question mark.

How it works

When a request arrives, the framework checks your routes in the order you defined them, comparing each one's method and path pattern. At the first match, it runs that handler and stops looking (unless the handler passes control on). If nothing matches, it sends a default "not found" response.

Why does it exist?

Without routing, one giant function would check the method and path with endless if-statements. Routing lets you declare clearly which code handles which request, so the codebase stays easy to navigate as it grows to dozens or hundreds of endpoints.

When to use it

Every endpoint needs a route. Whenever a client should reach some server logic through a specific URL and method, define a route for it.

When not to use it

Logic not triggered by a request doesn't need a route. A scheduled job or internal helper isn't called by URL.

Common mistakes

  • Defining a general route (like /users/:id) before a specific one (like /users/me). The general one matches first and swallows requests meant for the specific one.

  • Forgetting that the same path can mean different things for different HTTP methods.

  • Confusing route parameters (part of the path, like :id) with query strings (the ?key=value part after the path).

Practice exercises

  1. Easy:

    Write a route that responds to a GET request at /ping with the text "pong".

  2. Medium:

    Write a route /articles/:slug that reads the slug from the URL and returns it in a JSON response.

  3. Hard:

    Explain why putting app.get("/users/:id") before app.get("/users/me") causes a bug, and show how to fix the order.

Interview questions

What is routing in a web server?

The mechanism that maps an incoming request's method and URL path to the specific function that should handle it.

What's the difference between a route parameter and a query string?

A route parameter is a named part of the path itself, like :id in /users/:id, while a query string is optional key-value data appended after a question mark, like ?sort=asc.

What typically happens if no route matches an incoming request?

The framework falls back to a default handler, usually responding with a 404 Not Found status.

Why does the exact same URL path behave completely differently depending on the HTTP method used?

A route is method and path together. GET /users and POST /users are two separate routes that share a path, each with its own handler.

Given `app.get("/users/:id", handler1)` registered before `app.get("/users/me", handler2)`, which handler runs for a GET request to `/users/me`, and why?

handler1 runs. :id matches any value there, including the text "me". The framework checks routes in registration order and stops at the first match, so the general pattern wins even though /users/me was meant for handler2.

How would you fix the ordering bug from the previous question so `/users/me` reaches the correct handler?

Register the specific route, app.get("/users/me", handler2), before the general app.get("/users/:id", handler1), so the exact match is checked first.

In `app.get("/users/:id", ...)`, what does `req.params.id` contain for a request to `/users/42`?

The string "42". Route parameters are strings taken from the URL; they aren't converted to numbers or other types.

For a request to `/products/17?color=red`, what does `req.query` contain, and how does that differ from `req.params`?

req.query is { color: "red" }, the data after the ?, usually optional filters. req.params is { id: "17" }, captured from the path pattern. Params usually identify the resource and are required; query strings are usually optional refinements.

Why does a framework generally stop looking for further route matches once it finds the first one that matches?

A request should be handled once. Running it through every matching route would be wasteful and ambiguous, so the framework runs the first match and treats the request as handled.

Why does it matter that a route to delete a resource uses the DELETE method rather than just reusing GET for everything?

Routing uses the method as well as the path, so DELETE lets one URL safely support several operations. It also lets tools, caches and other developers see what a request does without reading its body.

A route is defined as `app.post("/users", ...)`, but a client sends a GET request to `/users` and no other route matches. What happens?

The method doesn't match, so no route matches. The request falls through to the framework's default "not found" behavior, usually a 404.

Why is it a mistake to think of a route path as matching regardless of HTTP method?

A route always pairs a method with a path pattern. A path alone isn't a full route, so /users registered only for GET won't match a POST to that path.

Why does the order in which routes are registered matter, if the framework is just checking each one against the request?

The framework stops at the first match, not the best match. A general pattern registered earlier can catch requests meant for a specific one registered later, so order acts as priority.

A team registers `app.get("/articles/:slug", handler1)` before `app.get("/articles/featured", handler2)`. What bug will `/articles/featured` hit?

Requests to /articles/featured are always caught by the :slug route, since :slug matches the text "featured" like any other value. handler2 never runs.

What general rule of thumb avoids the "general route matches before specific route" bug?

Register specific, literal routes before general, parameterized ones that could match the same requests.

Can a single path like `/users` have more than one route registered against it?

Yes. A route is method plus path, so /users can have separate GET, POST, DELETE (and other) routes, each with its own handler.

Why can a route parameter like `:id` match values you didn't expect, such as non-numeric text where you assumed a number, and what problem can that cause?

A route parameter captures whatever text is in that URL segment, with no type or format check. /users/:id matches /users/abc as readily as /users/42, so the handler must validate or convert the value, or it may crash or misbehave.

What's the difference in purpose between a route parameter and a query string, beyond syntax — when would you reach for one over the other?

A route parameter usually identifies which resource you're working on, so it's part of the path's identity (/orders/42). A query string usually adds optional modifiers, like sorting or filtering, that don't change which resource it is (/orders?status=shipped).

Is there a meaningful difference between `/users/:id` and `/users?id=42` achieving something similar?

Yes. By convention, /users/:id says "this URL is one specific user", while /users?id=42 reads as "list users, filtered by id". The intent differs even if the data returned overlaps.

Why does a framework need a "no routes matched" fallback at all, rather than assuming a route always exists?

Clients can request any path: typos, old URLs, malicious probes. A server can't guarantee a route exists for every request, so it needs defined behavior when nothing matches.

Walk through what happens, in order, when a `DELETE /users/42` request arrives.

The framework checks routes in the order defined, comparing each method and path pattern with DELETE and /users/42. When it reaches a match like app.delete("/users/:id", ...), it runs that handler with req.params.id set to "42" and stops looking.

If two routes are registered for the exact same method and path — `app.get("/x", a)` then `app.get("/x", b)` — which one runs, and why might this be a bug?

Handler a runs, because it was registered first and the framework stops at the first match. b is dead code for that path, which is almost always a mistake.

Why is routing described as replacing "one giant function with endless if-statements"? What would that alternative look like, and why is it harder to maintain?

Without routing, one handler would check method === "GET" && url === "/users", then method === "POST" && url === "/users", and so on for every endpoint. With dozens of endpoints, that function becomes long, hard to navigate, and prone to ordering and typo bugs. Separate routes keep each endpoint's logic isolated and easy to find.

Why doesn't routing logic apply to a scheduled background job, even though that job also runs backend code?

Routing maps an incoming HTTP request's method and path to a handler. A background job isn't triggered by a request or URL, so there's nothing to match. It's called directly on a timer or trigger, like any function.

How is routing conceptually similar to a JavaScript `switch` statement, and how is it different?

Both pick one branch from several by matching an incoming value. But a switch usually matches one exact value, while routing matches two things at once (method and path pattern), and path patterns can include parameters that match many values.