In this blog post we will see how to creating custom middleware for your application.
Middleware are useful very useful in large express application to organize code properly. This help to create modules in application and organize code better.
To create a middleware first create a new js file. Let’s say mod.js
Here is the code to write in it
module.exports = function () {
return function (req, res, next) {
//processing here
//assign variables to req if needed
//req.
next(); //call next middleware
}
}
This is a basic implementation of express middleware.
To use this.
var mod = require('./mod.js');
app.use(mod());
If you need pass some parameter into a middleware
module.exports = function (param) {
var local_param = param;
return function (req, res, next) {
if(param){
//do processing
}
next(); //call next middleware
}
}
To use this.
var mod = require('./mod.js');
app.use(mod(true));
That how simple creating express middleware is and its mainly used to modularize your code. Operations like error logging, mongodb models, common functions etc can easily be modularized using middleware.