Middleware functions 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. (official document)
Do you understand anything of it ?
In short, normally we use middleware to checking something. Like – if anyone is a authentic user or is the user is admin.
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 function in the stack.
An Express application can use the following types of middleware:
– Application-level middleware
– Router-level middleware
– Error-handling middleware
– Built-in middleware
– Third-party middleware
You can check the more details – https://expressjs.com/en/guide/using-middleware.html
Let’s use a middleware
we have 3 elements here – request, response and next cycle here. In the middleware we just console log the time. So when we’ll call the route, this function will be called always.
See the result when we hit the url –