Express routing and middleware

Beginner · 34 min

How Express 5 matches routes, runs the middleware chain with next(), organises routes with Router, and what changed in route path syntax.

Before thisThe http module and building a server

Traversy Media · 106 min · from 26:30

Express routing and middleware

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Traversy MediaReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Express is a router plus a middleware chain on top of `node:http`. A request passes through matching handlers in the order they were registered, and each either responds or calls `next()`.
  • A middleware is `(req, res, next)`. Call `next()` to continue, call `next(err)` to jump to error handling, or send a response and stop. Never do both, and never do neither.
  • `app.use(fn)` runs for every method on matching paths; `app.get(path, ...handlers)` matches one method and path. Order matters: register parsers and logging before the routes that need them.
  • `express.Router()` is a mini application. Mount it with `app.use('/api/items', router)` to group routes under a prefix with their own middleware.
  • Express 5 uses path-to-regexp 8: wildcards must be named (`/files/*splat`), optional segments use braces (`/opt{/:lang}`), regex inside parameters is gone, and `req.query` is a read-only getter with the `simple` parser by default.

What Express adds to http

In the http lesson you matched routes with if statements and parsed bodies by hand. Express packages exactly those jobs. It gives you a way to say “for GET on /users/:id, run this function”, a way to run shared code (logging, body parsing, auth) before handlers, and nicer req and res objects (res.json, req.params). Under the hood it is still createServer and the same streams.

Express 5 is the current major version (5.3 at the time of writing, and latest on npm). The code below runs on it.

Routes

import express from 'express';
const app = express();

app.get('/users/:id', (req, res) => res.json({ id: req.params.id, q: req.query }));

A request to /users/7?x=1&y=2 returned {"id":"7","q":{"x":"1","y":"2"}}. Route parameters are always strings; convert them yourself. app.get, app.post, app.put, app.patch and app.delete match one HTTP method and path. Express 5 removed app.del.

The path syntax changed in Express 5, because it moved to a newer path-to-regexp:

app.get('/files/*splat', (req, res) => res.json({ splat: req.params.splat }));
// /files/a/b/c.txt  ->  { splat: ['a', 'b', 'c.txt'] }

app.get('/opt{/:lang}', (req, res) => res.json({ lang: req.params.lang ?? null }));
// /opt -> null, /opt/en -> 'en'

A bare * ('/old*') now throws Missing parameter name at startup, and so does a regex in a parameter such as '/posts/:id(\\d+)', which fails with Unexpected (. Validate the format inside the handler instead. Two other Express 5 details: req.query is a getter you cannot assign to (assigning threw a TypeError in a strict module), and the default query parser is simple, so ?a[b]=1 is not expanded into a nested object unless you opt into extended.

The middleware chain

A middleware is a function (req, res, next). Express keeps an ordered list of them and runs the matching ones in turn:

app.use((req, res, next) => { console.log(req.method, req.url); next(); });
app.use(express.json());           // parses JSON bodies into req.body
app.get('/users/:id', handler);
app.use((req, res) => res.status(404).json({ error: 'not found' })); // fell off the end

Each middleware has three choices: respond (ending the chain), call next() (continue to the next match), or call next(err) (skip to the error handlers). The two bugs are doing neither, which leaves the request hanging, and doing both, which tries to send twice.

Order matters. express.json() must come before the routes that read req.body. In Express 5, req.body is undefined when no parser ran, not {}. The 404 catch-all goes last, because it matches everything. A path can be given to use, as in app.use('/admin', requireAuth), so the middleware only runs for URLs under that prefix.

One more tool: next('route') skips the rest of the current route’s handlers and continues matching later routes. And app.param('uid', fn) runs a function whenever a route has a :uid parameter, which is handy for loading and converting a value once.

Routers

As the app grows, group related routes:

const router = express.Router();
router.use((req, res, next) => { /* runs for this router only */ next(); });
router.get('/', (req, res) => res.json({ list: true }));
router.get('/:id', (req, res) => res.json({ one: req.params.id }));
app.use('/api/items', router);

/api/items and /api/items/9 both reach the router, which sees / and /9 because the mount path is stripped (req.originalUrl keeps the full path). A router is a self-contained middleware stack, so it carries its own use calls. I ran these on Express 5.3: the router middleware executed only for /api/items requests.

What the video covers

This lesson uses a clip of Brad Traversy’s May 2024 “Express Crash Course”, from 26:30 to 1:00:24. By its chapter list, that covers request params, query strings, setting status codes, route files, ES modules, request body data, POST, PUT and DELETE requests, and an introduction to middleware. The video’s full chapter list also has custom error handling (1:00:24) and controllers (1:14:17), which the next lessons use. It was published before Express 5 became the default, so it was written against Express 4. Its route syntax and middleware flow are mostly the same, but the wildcard, regex-parameter, req.query and req.body points above are the Express 5 differences. I could not read a transcript.

Where this fits

Middleware is the pattern behind everything in Express: parsing, CORS, auth and error handling are all (req, res, next) functions. Next: error handling and async routes, then building a REST API. For REST resource design itself, see REST resource modeling and URI design.

Check yourself

  1. 01A request to `/api/items/9` hits a router mounted with `app.use('/api/items', router)` and `router.get('/:id', ...)`. What is `req.params.id`, and what is `req.url` inside the router?

    `req.params.id` is the string `'9'`. Inside the router, `req.url` is `/9`, because the mount path is stripped so the router sees paths relative to where it was mounted. `req.originalUrl` still holds the full `/api/items/9`.

  2. 02Your logging middleware is registered after the route that handles `/users`. Why does it never log those requests?

    Express runs handlers in registration order, and the route responded without calling `next()`, so the middleware after it never ran. Register logging, body parsers and auth before the routes they apply to.

  3. 03What does `next('route')` do?

    It skips the remaining handlers of the current route and moves on to the next matching route. In a test with two `app.get('/skip', ...)` registrations, the first used `next('route')` and the second route answered.

  4. 04You upgrade to Express 5 and `app.get('/old*', ...)` throws at startup. What changed and how do you write it now?

    Express 5's path-to-regexp requires wildcards to have a name, so a bare `*` is an error (`Missing parameter name`). Use a named wildcard like `/old*splat`. Its value comes back as an array, for example `['a', 'b', 'c.txt']` for `/files/a/b/c.txt`.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark