'Chaining multiple pieces of middleware for specific route in ExpressJS

I want to just verify something but have't been able to find anything in the Express docs or online regarding this (although I know it's a feature).

I could just test this out but I don't really have a nice template and would like to hear from the community.

If I define a route in express like such:

app.get('/', function (req, res) {
  res.send('GET request to homepage');
});

I can also define a middleware and load it directly, such as

middleware = function(req, res){
  res.send('GET request to homepage');
});

app.get('/', middleware)

However, I can also chain at least one of these routes to run extra middleware, such as authentication, as such:

app.get('/', middleware, function (req, res) {
  res.send('GET request to homepage');
});

Are these infinitely chainable? Could I stick 10 middleware functions on a given route if I wanted to? I want to see the parameters that app.get can accept but like mentioned I can't find it in the docs.



Solution 1:[1]

Consider following example:

const middleware = {
    requireAuthentication: function(req, res, next) {
        console.log('private route list!');
        next();
    },
    logger: function(req, res, next) {
       console.log('Original request hit : '+req.originalUrl);
       next();
    }
}

Now you can add multiple middleware using the following code:

app.get('/', [middleware.requireAuthentication, middleware.logger], function(req, res) {
    res.send('Hello!');
});

So, from the above piece of code, you can see that requireAuthentication and logger are two different middlewares added.

Solution 2:[2]

Express version "express": "^4.17.1" or above

From the document: Series of Middleware

var r1 = express.Router();
r1.get('/', function (req, res, next) {
  next();
});

var r2 = express.Router();
r2.get('/', function (req, res, next) {
  next();
});

app.use(r1, r2);

Let's try a real life example:

tourController.js

 exports.checkBody = (req, res, next)=>{ // middleware 1
    if (!req.body.price){
        return res.status(400).json({
            status:'fail',
            message:'Missing price!!!'
        })
    }
    next();
  }

 exports.createTour = (req, res) => { // middleware 2
    tours.push(req.body);
    fs.writeFile(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours),
      (err) => {
        res.status(201).json({
          status: 'success',
          data: {
            tour: newTour,
          },
        });
      }
    );
  };

tourRouter.js

const express = require('express');
const tourController = require('./../controller/tourController')
const router = express.Router();

router.route('/')
.get(tourController.getAllTours)
.post(tourController.checkBody, tourController.createTour); 
//muliple Middleware in post route

module.exports = router //need this or the following step will break

app.js

const express = require('express');
const tourRouter = require('./route/tourRouter');
const app = express();

app.use(express.json());
app.use('/api/v1/tours', tourRouter);
module.exports = app;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 SamWalker