Middleware in Express is a function that can access the request object (req), response object (res), and the next middleware function in the application's request/response cycle. This next middleware function is typically represented by a variable named next.
The core functionalities of middleware include:
- Executing arbitrary code.
- Modifying the request and response objects.
- Terminating the request/response cycle.
- Invoking the next middleware in the stack.
If the current middleware does not terminate the request/response cycle, it must call next() to pass control to the subsequent middleware; otherwise, the request will hang indefinitely.
An Express application is constructed from a sequence of middleware function calls. These functions can perform the following tasks:
- Execute code and modify input/output.
- Validate request data.
- Handle cleanup after the request.
- Extend the Express framework with additional functionality.
Example
Suppose we want to log all incoming requests; we can implement the following middleware:
javascriptconst express = require('express'); const app = express(); // Logging middleware app.use((req, res, next) => { console.log(`${new Date().toISOString()} - ${req.method} request to ${req.url}`); next(); // Proceed to the next middleware }); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
In this example, the middleware first logs the timestamp, HTTP method, and URL of the request, then calls next() to continue processing the chain. If next() is omitted, the request terminates prematurely, and the client receives no response.