Skip to content

Commit b8fa188

Browse files
authored
fix: Update rate-limit socket docs
I have update WsThrottlerGuard following new methods: https://github.com/nestjs/throttler#working-with-websockets
1 parent 51735dc commit b8fa188

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

content/security/rate-limiting.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,26 +102,30 @@ This module can work with websockets, but it requires some class extension. You
102102
```typescript
103103
@Injectable()
104104
export class WsThrottlerGuard extends ThrottlerGuard {
105-
async handleRequest(
106-
context: ExecutionContext,
107-
limit: number,
108-
ttl: number,
109-
): Promise<boolean> {
105+
async handleRequest(context: ExecutionContext, limit: number, ttl: number): Promise<boolean> {
110106
const client = context.switchToWs().getClient();
111-
const ip = client.conn.remoteAddress;
107+
// this is a generic method to switch between `ws` and `socket.io`. You can choose what is appropriate for you
108+
const ip = ['conn', '_socket']
109+
.map((key) => client[key])
110+
.filter((obj) => obj)
111+
.shift().remoteAddress;
112112
const key = this.generateKey(context, ip);
113-
const ttls = await this.storageService.getRecord(key);
113+
const { totalHits } = await this.storageService.increment(key, ttl);
114114

115-
if (ttls.length >= limit) {
115+
if (totalHits > limit) {
116116
throw new ThrottlerException();
117117
}
118118

119-
await this.storageService.addRecord(key, ttl);
120119
return true;
121120
}
122121
}
123122
```
124123

124+
There are some things to take keep in mind when working with websockets:
125+
126+
- You cannot bind the guard with `APP_GUARD` or `app.useGlobalGuards()` due to how Nest binds global guards.
127+
- When a limit is reached, Nest will emit an `exception` event, so make sure there is a listener ready for this.
128+
125129
> info **Hint** If you are using the `@nestjs/platform-ws` package you can use `client._socket.remoteAddress` instead.
126130
127131
#### GraphQL

0 commit comments

Comments
 (0)