Express: Can I Use Multiple Middleware in a Single App. Use?

I have a lot of apps full of boilerplate code that looks like this:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
        secret: 'keyboard cat',
        resave: false,
        saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

How can I use multiple middleware at once? So I could turn the above into:

// Some file, exporting something that can be used by app.use, that runs multiple middlewares
const bodyParsers = require('body-parsers.js')
const sessions= require('sessions.js')

// Load all bodyparsers
app.use(bodyParsers)

// Load cookies and sessions
app.use(sessions)
5

3 Answers

You can specify multiple middlewares, see the app.use docs:

An array of combinations of any of the above.

You can create a file of all middlewares like -

middlewares.js

module.exports = [
  function(req, res, next){...},
  function(req, res, next){...},
  function(req, res, next){...},
  .
  .
  .
  function(req, res, next){...},
]

and as then simply add it like:

/*
you can pass any of the below inside app.use()
A middleware function.
A series of middleware functions (separated by commas).
An array of middleware functions.
A combination of all of the above.
*/
app.use(require('./middlewares.js'));

Note - Do this only for those middlewares which will be common for all requests

2

I like to use a Router to encapsulate application routes. I prefer them over a list of routes because a Router is like a mini express application.

You can create a body-parsers router like so:

const {Router} = require('express');

const router = Router();

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));
router.use(cookieParser());
router.use(require('express-session')({
        secret: 'keyboard cat',
        resave: false,
        saveUninitialized: false
}));
router.use(passport.initialize());
router.use(passport.session());

module.exports = router;

Then attach it to your main application like any other route:

const express = require('express');

const app = express();
app.use(require('./body-parsers'));
1

Try it like this, in main app.js run just init code:

const bodyParserInit = require('./bodyParserInit');
....
bodyParserInit(app);

And then in bodyParserInit you can do app.use

module.exports = function (app) {
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest