0%
Middleware

Middleware

The processing chain that protects and instruments every request.

10-15 min

Middleware

You add an authentication middleware, and it works perfectly on the new routes, but an older route remains accessible without a token. You add CORS, and the browser keeps rejecting the request. You add a rate limiter, and it counts every request as coming from the same IP address. These three symptoms have a single cause: declaration order.

Express has no notion of priority, scope, or lifecycle. It has a list, traversed from top to bottom, and each element decides whether to pass control to the next one or to end the request. A middleware declared after a route will never apply to that route. A middleware that calls neither next() nor a response method leaves the request hanging forever, until the client's timeout, while keeping the req and res objects in memory along with everything its closure captures. That is a memory leak that produces no error message. This lesson gives you the exact model, then the minimal chain to set up on any serious API.

The signature and the contract

A middleware is a function with three arguments, and an error handler is a function with four arguments. Express tells the two apart by inspecting fn.length: if you omit the err parameter or any of the others, your error handler becomes an ordinary middleware and will never be called on error.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!