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.
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.
This is a very basic example, which modifies the request object. It adds the current date and time to the request object, once the date and time are added to the request object, the request is forwarded to the next route.
To use the middleware in the application, app.use() function is used and the name of the middleware function is passed.
In the above example we are setting up the middleware for only ‘/’ route, by passing the middleware function name. In this way we setup middleware according to the routes.