express: passing middleware as an array does not work

var middleware = [loadForum, loadThread];

app.get('/forum/:fid/thread/:tid', middleware, function(){
  // ...
})

the above part gives me the following error:

Error: Route.use() requires callback functions but got a [object Array]

It works fine if i pass the middleware like this:

app.get('/forum/:fid/thread/:tid', loadForum, loadThread, function(){
  // ...
})

According to the 4.x docs, the array should be flattened by express, but it doesn’t seem to work as intended

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 16 (8 by maintainers)

Most upvoted comments

@php-workx @agauniyal an array of middleware is still supported:

var express = require('express')
var app = express()

var apple = function (req, res, next) {
  console.log('apple')
  next()
}

var book = function (req, res, next) {
  console.log('book')
  next()
}

var cat = function (req, res) {
  console.log('cat')
  res.send('HELLO!')
}

app.get('/', [apple, book, cat])

app.listen(3000, function () { console.log('READY!') })

I use arrays of middleware too without issues.

Yea, the array thing and the accepting multiple functions is an inconsistency. I might actually want to remove them both now that I think about it.

For routes, you don’t need arrays cause you can just do what you showed above. And for the .use case, you can just create a router to provide multiple middleware for a particular subpath.

app.use('/foo', middleware1, middleware2);

Would now be:

var router = express.Router();
router.use(middleware1);
router.use(middleware2);

app.use('/foo', router);

Thoughts @visionmedia @jonathanong ?