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)
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
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With