0
0
ExpressHow-ToBeginner · 3 min read

How to Use Route Chaining in Express for Cleaner Code

In Express, route chaining lets you handle multiple HTTP methods on the same route by chaining method calls on app.route(path). This keeps your code organized by grouping handlers for GET, POST, PUT, DELETE, etc., on one route.
📐

Syntax

The app.route(path) method creates a route object for the specified path. You can then chain HTTP method handlers like .get(), .post(), .put(), and .delete() on this route object. Each method takes a callback function that handles the request and response.

This pattern groups all handlers for one route together, making your code cleaner and easier to read.

javascript
app.route('/example')
  .get((req, res) => {
    res.send('GET request to /example');
  })
  .post((req, res) => {
    res.send('POST request to /example');
  });
💻

Example

This example shows how to use route chaining to handle GET and POST requests on the same /users path. The GET handler sends a list of users, and the POST handler adds a new user.

javascript
import express from 'express';
const app = express();
app.use(express.json());

const users = [{ id: 1, name: 'Alice' }];

app.route('/users')
  .get((req, res) => {
    res.json(users);
  })
  .post((req, res) => {
    const newUser = req.body;
    users.push(newUser);
    res.status(201).json(newUser);
  });

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

One common mistake is to define separate routes for the same path and HTTP methods instead of chaining them, which can lead to duplicated code and harder maintenance.

Another pitfall is forgetting to call next() or send a response in one of the handlers, causing the request to hang.

javascript
/* Wrong way: separate routes for same path */
app.get('/items', (req, res) => {
  res.send('Get items');
});
app.post('/items', (req, res) => {
  res.send('Add item');
});

/* Right way: route chaining */
app.route('/items')
  .get((req, res) => {
    res.send('Get items');
  })
  .post((req, res) => {
    res.send('Add item');
  });
📊

Quick Reference

  • app.route(path): Creates a route object for chaining.
  • Chain HTTP methods like .get(), .post(), .put(), .delete().
  • Each method takes a callback with req and res.
  • Use route chaining to keep related handlers together.

Key Takeaways

Use app.route(path) to chain multiple HTTP method handlers on the same route.
Route chaining groups related handlers, making code cleaner and easier to maintain.
Each chained method takes a callback function with request and response parameters.
Avoid defining separate routes for the same path and methods to prevent duplication.
Always send a response or call next() in each handler to avoid hanging requests.