From 0c65024ac61f6449bf0cf79ec50ad1d08931662d Mon Sep 17 00:00:00 2001 From: MuhammadSaad0 Date: Wed, 18 Sep 2024 17:08:04 +0500 Subject: [PATCH] chore: websocket rate limiting --- NestJS/Throttling/websockets.md | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 NestJS/Throttling/websockets.md diff --git a/NestJS/Throttling/websockets.md b/NestJS/Throttling/websockets.md new file mode 100644 index 0000000..1e01a5c --- /dev/null +++ b/NestJS/Throttling/websockets.md @@ -0,0 +1,35 @@ +### Rate Limiting a WebSocket connection +Create a guard like so: +``` +@Injectable() +export class WsThrottlerGuard extends ThrottlerGuard { + async handleRequest({ + context, + limit, + ttl, + throttler, + }: { + context: ExecutionContext; + limit: number; // limit of requests before connection should be rate limited + ttl: number; // how long requests are considered to be of the same session + throttler: ThrottlerOptions; + }): Promise { + const client = context.switchToWs().getClient(); + const ip = client.conn.remoteAddress; + const key = this.generateKey(context, ip, throttler.name); + // Increment number of requests made by this key (which is unique for each user and session) + const out = await this.storageService.increment( + key, + ttl, + limit, + 60000, // blocked for a minute + 'default', // name of the throttler + ); + if (out.totalHits > limit) { + throw new ThrottlerException(); + } + return true; + } +} +``` +This guard can then be applied to a websocket controller or event using UseGuards or to the whole module. Docs: https://docs.nestjs.com/security/rate-limiting \ No newline at end of file