HomeBack-End & DatabaseExpressJS Creating Custom Middileware

ExpressJS Creating Custom Middileware

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
[js]
module.exports = function () {
return function (req, res, next) {
//processing here
//assign variables to req if needed
//req.
next(); //call next middleware
}
}
[/js]

This is a basic implementation of express middleware.

To use this.
[js]
var mod = require(‘./mod.js’);
app.use(mod());
[/js]

If you need pass some parameter into a middleware

[js]
module.exports = function (param) {
var local_param = param;
return function (req, res, next) {
if(param){
//do processing
}
next(); //call next middleware
}
}
[/js]

To use this.
[js]
var mod = require(‘./mod.js’);
app.use(mod(true));
[/js]

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.

%d bloggers like this: