Rate Limiter
The Rate Limiter component protects your application from abuse, denial-of-service (DoS) attacks, and brute-force attempts by limiting the frequency of incoming requests from a single IP address.
Built on top of express-rate-limit, it provides a standardized way to apply rate limits globally or to specific sensitive routes.
Installation Guide
This component requires additional Servercn components.
👉 You do not need to install any Servercn components manually. Running this component installer will automatically install all required components. Manual installation is optional and only recommended if you prefer fine-grained components control
1. Install Servercn components(Optional)
2. Install this component
npx servercn-cli add rate-limiterConfiguration Options
The rate limiter can be customized to fit your application's needs:
- windowMs: The timeframe for which requests are checked (in milliseconds).
- max: The maximum number of connections to allow during the
windowMsbefore returning a 429 error. - standardHeaders: Enables the
RateLimit-*headers in the response. - handler: A custom function to execute when the limit is reached. In Servercn, we use it to forward the error to our global error handler.
Basic Implementation
MVC: src/middlewares/rate-limiter.ts
Modular: src/shared/middlewares/rate-limiter.ts
Usage Guide
Global Rate Limiting
Apply the rate limiter globally in your main app.ts file to protect all routes by default.
src/app.ts
Route-Specific Rate Limiting
For sensitive routes like login, password reset, or expensive search operations, you should apply stricter limits.
src/routes/auth.routes.ts