Middleware là function signature (req, res, next) thực thi tuần tự theo thứ tự đăng ký — thứ tự là tuyệt đối.
- App-level:
app.use(helmet())áp dụng cho toàn bộ app. - Router-level:
router.use(authMiddleware)chỉ cho nhóm routes. - Error-handling middleware có 4 tham số
(err, req, res, next)phải đăng ký SAU tất cả routes. - Third-party ecosystem:
helmet(security headers),morgan(logging),compression(gzip),passport(auth strategies). - Flow:
next()chuyển sang middleware tiếp theo,next(err)nhảy thẳng tới error handler bỏ qua tất cả non-error middleware, không gọinext()và khôngres.send()thì request treo mãi.
Pitfall: đặt express.json() sau route handler → req.body undefined; đặt cors() sau route → preflight OPTIONS request trả 404.