What is the most common way to use a middleware in node with express and connect
- by Bernhard
Thinking about the correct way, how to make use of middlewares in a node.js web project using express and connect which is growing up at the moment.
Of course there are middlewares right now wich has to pass or extend requests globally but in a lot of cases there are special jobs like prepare incoming data and in this case the middleware would only work for a set of http-methods and routes.
I've a component based architecture and each component brings it's own middleware layer which can implement those for requests this component can handle. On app startup any required component is loaded and prepared. Is it a good idea to bind the middleware code execution to URLs to keep cpu load lower or is it better to use middlewares only for global purposes?
Here's some dummy how an url related middleware look like.
app.use(function(req, res, next) {
// Check if requested route is a part of the current component
// or if the middleware should be passed on any request
if (APP.controller.groups.Component.isExpectedRoute(req) ||
APP.controller.groups.Component.getConfig().MIDDLEWARE_PASS_ALL === true) {
// Execute the midleware code here
console.log('This is a route which should be afected by middleware');
...
next();
}else{
next();
}
});