What is middleware and how it works?
What is middleware?
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 per it’s name, middleware comes in the middle of the request-response cycle.
What is request-response cycle?

When any client/user request any data from server to till the client/user get the final response, this whole process known as the request-response cycle.
What middleware can do?
- Execute any operation coded in the method.
- Make changes to the request and the response objects.
- End the request-response cycle. For example, if there is any exception is thrown, instead of calling the next method in the series of middleware, it can end the chain.
- Call the next middleware function in the stack.
How it works?

In the above diagram we can see we have multiple middleware functions in the request-response cycle.
In the diagram we have 5 middleware which called as middleware stack.
When express get the request it has request object and response object. Which get passed to middleware, middleware can process it by modifying request or by doing any other activity which may not modify request i.e. printing logs. Now when we call next() at the end of any middleware it call the next middleware.
As we can see in the middleware stack diagram, when middleware 1 call next() it get to middleware 2 which will contain request object and response object which are forwarded by middleware 1 then middleware 3 get called and at the end we reach to middleware 5 where we will have final request object and response object which will then use res.send() instead of next() to end the request-response cycle by providing the final response to user.
If we forgot to use next() (except in the last middleware/route as route it self is a middleware) at the end of any middleware then we will stuck there only.
here please take care of the order of your middleware as they will execute in the sequence of what they are called/written.
Types of middlewares
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
Application-level middleware
This kind of middleware apply to all requests come to the app i.e. authentication and authorization or add start time to any request. Make sure to use such middleware before using any route.
Example:

Router-level middleware
Router level middleware works same as application level except that it is applicable to only routes in which we pass that middleware.
Example

In above code spinet we can see that we have startTime middleware only for v2 route. Now when we use the v1 route in the above screenshot we can see that the req beginning time is undefined, but when we have used v2 we can see req beginning time and we got time taken by the v2 route using the req beginning time.
Error-handling middleware
In error handling middleware we will have one extra argument then application and router level middleware (i.e req, res, next) which is error.


We should add our error handler middleware after all other routes, so if we get any error and we want to throw it using our error handler then with the next() it will get to the error handler and if we did not get any error then we will use res.send() so it will provide final response and close the request.
Built-in middleware
Express has the following built-in middleware functions:
- express.static serves static assets such as HTML files, images, and so on.
- express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
- express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+
Here we need to create a folder public in the level of our index.js file. Now to access images/css/JS files we can use their name with path.

We can see in the above screenshot the URL is http://localhost:8000/nature-1.jpg, I have used the image name after the domain. So if I have created different folders for images and CSS then I can use them i.e. http://localhost:8000/images/nature-1.jpg. We have no need to include the public folder name but we need to use the folder/file name which are in public folder.
Third-party middleware
There are a number of third party middleware, such as body-parser, mongoose, morgan and so on. These can be installed by using command
npm install <module name>
Then we can use them in code. Below we have an example of body parser, which will parse incoming request bodies in a middleware before your handlers, available under the req.body
property.
Conclusion
Middleware functions are a really great to use in our development with express as it can run code on each request, or on each request for a certain route, and to take action on request or response data.