TExcelTAD
Home › Express & NestJS › Express Routing

Express Routing

A route is a combination of an HTTP method, a path and one or more handler functions. Routing decides which code runs for GET /books versus DELETE /books/7.

Methods

Express has a method for every HTTP verb, plus app.all() for "any method":

Method Typical use
app.get(path, fn) read a resource
app.post(path, fn) create a resource
app.put(path, fn) replace a resource
app.patch(path, fn) partially update a resource
app.delete(path, fn) delete a resource
app.all(path, fn) every method — useful for shared checks

HEAD requests are answered automatically by your GET routes (without a body), and OPTIONS gets an automatic reply listing the allowed methods.

node · try it yourself
const express = require('express');

const app = express();

app.get('/tasks', (req, res) => res.json({ action: 'list tasks' }));
app.post('/tasks', (req, res) => res.status(201).json({ action: 'create task' }));
app.delete('/tasks', (req, res) => res.json({ action: 'delete all tasks' }));

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/tasks`;
  for (const method of ['GET', 'POST', 'DELETE', 'PUT']) {
    const res = await fetch(url, { method });
    console.log(method.padEnd(6), res.status, res.status === 404 ? '(no route)' : await res.text());
  }
  server.close();
});
GET    200 {"action":"list tasks"}
POST   201 {"action":"create task"}
DELETE 200 {"action":"delete all tasks"}
PUT    404 (no route)

Chaining with app.route()

When several methods share a path, app.route() avoids repeating it:

js
app.route('/tasks')
  .get((req, res) => res.json(tasks))
  .post((req, res) => { /* create */ });

Path syntax in Express 5

Express 5 uses a stricter path syntax than v4. Paths are plain strings with a few special forms:

Pattern Matches Notes
/about /about exact (case-insensitive, trailing slash allowed)
/users/:id /users/7, /users/ana named parameter → req.params.id
/files/*path /files/a/b.txt named wildcard → req.params.path is an array of segments
/posts{/:slug} /posts and /posts/hello braces make a part optional
/report.:ext /report.pdf parameters can sit next to literal text

Note: v4 patterns such as /*, /:id? or /ab+cd throw an error in Express 5. Write /*splat, {/:id}, or use a real regular expression instead: app.get(/^\/ab+cd$/, fn).

node · try it yourself
const express = require('express');

const app = express();

app.get('/files/*filepath', (req, res) => res.json({ filepath: req.params.filepath }));
app.get('/posts{/:slug}', (req, res) => res.json({ slug: req.params.slug ?? '(all posts)' }));
app.get('/report.:ext', (req, res) => res.json({ format: req.params.ext }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const path of ['/files/docs/2025/plan.txt', '/posts', '/posts/hello-world', '/report.csv']) {
    const res = await fetch(base + path);
    console.log(path, '->', await res.text());
  }
  server.close();
});
/files/docs/2025/plan.txt -> {"filepath":["docs","2025","plan.txt"]}
/posts -> {"slug":"(all posts)"}
/posts/hello-world -> {"slug":"hello-world"}
/report.csv -> {"format":"csv"}

Order matters

Routes are checked top to bottom, and the first match wins. A parameter route registered too early "steals" requests meant for a literal path:

node · try it yourself
const express = require('express');

const app = express();

app.get('/users/:id', (req, res) => res.json({ route: 'by id', id: req.params.id }));
app.get('/users/me', (req, res) => res.json({ route: 'current user' })); // never reached!

const server = app.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/users/me`);
  console.log(await res.json());
  server.close();
});
{ route: 'by id', id: 'me' }

Fix: register /users/me before /users/:id. Put specific routes first, general ones after.

Several handlers per route

A route can take multiple functions. Each calls next() to pass control to the next one — the basis of middleware, covered in a later lesson:

node · try it yourself
const express = require('express');

const app = express();

const mustBeAdmin = (req, res, next) => {
  if (req.get('x-role') !== 'admin') return res.status(403).json({ error: 'admins only' });
  next();
};

app.delete('/cache', mustBeAdmin, (req, res) => res.json({ cleared: true }));

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/cache`;
  const guest = await fetch(url, { method: 'DELETE' });
  const admin = await fetch(url, { method: 'DELETE', headers: { 'x-role': 'admin' } });
  console.log(guest.status, await guest.text());
  console.log(admin.status, await admin.text());
  server.close();
});
403 {"error":"admins only"}
200 {"cleared":true}

Tip: A route handler that neither responds nor calls next() leaves the client waiting until it times out. Every code path must do one of the two.

Test yourself

Which Express 5 path matches both /docs and /docs/intro?

  1. /docs/:page?
  2. /docs{/:page}
  3. /docs/*
  4. /docs/(:page)

For app.get('/files/*rest', …), what is req.params.rest for /files/a/b.txt?

  1. 'a/b.txt'
  2. ['a', 'b.txt']
  3. 'b.txt'
  4. undefined

/users/:id is registered before /users/me. What does GET /users/me hit?

  1. /users/me
  2. /users/:id with id 'me'
  3. Both handlers
  4. A 404