Thuta Learning
Node.js
IntermediateWeb DevelopmentBeginner

Express Routing

Node.jsLesson 1230 min

What you'll walk away with

  • Tell apart req.params, req.query and req.body by where each comes from in the request
  • Group a resource's routes with express.Router() and mount them under a path prefix
  • Return accurate status codes, such as 404 for a missing item and 201 for a created one
  • Explain how an async handler's error reaches the error middleware in Express 5

Explain it simply

Explain it simply

Routing is like sorting mail at a post office. An envelope marked "GET /products/15" is sent to a department based on its method (GET) and address (/products/15). /products/15, /products/16 and /products/99 all go to the same department, which reads the number from the address to find the item.

In Express you write that "number slot" as /products/:id and organize departments with express.Router(). Notes on the envelope such as ?maxPrice=30 are the query string, and the letter inside, the JSON sent with a POST, is the request body.

Problem → Why → Solution

The problem: one route per id

Say you route a ten-product shop by writing /products/1, /products/2 and so on, one by one. Every new product means editing code and redeploying. In the POST route, reading req.body fails with "TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined". And once there are hundreds of routes, keeping them all in one app.js becomes a problem of its own.

shop.js
app.get('/products/1', (req, res) => res.json(products[0]));
app.get('/products/2', (req, res) => res.json(products[1]));
// ...one route per product, forever

app.post('/products', (req, res) => {
  const { name, price } = req.body;   // TypeError: req.body is undefined
  res.json({ name, price });          // (express.json() was never added)
});

Why does this happen?

The changing part of the URL, the id, was written as individual values instead of a pattern. One route parameter such as :id catches every id with a single route. The body arrives as a stream, so Express does not read it on its own: only the express.json() middleware parses JSON into req.body. Without a body parser req.body is undefined, and in Express 5 it also stays undefined when express.json() runs but the request has no JSON body.

Core concept: three parts of a request, and the Router

A route is written as app.METHOD(path, handler), and Express picks the first route whose method and path both match. A path segment starting with : is a route parameter: /products/:id matches /products/15 and sets req.params.id to '15'. Parameter values are always strings, so convert with Number() before comparing against numeric ids, because '15' === 15 is false. A parameter never crosses a /, so /products/:id does not match /products/1/reviews.

Data can come from three places in a request. req.params holds the :name segments from the path, req.query holds the query string after ? (/products?maxPrice=30 gives { maxPrice: '30' }), and req.body holds the body sent with POST, PUT or PATCH. The usual convention: params pick a resource (which product), query filters, sorts or pages a list, and body carries new data. The body is only available after app.use(express.json()).

express.Router() is a mini app that groups routes. You write router.get('/:id') without the prefix, mount it with app.use('/products', router), and Express adds /products in front. That lets each resource keep its routes in its own file, such as products.js and users.js.

Each method carries its own meaning: GET reads, POST creates, PUT replaces a whole item, PATCH changes part of it, and DELETE removes it. So one path such as /products/:id can have three separate handlers, router.get(), router.put() and router.delete(), and Express chooses between them by method.

A middleware with four parameters, (err, req, res, next), is an error handler. When a handler calls next(err), throws synchronously or, in Express 5, returns a rejected Promise from an async function, Express skips the remaining routes and goes straight to it. In Express 4 you had to try/catch async errors and call next(err) yourself, or the request was left hanging.

Mental model: method + path picks a handler
  1. Strip the mount prefix (/products)
  2. Match the rest against each pattern
  3. :id -> req.params, ?x -> req.query
  4. On error, jump to the 4-arg handler

params and query values are always strings; body values keep the JSON types that express.json() parsed.

General pattern

javascript
const router = express.Router();

router.get('/', handler);          // GET    /prefix?key=value -> req.query
router.get('/:param', handler);    // GET    /prefix/abc       -> req.params
router.post('/', handler);         // POST   /prefix + body    -> req.body

app.use(express.json());           // parse JSON bodies first
app.use('/prefix', router);        // mount the router
app.use((err, req, res, next) => { /* one place for errors */ });

Router paths are relative to the mount prefix. Put express.json() above the router and the error handler below everything else.

Example: a products router

One router holds a list route filtered by a query, a route that finds one product by :id, a POST route that creates a product from a JSON body, and an async route that throws. Five fetch requests print each status and body. Watch the last line: the async error comes out of the error handler as a 500 JSON response.

products.mjs
import express from 'express';

const products = [
  { id: 1, name: 'Keyboard', price: 45 },
  { id: 2, name: 'Mouse', price: 20 },
];
async function loadReviews(id) {
  throw new Error(`Review service is down (product ${id})`);
}

const router = express.Router();
router.get('/', (req, res) => {
  const max = Number(req.query.maxPrice ?? Infinity);
  res.json(products.filter((p) => p.price <= max));
});
router.get('/:id', (req, res) => {
  const product = products.find((p) => p.id === Number(req.params.id));
  if (!product) return res.status(404).json({ error: 'Product not found' });
  res.json(product);
});
router.post('/', (req, res) => {
  const { name, price } = req.body;
  const product = { id: products.length + 1, name, price: Number(price) };
  products.push(product);
  res.status(201).json(product);
});
router.get('/:id/reviews', async (req, res) => {
  res.json(await loadReviews(req.params.id)); // Express 5 forwards the rejection
});

const app = express();
app.use(express.json());
app.use('/products', router);
app.use((err, req, res, next) => res.status(500).json({ error: err.message }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const call = async (method, path, body) => {
    const res = await fetch(base + path, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: body && JSON.stringify(body),
    });
    console.log(`${method} ${path} -> ${res.status} ${await res.text()}`);
  };
  await call('GET', '/products?maxPrice=30');
  await call('GET', '/products/2');
  await call('GET', '/products/99');
  await call('POST', '/products', { name: 'Monitor', price: 150 });
  await call('GET', '/products/1/reviews');
  server.close();
});

Code breakdown

  1. Query stringconst max = Number(req.query.maxPrice ?? Infinity);

    ?maxPrice=30 arrives as the string '30', so Number() converts it. Without the query, Infinity is used and every product is returned.

  2. Route parameter + 404if (!product) return res.status(404).json({ error: 'Product not found' });

    Product 99 does not exist, so it answers 404; the return stops the res.json(product) below from also running.

  3. JSON bodyconst { name, price } = req.body;

    express.json() already parsed the body. Picking fields by name stops extra fields the client sends, such as its own id, from reaching the new object.

  4. 201 Createdres.status(201).json(product);

    Creating something answers 201 instead of 200 and returns the new object, including its new id.

  5. Async errorres.json(await loadReviews(req.params.id)); // Express 5 forwards the rejection

    loadReviews() rejects, so the handler's Promise rejects too. Express 5 calls next(err) for you and the error handler answers with a 500 JSON body, with no try/catch needed.

  6. Error handlerapp.use((err, req, res, next) => res.status(500).json({ error: err.message }));

    Four parameters mark it as an error handler. next is unused but cannot be removed: with three parameters it would become ordinary middleware.

You should see
GET /products?maxPrice=30 -> 200 [{"id":2,"name":"Mouse","price":20}]
GET /products/2 -> 200 {"id":2,"name":"Mouse","price":20}
GET /products/99 -> 404 {"error":"Product not found"}
POST /products -> 201 {"id":3,"name":"Monitor","price":150}
GET /products/1/reviews -> 500 {"error":"Review service is down (product 1)"}

Express 5 path syntax

Express 5 uses a newer path-to-regexp, so some patterns from older Express 4 tutorials no longer work. Wildcards must be named (/files/*splat) and optional parts are written with {}. Writing an unnamed * such as app.get('/a/*', ...) throws a "Missing parameter name" error as soon as the app starts.

PatternMatching URLreq.params
/users/:id/users/7{ id: '7' }
/files/*splat/files/a/b/c{ splat: ['a', 'b', 'c'] }
/posts{/:slug}/posts and /posts/hello{} / { slug: 'hello' }

In real projects

Where this shows up in real projects

In a REST API, each resource (users, orders, products) gets its own router file, and app.js contains little more than mount lines such as app.use('/api/users', usersRouter). List endpoints such as GET /api/orders?status=paid&page=2 read filters and pagination from the query, and GET /api/orders/:id returns one order. Following the same status-code rules across the whole API, 201 for POST, 404 for missing, 400 for bad data, matters a great deal to the frontend developers who call it.

A single error handler pays off in production too. Policies such as sending every error to a logging service while showing clients a generic message instead of a stack trace live in one place. Thanks to Express 5's async error forwarding, routes that query a database no longer need the same try/catch repeated in each one.

Common mistakes

Common mistakes

1. Comparing req.params.id to a number with ===

products.find((p) => p.id === req.params.id) compares '2' === 2, never matches, and returns 404 for every id. Convert with Number(req.params.id), check it with Number.isInteger(), and answer 400 when it is not a valid id.

2. Putting a specific route below a :param route

With router.get('/:id') above router.get('/featured'), /products/featured matches the first route with :id = 'featured', so the featured route is never reached. Register fixed paths above parameter routes.

3. Writing the error handler with three parameters

With (err, req, res) => ..., Express counts the parameters, treats it as ordinary middleware, and errors fall through to the default HTML error page. Write all four parameters even if next goes unused.

Best practices

Best practices

  • Use plural nouns in paths (/products, /orders) and express the action with the method, not with paths like /getProducts.
  • Convert and validate every value from params, query and body, and answer 400 with a reason when it is wrong.
  • Give each resource its own router file and leave only mount lines in app.js.

Mini challenge

Mini challenge: a todos router

Write a todo-list API as a router mounted at /api/todos, and test it with six fetch requests.

  • GET / returns all todos, or only finished ones with ?done=true
  • GET /:id returns one todo, or 404 if it does not exist
  • POST / returns 400 without a title, otherwise 201 and the new todo
  • DELETE /:id returns 204 with no body, or 404 if it does not exist
todos.mjs
import express from 'express';

const todos = [{ id: 1, title: 'Learn routing', done: true },
  { id: 2, title: 'Build an API', done: false }];
const todosRouter = express.Router();

// TODO: GET    /        (?done=true filter; query values are strings)
// TODO: GET    /:id     (404 when missing)
// TODO: POST   /        (400 without title, else 201)
// TODO: DELETE /:id     (204, or 404 when missing)

const app = express();
// TODO: express.json(), then mount todosRouter at /api/todos

const server = app.listen(0, async () => {
  // TODO: send the six requests, print "<METHOD> <path> -> <status> <body>", close
});

Expected: Expected output: GET /api/todos?done=true -> 200 [{"id":1,"title":"Learn routing","done":true}] GET /api/todos/2 -> 200 {"id":2,"title":"Build an API","done":false} POST /api/todos -> 400 {"error":"title is required"} POST /api/todos -> 201 {"id":3,"title":"Write tests","done":false} DELETE /api/todos/1 -> 204 GET /api/todos/1 -> 404 {"error":"Todo not found"}

Show hint

req.query.done is the string 'true', so test req.query.done === 'true'. For a bodiless 204 use res.sendStatus(204) or res.status(204).end(). findIndex() plus splice() handles the delete.

Show solution
todos.mjs
import express from 'express';

const todos = [{ id: 1, title: 'Learn routing', done: true },
  { id: 2, title: 'Build an API', done: false }];
let nextId = 3;
const todosRouter = express.Router();

todosRouter.get('/', (req, res) => {
  const onlyDone = req.query.done === 'true';
  res.json(onlyDone ? todos.filter((t) => t.done) : todos);
});
todosRouter.get('/:id', (req, res) => {
  const todo = todos.find((t) => t.id === Number(req.params.id));
  if (!todo) return res.status(404).json({ error: 'Todo not found' });
  res.json(todo);
});
todosRouter.post('/', (req, res) => {
  const title = req.body?.title;
  if (!title) return res.status(400).json({ error: 'title is required' });
  const todo = { id: nextId++, title, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});
todosRouter.delete('/:id', (req, res) => {
  const index = todos.findIndex((t) => t.id === Number(req.params.id));
  if (index === -1) return res.status(404).json({ error: 'Todo not found' });
  todos.splice(index, 1);
  res.sendStatus(204);
});

const app = express();
app.use(express.json());
app.use('/api/todos', todosRouter);

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const requests = [['GET', '/api/todos?done=true'], ['GET', '/api/todos/2'],
    ['POST', '/api/todos', {}], ['POST', '/api/todos', { title: 'Write tests' }],
    ['DELETE', '/api/todos/1'], ['GET', '/api/todos/1']];
  for (const [method, path, body] of requests) {
    const res = await fetch(base + path, {
      method,
      headers: { 'Content-Type': 'application/json' },
      body: body && JSON.stringify(body),
    });
    console.log(`${method} ${path} -> ${res.status} ${await res.text()}`);
  }
  server.close();
});

Quick quiz 1 / 3

router.get('/:id', ...) is mounted with app.use('/books', router). For GET /books/42?format=pdf, what does the handler see?

Quick quiz 2 / 3

Without app.use(express.json()), what is req.body inside an Express 5 POST handler?

Quick quiz 3 / 3

In Express 5, an async route's await db.find() rejects. What is needed for the error to reach the error handler?

What to remember

  • The first route whose method and path both match answers the request.
  • req.params holds :name path segments, req.query the string after ?, and req.body the body parsed by express.json().
  • Group each resource's routes with express.Router() and mount them with app.use('/prefix', router).
  • In Express 5, async errors reach the (err, req, res, next) handler automatically.

Routing — Express.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Express Routing | Thuta Learning