How to use
If you want to start restricting specific routes, you can import theRateLimit class from the plugin and then use it as follows:
src/api/middlewares.ts
When building custom middleware, use
req.socket.remoteAddress for the client IP. Avoid using x-forwarded-for directly as it can be spoofed. If you need proxy support, use the built-in ipRateLimit middleware with trustProxy instead.src/api/middlewares.ts
Built-in IP Rate Limiting
For the common use case of IP-based rate limiting, V3 includes a ready-to-useipRateLimit middleware:
src/api/middlewares.ts
ipRateLimit middleware automatically:
- Extracts the client IP address
- Sets appropriate rate limit headers (
X-RateLimit-Limit,X-RateLimit-Remaining) - Returns a 429 status when the limit is exceeded
Extracting the client IP
By default,ipRateLimit uses req.socket.remoteAddress (the direct connection IP). This prevents attackers from bypassing rate limiting by spoofing the X-Forwarded-For header.
If your server is behind a reverse proxy (nginx, Cloudflare, etc.), enable trustProxy:
src/api/middlewares.ts
trustProxy value | Behavior |
|---|---|
false (default) | Uses direct connection IP. Ignores X-Forwarded-For. |
true | Uses leftmost IP from X-Forwarded-For. Only use if your proxy overwrites the header. |
number | Number of trusted proxy hops. Extracts IP from the right side of the header, preventing spoofing. |
trustProxy: 1: