Skip to content

Routing

Routing is the process of deciding which piece of code handles a given HTTP request. The decision is based on two properties of the request:

  • req.method — the HTTP verb: GET, POST, PUT, DELETE, etc.
  • req.url — the path (and optional query string): /users, /users/42, /search?q=node

Node’s built-in server gives you both. You write the logic that maps them to handlers.

The simplest router is a chain of if statements:

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

When URLs contain path parameters or query strings, use Node’s global URL constructor to parse them cleanly. Pass req.url as the first argument and a fake base as the second:

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Once you have more than a few routes, extract them into a router map. This is exactly the pattern that Express uses internally:

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Which two properties of the request object are used for routing decisions?
What does `new URL(req.url, "http://localhost")` give you?
What HTTP status code should a router return when no route matches?