Cadeia de Middlewares no Express (auth, rate limit, validação)
Summary: Order matters. I structure from most broad / least expensive to most specific / expensive.
Correct order
- Logging / Request ID – adds
req.idfor tracing. - CORS / Helmet – security headers first.
- Body parsers –
express.json(),express.urlencoded(). - Rate limiter –
express-rate-limitbased on IP or user ID. - Authentication – validates JWT / OAuth token. Blocks early if invalid.
- Authorization – checks permissions (e.g.,
req.user.role === 'admin'). - Validation –
Joi/zodto validate request body/query. - Route handler – the actual business logic.
- Error handler – catches all errors and sends appropriate HTTP status.
app.use(logger);
app.use(helmet());
app.use(cors());
app.use(express.json());
app.use(rateLimiter);
app.use(authMiddleware);
app.use(authorizationMiddleware);
app.use(validateRequest);
app.use('/api/orders', orderRoutes);
app.use(errorHandler);
Why this order
- Rate limiting before auth avoids wasting CPU on invalid tokens.
- Auth before validation prevents validating requests from unauthenticated users.
- Error handler is last to catch any thrown errors.
Real-world note: I also add circuit breakers on external API calls inside the route handler to prevent cascading failures.
Relacionadas: Node.js sob alta concorrência · índice.