Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle.
What Middleware Can Do
- Execute any code (e.g., logging, timing, analytics).
- Modify
reqorresobjects (e.g., attachreq.user). - End the request-response cycle early (e.g., return
401 Unauthorized). - Call
next()to pass control to the next middleware or route handler.
Important: Middleware runs in the exact order you register it with app.use().
ADVERTISEMENT