Skip to content

Commit e867bbf

Browse files
Merge pull request #2609 from Lolly1150/patch-1
fix: Update rate-limit websocket docs
2 parents 6706fc8 + 606af6b commit e867bbf

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

content/security/rate-limiting.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,25 +102,26 @@ 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+
const ip = client._socket.remoteAddress
112108
const key = this.generateKey(context, ip);
113-
const ttls = await this.storageService.getRecord(key);
109+
const { totalHits } = await this.storageService.increment(key, ttl);
114110

115-
if (ttls.length >= limit) {
111+
if (totalHits > limit) {
116112
throw new ThrottlerException();
117113
}
118114

119-
await this.storageService.addRecord(key, ttl);
120115
return true;
121116
}
122117
}
123118
```
119+
> info **Hint** If you using ws, it is necessary to replace the `_socket` with `conn`
120+
121+
There's a few things to keep in mind when working with WebSockets:
122+
123+
- Guard cannot be registered with the `APP_GUARD` or `app.useGlobalGuards()`
124+
- When a limit is reached, Nest will emit an `exception` event, so make sure there is a listener ready for this
124125

125126
> info **Hint** If you are using the `@nestjs/platform-ws` package you can use `client._socket.remoteAddress` instead.
126127

0 commit comments

Comments
 (0)