Node JS middlewares at a glance

Anupam Roy
3 min readMay 13, 2020

--

Middleware functions are functions that have access to the request object req, the response object res, and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

A web server can be seen as a function that takes in a request and outputs a response. Middlewares are functions executed in the middle after the incoming request then produces an output which could be the final output passed or could be used by the next middleware until the cycle is completed, meaning we can have more than one middleware and they will execute in the order they are declared.

Anatomy of an Express Middleware

function myCustomMiddleware(req, res, next) {
// custom middleware here…
}

Middleware functions can perform the following tasks:

- Execute any code.

- Make changes to the request and the response objects.

- End the request-response cycle.

- Call the next middleware in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Using a middleware

  1. You can then use the middleware in various ways, the simplest being globally for all your routes:
var app = express()
app.use(myCustomMiddleware)
// normal route Handlers
app.get('/someroute', handler)
...

2. Second option is to include it only for a specific path:

app.use('/withmiddleware', myMiddleware)

3. Third option can be using it directly in the route handler:

//middlewares passed as array in second argument to a route definition
app.get('/someroute', [myMiddleware], handler)

Middleware chaining

Chaining of middleware allows you to compartmentalize your code and create reusable middlewares.

The middlewares will get executed in the order of their use calls or their order in the array. They will receive the augmented Request object from previous middlewares, so they can depend on each others functionality, like your custom middleware being inserted after bodyParser and thereby being able to use the parsed body.

List of commonly used middlewares:

Conclusion:

Middleware literally means anything you put in the middle of one layer of the software and another. Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it’s attached to.

Thanks for reading the article, do give a clap if you find this article helpful.

--

--