Skip to content

Commit e02b95a

Browse files
Merge pull request #2045 from bttger/patch-1
docs(security): add rate limit example behind proxies
2 parents 1015c35 + f31d8d6 commit e02b95a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

content/security/rate-limiting.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,30 @@ There may be a time where you want to bind the guard to a controller or globally
3737

3838
There is also the `@Throttle()` decorator which can be used to override the `limit` and `ttl` set in the global module, to give tighter or looser security options. This decorator can be used on a class or a function as well. The order for this decorator does matter, as the arguments are in the order of `limit, ttl`.
3939

40+
#### Proxies
41+
42+
If your application runs behind a proxy server, check the specific HTTP adapter options ([express](http://expressjs.com/en/guide/behind-proxies.html) and [fastify](https://www.fastify.io/docs/latest/Server/#trustproxy)) for the `trust proxy` option and enable it. Doing so will allow you to get the original IP address from the `X-Forward-For` header, and you can override the `getTracker()` method to pull the value from the header rather than from `req.ip`. The following example works with both express and fastify:
43+
44+
```ts
45+
// throttler-behind-proxy.guard.ts
46+
import { ThrottlerGuard } from '@nestjs/throttler';
47+
import { Injectable } from '@nestjs/common';
48+
49+
@Injectable()
50+
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
51+
protected getTracker(req: Record<string, any>): string {
52+
return req.ips.length ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs
53+
}
54+
}
55+
56+
// app.controller.ts
57+
import { ThrottlerBehindProxyGuard } from './throttler-behind-proxy.guard';
58+
59+
@UseGuards(ThrottlerBehindProxyGuard)
60+
```
61+
62+
> info **Hint** You can find the API of the `req` Request object for express [here](https://expressjs.com/en/api.html#req.ips) and for fastify [here](https://www.fastify.io/docs/latest/Request/).
63+
4064
#### Websockets
4165

4266
This module can work with websockets, but it requires some class extension. You can extend the `ThrottlerGuard` and override the `handleRequest` method like so:

0 commit comments

Comments
 (0)