Chained Route Handlers

Use app.route() to attach several methods to a single path without repeating it.

Syntaxapp.route(path).get(...).post(...)

When one path supports several methods, app.route() lets you chain them so you write the path only once. This keeps related handlers together and reduces mistakes.

The router version, router.route(), works the same way inside a router module.

Example

Example · javascript
app.route('/books')
  .get((req, res) => res.send('List books'))
  .post((req, res) => res.send('Add a book'));

app.route('/books/:id')
  .get((req, res) => res.send('Show book ' + req.params.id))
  .put((req, res) => res.send('Update book ' + req.params.id))
  .delete((req, res) => res.send('Delete book ' + req.params.id));

When to use it

  • A REST resource for /products/:id chains GET, PUT, and DELETE on a single route() call to keep related handlers co-located.
  • A team uses route().all() to apply authentication to all methods on a resource path before individual method handlers run.
  • A developer prefers chained routes over three separate app.get/put/delete calls to reduce repetition of the same path string.

More examples

Chaining GET POST on a path

Calls app.route() once for /books and chains .get() and .post() to avoid repeating the path string.

Example · js
app.route('/books')
  .get((req, res) => {
    res.json([{ id: 1, title: 'Express in Action' }]);
  })
  .post((req, res) => {
    res.status(201).json({ created: true });
  });

Full CRUD on a resource

Chains all four methods on the same parameterised path, covering the full CRUD surface for a single article.

Example · js
app.route('/articles/:id')
  .get((req, res) => res.json({ id: req.params.id }))
  .put((req, res) => res.json({ updated: true }))
  .patch((req, res) => res.json({ patched: true }))
  .delete((req, res) => res.status(204).send());

Chained route with .all() guard

Uses .all() at the top of the chain to enforce an admin check before any HTTP method handler runs.

Example · js
app.route('/admin/settings')
  .all((req, res, next) => {
    if (!req.user?.isAdmin) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    next();
  })
  .get((req, res) => res.json({ theme: 'dark' }))
  .post((req, res) => res.json({ saved: true }));

Discussion

  • Be the first to comment on this lesson.