Middleware in Express Applications
Middleware in Express Applications

It’s not nearly as complicated as it sounds

Photo by Quinten de Graaf on Unsplash.

One of the core concepts of an Express application is middleware, and most of us get confused by it.

First of all, think of middleware as a simple function that will take a request object and pass control to the next middleware function or send a response to the client.

One of the simplest examples of middleware is the route handler function in the Express framework. Those who already have some knowledge of the Express framework are familiar with the following code:

app.get('/', (req, res) => {

res.send({ id: 1, name: 'Ashraful' });

}

In the case above, the get function takes a request and sends a response to the client.

Another example is to get the JSON object from the body of the request we wrote:

app.use(express.json())

express.json() parses the body of the request and sets the object in req.body in the route handler. Here, express.json() returns a middleware function.

We can easily understand the request and response cycle with the following diagram:

Request-response pipeline in Express

Think of it as a pipeline. On one side of that pipeline, we will have our request object. On another side, there will be the response object. In between the request and response, we can place some middleware.

Express comes with some built-in middleware functions. But we can also create custom middleware functions that we can place in between middleware functions to perform some operations. A good example would be performing authentication and authorization with custom middleware.
['Ashraful Islam']
['JavaScript', 'Programming', 'Nodejs', 'Expressjs', 'Web Development']