mikemaccana
mikemaccana

Reputation: 123058

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)

Upvotes: 14

Views: 25975

Answers (3)

Suresh Prajapati
Suresh Prajapati

Reputation: 4457

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

Upvotes: 21

Jake Holzinger
Jake Holzinger

Reputation: 6053

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'));

Upvotes: 7

Ivan Marjanovic
Ivan Marjanovic

Reputation: 1049

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 }));
}

Upvotes: 0

Related Questions