Stop 05 · Express.js & Web FrameworksTopics · 2/14

Routing

Part of the Backend Developer Roadmap

In short

Your API might have fifty endpoints. Routing is how Express sends each request to the exact piece of code meant for it, and nowhere else.

Mapping HTTP methods and URL paths to handler functions — the core job of any web framework, and the first thing you define for every new endpoint.

The mascot drops letters into a wall of wooden pigeonhole boxes.

Think of it like this

The post office sorting desk

At the sorting desk, every letter is checked for its PIN code and dropped into the right pigeonhole. Wrong slot, wrong city. Express routing checks each request's method and path and drops it into the right handler.

Watch it happen

How Express matches GET /products/7

app
GET
POST
/products
/products/:id
/products
404 fallback

1/5Request GET /products/7 arrives. Express checks routes in the order you added them.

The big ideas

What you need to know

One route per job

app.get, app.post, app.put, app.patch and app.delete each match one HTTP method.

Order matters

Express checks routes top to bottom. Put /products/featured before /products/:id, or :id will grab it.

app.route for one path

app.route("/products").get(list).post(create) keeps all methods for a path together.

End with a 404

A final app.use((req, res) => res.status(404)...) catches anything no route matched.

See it in code

Walk through the code

js
1app.get("/products", (req, res) => res.json(products));2 3app.get("/products/featured", (req, res) => {4  res.json(products.filter((p) => p.featured));5});6 7app.get("/products/:id", (req, res) => {8  res.json(products.find((p) => p.id === req.params.id));9});10 11app.post("/products", (req, res) => res.status(201).json(req.body));12 13app.use((req, res) => {14  res.status(404).json({ error: `No route for ${req.method} ${req.path}` });15});

1/4List all products.

Swap the order of /featured and /:id and GET /products/featured would try to find a product whose id is "featured".

Save yourself the pain

Common mistakes

Oops

Using GET /deleteProduct?id=7 to delete things.

Do this instead

Use the HTTP method for the action: DELETE /products/7. GET requests should never change data.

Oops

Letting unmatched routes return Express's default HTML 404 page in a JSON API.

Do this instead

Add your own final 404 handler that returns JSON, so clients always get the same format.

Your mission

Route a mini catalogue

~20 min

Quick check

Routes are added in order: GET /users/:id, then GET /users/me. What handles GET /users/me?

Go deeper

  1. 1Build routes for all 5 common HTTP methods against one resource.
  2. 2Practice route parameters (`/users/:id`) alongside static routes.
  3. 3Organize related routes into their own router files as the app grows.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge