# throttler **Repository Path**: mirrors_nestjs/throttler ## Basic Information - **Project Name**: throttler - **Description**: A rate limiting module for NestJS to work with Fastify, Express, GQL, Websockets, and RPC 🧠- **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-11-21 - **Last Updated**: 2026-07-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README
A progressive Node.js framework for building efficient and scalable server-side applications.
## Description A Rate-Limiter for NestJS, regardless of the context. Throttler ensures that users can only make `limit` requests per `ttl` to each endpoint. By default, users are identified by their IP address. This behavior can be customized by providing your own `getTracker` function. See [Proxies](#proxies) for an example where this is useful. Throttler comes with a built-in in-memory cache to keep track of the requests. It supports alternate storage providers. For an overview, see [Community Storage Providers](#community-storage-providers). ## Installation ```bash $ npm i --save @nestjs/throttler ``` ## Versions `@nestjs/throttler@^1` is compatible with Nest v7 while `@nestjs/throttler@^2` is compatible with Nest v7 and Nest v8, but it is suggested to be used with only v8 in case of breaking changes against v7 that are unseen. For NestJS v10, please use version 4.1.0 or above. ## Usage ### ThrottlerModule Once the installation is complete, the `ThrottlerModule` can be configured as any other Nest package with `forRoot` or `forRootAsync` methods. ```typescript @@filename(app.module) @Module({ imports: [ ThrottlerModule.forRoot([{ ttl: 60000, limit: 10, }]), ], }) export class AppModule {} ``` The above will set the global options for the `ttl`, the time to live in milliseconds, and the `limit`, the maximum number of requests within the ttl, for the routes of your application that are guarded. Once the module has been imported, you can then choose how you would like to bind the `ThrottlerGuard`. Any kind of binding as mentioned in the [guards](https://docs.nestjs.com/guards) section is fine. If you wanted to bind the guard globally, for example, you could do so by adding this provider to any module: ```typescript { provide: APP_GUARD, useClass: ThrottlerGuard } ``` #### Multiple Throttler Definitions There may come upon times where you want to set up multiple throttling definitions, like no more than 3 calls in a second, 20 calls in 10 seconds, and 100 calls in a minute. To do so, you can set up your definitions in the array with named options, that can later be referenced in the `@SkipThrottle()` and `@Throttle()` decorators to change the options again. ```typescript @@filename(app.module) @Module({ imports: [ ThrottlerModule.forRoot([ { name: 'short', ttl: 1000, limit: 3, }, { name: 'medium', ttl: 10000, limit: 20 }, { name: 'long', ttl: 60000, limit: 100 } ]), ], }) export class AppModule {} ``` #### Important note on using decorators with Named Throttlers: When you have configured named throttlers (e.g., 'short', 'medium', 'long' as shown above), both the `@SkipThrottle()` and `@Throttle()` decorators must be provided with an object where keys are the names of your throttlers. If you use `@SkipThrottle()` without specifying the names, it will not skip any of your named throttlers. Similarly, `@Throttle()` without specifying names cannot override settings for specific named throttlers. **Correct usage with named throttlers:** To skip specific named throttlers: ```typescript @SkipThrottle({ short: true, medium: true }) @Controller('users') export class UsersController {} ``` To override limits for specific named throttlers: ```typescript @Throttle({ short: { limit: 5, ttl: 1000 }, medium: { limit: 30, ttl: 10000 } }) @Get() findAll() { return "Custom limits for specific throttlers"; } ``` **Incorrect usage** (will not work as intended for named throttlers): ```typescript @SkipThrottle() // This will NOT skip any named throttlers @Controller('users') export class UsersController {} ``` For more details on this behavior, especially if migrating from older versions, please refer to the [Migration to v5](#migrating-to-v5-from-earlier-versions) guide. ### Customization There may be a time where you want to bind the guard to a controller or globally, but want to disable rate limiting for one or more of your endpoints. For that, you can use the `@SkipThrottle()` decorator to negate the throttler for an entire class or a single route. The `@SkipThrottle()` decorator behaves differently based on your ThrottlerModule configuration: 1. **For a single, default (unnamed) throttler:** You can use `@SkipThrottle()`, `@SkipThrottle(true)`, or `@SkipThrottle({ default: true })`. ```typescript @SkipThrottle() @Controller('users') export class UsersController {} ``` 2. **For multiple named throttlers** (e.g., 'short', 'medium'): You must provide an object where keys are the names of the throttlers you wish to skip, and values are `true`. ```typescript @SkipThrottle({ short: true, medium: true }) @Controller('users') export class UsersController {} ``` > **Important:** Simply using `@SkipThrottle()` without an object will not skip any named throttlers. See the [Multiple Throttler Definitions](#multiple-throttler-definitions) section for a detailed example and explanation. The `@SkipThrottle()` decorator can also be used to negate the skipping of a route in a class that is already skipped: ```typescript @SkipThrottle({ default: true }) @Controller('users') export class UsersController { // Rate limiting is applied to this route. @SkipThrottle({ default: false }) dontSkip() { return 'List users work with Rate limiting.'; } // This route will skip rate limiting. doSkip() { return 'List users work without Rate limiting.'; } } ``` 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. With version 5 and onwards, the decorator takes in an object with the string relating to the name of the throttler set, and an object with the limit and ttl keys and integer values, similar to the options passed to the root module. If you do not have a name set in your original options, use the string `default` You have to configure it like this: ```typescript // Override default configuration for Rate limiting and duration. @Throttle({ default: { limit: 3, ttl: 60000 } }) @Get() findAll() { return "List users works with custom rate limiting."; } ``` ### Proxies 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/Reference/Server/#trustproxy)) for the `trust proxy` option and enable it. Doing so will allow you to get the original IP address from the `X-Forwarded-For` header. For express, no further configuration is needed because express sets `req.ip` to the client IP if `trust proxy` is enabled. For fastify, you need to read the client IP from `req.ips` instead. The following example is only needed for fastify, but works with both engines: ```typescript // throttler-behind-proxy.guard.ts import { ThrottlerGuard } from '@nestjs/throttler'; import { Injectable } from '@nestjs/common'; @Injectable() export class ThrottlerBehindProxyGuard extends ThrottlerGuard { protected getTracker(req: Recordname |
the name for internal tracking of which throttler set is being used. Defaults to `default` if not passed |
ttl |
the number of milliseconds that each request will last in storage |
limit |
the maximum number of requests within the TTL limit |
blockDuration |
the number of milliseconds the request will be blocked |
ignoreUserAgents |
an array of regular expressions of user-agents to ignore when it comes to throttling requests |
skipIf |
a function that takes in the ExecutionContext and returns a boolean to short circuit the throttler logic. Like @SkipThrottler(), but based on the request |
getTracker |
a function that takes in the Request and ExecutionContext, and returns a string to override the default logic of the getTracker method |
generateKey |
a function that takes in the ExecutionContext, the tracker string and the throttler name as a string and returns a string to override the final key which will be used to store the rate limit value. This overrides the default logic of the generateKey method |
storage |
a custom storage service for where the throttling should be kept track. See Storages below. |
ignoreUserAgents |
an array of regular expressions of user-agents to ignore when it comes to throttling requests |
skipIf |
a function that takes in the ExecutionContext and returns a boolean to short circuit the throttler logic. Like @SkipThrottler(), but based on the request |
throttlers |
an array of throttler sets, defined using the table above |
errorMessage |
a string OR a function that takes in the ExecutionContext and the ThrottlerLimitDetail and returns a string which overrides the default throttler error message |
getTracker |
a function that takes in the Request and ExecutionContext, and returns a string to override the default logic of the getTracker method |
generateKey |
a function that takes in the ExecutionContext, the tracker string and the throttler name as a string and returns a string to override the final key which will be used to store the rate limit value. This overrides the default logic of the generateKey method |