[Fixed] 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.


It’s not saying "infinitely", but it does say that you can add multiple middleware functions (called "callbacks" in the documentation) here:

router.METHOD(path, [callback, …] callback)

You can provide multiple callbacks, and all are treated equally, and behave just like middleware, except that these callbacks may invoke next(‘route’) to bypass the remaining route callback(s). You can use this mechanism to perform pre-conditions on a route then pass control to subsequent routes when there is no reason to proceed with the route matched.

As you can see, there’s not distinction between a middleware function and the function that commonly handles the request (the one which is usually the last function added to the list).

Having 10 shouldn’t be a problem (if you really need to).

Leave a Reply

(*) Required, Your email will not be published