Middleware Pattern (Express-style)
The Middleware Pattern & Request Lifecycle
The philosophical backbone of Node.js web frameworks (Express, Koa) relies heavily on the Middleware (Chain of Responsibility) pattern. Every incoming HTTP request enters a pipeline of functions sequentially.
The Next Paradigm
Each middleware function has access to the request, response, and the pivotal next callback function. A middleware acts as a discrete, composable unit of logic. If it does not terminate the cycle by sending a response, it must invoke next() to pass control to the subsequent function.
Middleware Categorization
- Application-Level: Executes for all routes globally (e.g., CORS definitions, JSON payload parsers).
- Route-Level: Bound specifically to individual endpoints (e.g., Role-based access validation).
- Error-Handling: Distinguished exclusively by accepting four arguments
(err, req, res, next). These intercept any errors passed down the pipeline vianext(err).