Middleware & Request Pipelines
The problem
Many concerns (logging, authentication, error formatting) apply to nearly every request a server handles, and duplicating that logic inside every single route handler is repetitive and error-prone — middleware lets you insert shared logic into the request-handling pipeline once, applied to many or all routes automatically.
Why now
Building an HTTP server established the accept-parse-respond loop; middleware is where that loop gets deliberately broken into composable stages. Higher-order functions already established taking and returning functions as a reusable pattern — middleware is exactly that pattern, applied to wrap request handlers.
Mental model
Middleware is a chain of functions, each receiving the request, doing something (logging, checking auth), and either passing control to the next function in the chain or stopping it short (rejecting the request). It's the same higher-order-function composition idea as chaining map/filter — except each stage decides whether the pipeline continues at all.
Requires
- Building an HTTP ServerBackend Engineering
Middleware inserts itself into the request-handling loop a server already runs; you need that loop as the thing being extended before 'insert shared logic into it' has anywhere to go.
- Higher-Order FunctionsProgramming Fundamentals
Middleware is functions wrapping functions — the exact higher-order pattern already covered, specialized so each wrapper can choose whether to call the next one at all.
Unlocks
Used in
- Logging, authentication, and CORS middleware in nearly every backend framework
- Express, Koa, and similar frameworks whose entire architecture is built around a middleware chain
- Rate limiting and request validation, commonly implemented as middleware
- Error-handling middleware, catching failures from anywhere later in the chain in one place
Projects
- Write a logging middleware from scratch that records every request's method, path, and response time, without a framework's built-in logger
- Build an authentication middleware that rejects unauthenticated requests before they ever reach the route handler
Examples
- app.use(authMiddleware) runs before every route handler, rejecting unauthenticated requests before any route-specific code executes
- A logging middleware wraps the next handler, timing how long it takes and logging the result after it returns
Resources
Mastery checklist
- I can write a middleware function that can either continue or stop the request pipeline
- I can order middleware correctly (e.g. auth before route-specific logic)
- I can explain middleware as an application of the higher-order function pattern
- I can implement centralized error-handling middleware