Middleware & Request Pipelines

Difficulty
Importance

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

Unlocks

Used in

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