Gathering detailed insights and metrics for nestjs-multi-throttler
Gathering detailed insights and metrics for nestjs-multi-throttler
Gathering detailed insights and metrics for nestjs-multi-throttler
Gathering detailed insights and metrics for nestjs-multi-throttler
NestJS Multi-Throttler is a powerful rate limiting package for NestJS applications that supports both Express and Fastify frameworks. It allows you to easily implement rate limiting functionality to control the number of requests your application can handle within a specific time frame.
npm install nestjs-multi-throttler
Typescript
Module System
Node Version
NPM Version
TypeScript (97.35%)
JavaScript (2.23%)
Shell (0.42%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
3 Stars
10 Commits
1 Watchers
7 Branches
1 Contributors
Updated on Jun 29, 2024
Latest Version
1.0.2
Package Id
nestjs-multi-throttler@1.0.2
Unpacked Size
156.54 kB
Size
49.54 kB
File Count
37
NPM Version
8.15.0
Node Version
16.17.0
Published on
Jun 15, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
3
51
NestJS Multi-Throttler is a powerful rate limiting package for NestJS applications
NestJS Multi-Throttler is a powerful rate limiting package for NestJS applications that supports both Express and Fastify frameworks. It allows you to easily implement rate limiting functionality to control the number of requests your application can handle within a specific time frame.
Supports rate limiting for Express and Fastify frameworks. Provides options for defining custom time rates for rate limiting. Based on the nestjs/throttler project.
1$ npm i --save nestjs-multi-throttler
or
1yarn add nestjs-multi-throttler 2
To start using NestJS Multi-Throttler, you need to import the ThrottlerModule into your application module and configure it with your desired rate limit options.
1import { Module } from '@nestjs/common';
2import { ThrottlerModule } from 'nestjs-multi-throttler';
3
4@Module({
5 imports: [
6 ThrottlerModule.forRoot({
7 limits: [
8 { timeUnit: 'second', limit: 10 }, // Example rate limit configuration
9 { timeUnit: 'minute', limit: 100 },
10 { timeUnit: 'hour', limit: 200 },
11 { timeUnit: 'day', limit: 300 },
12 { timeUnit: 'week', limit: 1000 },
13 { timeUnit: 1200, limit: 150 }, // custom configuration 1200 seconds ie. 20 mins
14 ],
15
16 // Below are possible options on how to configure the storage service.
17
18 // default config (host = localhost, port = 6379)
19 storage: new ThrottlerStorageRedisService(),
20
21 // connection url
22 storage: new ThrottlerStorageRedisService('redis://'),
23
24 // redis object
25 storage: new ThrottlerStorageRedisService(new Redis()),
26
27 // redis clusters
28 storage: new ThrottlerStorageRedisService(new Redis.Cluster(nodes, options)),
29
30
31 // connection url
32 storage: new ThrottlerStorageMongoService('mongodb://'),
33
34 // MongoDB connection string with connection options
35 storage: new ThrottlerStorageMongoService('mongodb://',{
36 useNewUrlParser: true,
37 useUnifiedTopology: true,
38 // Other connection options
39 }
40 ),
41
42 //In-memory storage option
43 storage: new ThrottlerStorageMemoryService(),
44
45 }),
46 ],
47})
48export class AppModule {}
You can customize the rate limits by specifying the timeUnit (e.g., 'second', 'minute', 'hour', 'day', 'week') and the corresponding limit. The package also supports multiple rate limits, allowing you to define different limits for various time units.
Additionally, NestJS Multi-Throttler provides support for different storage options, such as Redis, in-memory storage (default), and MongoDB.
The ThrottleModule
is the main entry point for this package, and can be used
in a synchronous or asynchronous manner. All the needs to be passed is the
ttl
, the time to live in seconds for the request tracker, and the limit
, or
how many times an endpoint can be hit before returning a 429.
1import { APP_GUARD } from '@nestjs/core'; 2import { ThrottlerGuard, ThrottlerModule } from 'nestjs-multi-throttler'; 3 4@Module({ 5 imports: [ 6 ThrottlerModule.forRoot([ 7 { timeUnit: 'minute', limit: 5 }, 8 { timeUnit: 'hour', limit: 50 }, 9 { timeUnit: 20, limit: 3 }, // 20 seconds 10 ]), 11 ], 12 providers: [ 13 { 14 provide: APP_GUARD, 15 useClass: ThrottlerGuard, 16 }, 17 ], 18}) 19export class AppModule {}
The above would mean that 5 requests from the same IP can be made to a single endpoint in 1 minute, along with 50 requests for 1 hour and a custom timelimit of 20 seconds with 3 requests.
1@Module({ 2 imports: [ 3 ThrottlerModule.forRootAsync({ 4 imports: [ConfigModule], 5 inject: [ConfigService], 6 useFactory: (config: ConfigService) => ({ 7 limits: config.get('THROTTLE_LIMIT'), 8 }), 9 }), 10 ], 11 providers: [ 12 { 13 provide: APP_GUARD, 14 useClass: ThrottlerGuard, 15 }, 16 ], 17}) 18export class AppModule {}
The above is also a valid configuration for asynchronous registration of the module.
NOTE: If you add the ThrottlerGuard
to your AppModule
as a global guard
then all the incoming requests will be throttled by default. This can also be
omitted in favor of @UseGuards(ThrottlerGuard)
. The global guard check can be
skipped using the @SkipThrottle()
decorator mentioned later.
Example with @UseGuards(ThrottlerGuard)
:
1// app.module.ts 2@Module({ 3 imports: [ThrottlerModule.forRoot([{ timeUnit: 'minute', limit: 20 }])], 4}) 5export class AppModule {} 6 7// app.controller.ts 8@Controller() 9export class AppController { 10 @UseGuards(ThrottlerGuard) 11 @Throttle([ 12 { timeUnit: 'minute', limit: 20 }, 13 { timeUnit: 'hour', limit: 100 }, 14 { timeUnit: 'second', limit: 1 }, 15 ]) 16 normal() {} 17}
1@Throttle([{ timeUnit: 'minute', limit: 20 }])
This decorator will set THROTTLER_LIMIT
metadata on the
route, for retrieval from the Reflector
class. Can be applied to controllers
and routes.
1@SkipThrottle(skip = true)
This decorator can be used to skip a route or a class or to negate the skipping of a route in a class that is skipped.
1@SkipThrottle() 2@Controller() 3export class AppController { 4 @SkipThrottle(false) 5 dontSkip() {} 6 7 doSkip() {} 8}
In the above controller, dontSkip
would be counted against and rate-limited
while doSkip
would not be limited in any way.
You can use the ignoreUserAgents
key to ignore specific user agents.
1@Module({
2 imports: [
3 ThrottlerModule.forRoot({
4 [
5 { timeUnit: 'minute', limit: 20 },
6 { timeUnit: 'hour', limit: 100 },
7 { timeUnit: 'day', limit: 200 },
8 ]
9 ignoreUserAgents: [
10 // Don't throttle request that have 'googlebot' defined in them.
11 // Example user agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
12 /googlebot/gi,
13
14 // Don't throttle request that have 'bingbot' defined in them.
15 // Example user agent: Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)
16 new RegExp('bingbot', 'gi'),
17 ],
18 }),
19 ],
20})
21export class AppModule {}
Interface to define the methods to handle the details when it comes to keeping track of the requests.
Currently the key is seen as an MD5
hash of the IP
, the ClassName
, the
MethodName
and TimeUnit
to ensure that no unsafe characters are used and to ensure that
the package works for contexts that don't have explicit routes (like Websockets
and GraphQL).
The interface looks like this:
1export interface ThrottlerStorage { 2 storage: Record<string, ThrottlerStorageRecord>; 3 increment(key: string, ttl: number): Promise<ThrottlerStorageRecord>; 4}
So long as the Storage service implements this interface, it should be usable by the ThrottlerGuard
.
If you are working behind a proxy, check the specific HTTP adapter options (express and fastify) 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:
1// throttler-behind-proxy.guard.ts 2import { ThrottlerGuard } from 'nestjs-multi-throttler'; 3import { Injectable } from '@nestjs/common'; 4 5@Injectable() 6export class ThrottlerBehindProxyGuard extends ThrottlerGuard { 7 protected getTracker(req: Record<string, any>): string { 8 return req.ips.length ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs 9 } 10} 11 12// app.controller.ts 13import { ThrottlerBehindProxyGuard } from './throttler-behind-proxy.guard'; 14@UseGuards(ThrottlerBehindProxyGuard)
To work with Websockets you can extend the ThrottlerGuard
and override the handleRequest
method with something like the following method
1@Injectable() 2export class WsThrottlerGuard extends ThrottlerGuard { 3 async handleRequest(context: ExecutionContext, limits: ThrottlerRateLimit[]): Promise<boolean> { 4 const client = context.switchToWs().getClient(); 5 // this is a generic method to switch between `ws` and `socket.io`. You can choose what is appropriate for you 6 const ip = ['conn', '_socket'] 7 .map((key) => client[key]) 8 .filter((obj) => obj) 9 .shift().remoteAddress; 10 for (const limit of limits) { 11 const key = this.generateKey(context, tracker, limit.timeUnit); 12 const { totalHits, timeToExpire } = await this.storageService.increment( 13 key, 14 this.getTTL(limit.timeUnit) * 1000, 15 ); 16 17 // Throw an error when the user has reached their limit for the current rate limit 18 if (totalHits > limit.limit) { 19 throw new ThrottlerException(); 20 } 21 } 22 23 return true; 24 } 25}
There are some things to take keep in mind when working with websockets:
APP_GUARD
or app.useGlobalGuards()
due to how Nest binds global guards.exception
event, so make sure there is a listener ready for this.To get the ThrottlerModule
to work with the GraphQL context, a couple of things must happen.
Express
and apollo-server-express
as your GraphQL server engine. This is
the default for Nest, but the apollo-server-fastify
package does not currently support passing res
to the context
, meaning headers cannot be properly set.GraphQLModule
, you need to pass an option for context
in the form
of ({ req, res}) => ({ req, res })
. This will allow access to the Express Request and Response
objects, allowing for the reading and writing of headers.ExecutionContext
to pass back values correctly (or you can override the method entirely)1@Injectable() 2export class GqlThrottlerGuard extends ThrottlerGuard { 3 getRequestResponse(context: ExecutionContext) { 4 const gqlCtx = GqlExecutionContext.create(context); 5 const ctx = gqlCtx.getContext(); 6 return { req: ctx.req, res: ctx.res }; // ctx.request and ctx.reply for fastify 7 } 8}
The storage property is used to define the storage option for the rate limiter. There are three options available: Option 1: Redis
1@Module({ 2 imports: [ 3 ThrottlerModule.forRoot({ 4 limits: [{ timeUnit: 'minute', limit: 5 }], 5 storage: new ThrottlerStorageRedisService(), 6 }), 7 ], 8})
This option uses Redis as the storage for the rate limiter. It requires providing the valid Redis server URL (redis://localhost:6379 in this case).
Option 2: Memory (default)
1@Module({ 2 imports: [ 3 ThrottlerModule.forRoot({ 4 limits: [{ timeUnit: 'minute', limit: 5 }], 5 storage: new ThrottlerStorageMemoryService(),// -- default 6 }), 7 ], 8})
This option uses in-memory storage for the rate limiter. It is the default option if no storage property is provided.
Option 3: MongoDB
1@Module({ 2 imports: [ 3 ThrottlerModule.forRoot({ 4 limits: [{ timeUnit: 'minute', limit: 5 }], 5 storage: new ThrottlerStorageMongoService('mongodb://localhost:27017'), 6 }), 7 ], 8}) 9
This option uses MongoDB as the storage for the rate limiter. It requires providing the valid MongoDB server URL (mongodb://localhost:27017 in this case).
Feel free to submit a PR with your custom storage options being added to this list.
Nest is MIT licensed.
This project was forked from the nestjs/throttler project.
No vulnerabilities found.
No security vulnerabilities found.