NodeJS Express middleware abstraction

George Tsopouridis
Jul 24, 2017 · 1 min read

NodeJS Express https://expressjs.com/ is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls.

Middleware functions https://expressjs.com/en/guide/using-middleware.html are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Abstraction

Middleware is flexible. You can use anonymous or named functions, but the best thing is to abstract request handlers into external modules based on the functionality. Even this is straightforward, sometimes we need to pass a param(s) to the exported module functions. Param could be even a callback function. You can find below a simple example.

./middlewares/middleware.js

requiredParamHandler = function(param) {
return function (req, res, next) {
// Use param
}
}
exports.requiredParamHandler = requiredParamHandler;

app.js

let middleware = require('./middlewares/middleware');app.get('/api/v1', middleware.requiredParamHandler(param));

George Tsopouridis

Written by

Software Architect at Sunrise Communications AG, Zurich, CH - Envato Author https://codecanyon.net/user/gtsopour/portfolio - Github https://github.com/gtsopour

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade