Introduction
Express is one of the most popular routing frameworks for node.js. No matter whether you are a MERN or MEAN stack developer the “E” remains constant which stands for Express.js. Express is a fast and minimalistic web framework for node.js
Middleware in express.js are the functions that are invoked by the routing layer of express.js before the final request handler. As it is pretty much clear by the name that middleware is a piece of code/function that appears between the two requests and responses.
Middleware is very useful in the development of a website. In this article we will be discussing middleware in detail.
What is Middleware?
According to the express.js official documentation, middleware is defined as-
“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.”
As we discussed earlier, Middleware is the piece of code that sits between request and response. Middleware gets executed when the server receives a request and before the sending of a response. In fact, an express-based application is a series of middleware function calls.
Middleware in express.js 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.
The figure below shows the different elements involved in a middleware function in express.js
Now we are familiar with the basics of the middleware in express, let's discuss middleware chaining.