Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@nestjs/throttler
Advanced tools
A Rate-Limiting module for NestJS to work on Express, Fastify, Websockets, Socket.IO, and GraphQL, all rolled up into a simple package.
@nestjs/throttler is a rate-limiting module for NestJS applications. It helps to control the rate of incoming requests to prevent abuse and ensure fair usage of resources. This package is particularly useful for APIs to avoid being overwhelmed by too many requests in a short period.
Basic Rate Limiting
This feature allows you to set up basic rate limiting for your entire application. In this example, a maximum of 10 requests per minute is allowed.
```typescript
import { ThrottlerModule } from '@nestjs/throttler';
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
],
})
export class AppModule {}
```
Rate Limiting for Specific Routes
This feature allows you to apply rate limiting to specific routes. In this example, the 'limited' route is restricted to 5 requests per minute.
```typescript
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ThrottlerGuard, Throttle } from '@nestjs/throttler';
@Controller('api')
@UseGuards(ThrottlerGuard)
export class ApiController {
@Get('limited')
@Throttle(5, 60)
getLimited() {
return 'This route is rate limited to 5 requests per minute';
}
}
```
Customizing Rate Limiting
This feature allows you to customize the rate limiting storage mechanism. In this example, Redis is used as the storage backend for rate limiting.
```typescript
import { ThrottlerModule, ThrottlerGuard, ThrottlerStorageRedisService } from '@nestjs/throttler';
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
storage: new ThrottlerStorageRedisService(),
}),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
```
express-rate-limit is a basic rate-limiting middleware for Express applications. It is simpler and more lightweight compared to @nestjs/throttler, but it lacks the deep integration with NestJS and some advanced features like custom storage backends.
rate-limiter-flexible is a highly flexible rate-limiting library that supports various backends like Redis, MongoDB, and in-memory storage. It offers more customization options compared to @nestjs/throttler but requires more setup and integration effort.
koa-ratelimit is a rate-limiting middleware for Koa applications. It provides similar functionalities to @nestjs/throttler but is designed specifically for Koa, making it less suitable for NestJS applications.
A progressive Node.js framework for building efficient and scalable server-side applications.
A Rate-Limiter for NestJS, regardless of the context.
For an overview of the community storage providers, see Community Storage Providers.
This package comes with a couple of goodies that should be mentioned, first is the ThrottlerModule
.
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.
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerGuard, ThrottlerModule } from 'nestjs-throttler';
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
The above would mean that 10 requests from the same IP can be made to a single endpoint in 1 minute.
@Module({
imports: [
ThrottlerModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
ttl: config.get('THROTTLE_TTL'),
limit: config.get('THROTTLE_LIMIT'),
}),
}),
],
providers: [
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export 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)
:
// app.module.ts
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
],
})
export class AppModule {}
// app.controller.ts
@Controller()
export class AppController {
@UseGuards(ThrottlerGuard)
@Throttle(5, 30)
normal() {}
}
@Throttle(limit: number = 30, ttl: number = 60)
This decorator will set THROTTLER_LIMIT and THROTTLER_TTL metadatas on the
route, for retrieval from the Reflector
class. Can be applied to controllers
and routes.
@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.
@SkipThrottle()
@Controller()
export class AppController {
@SkipThrottle(false)
dontSkip() {}
doSkip() {}
}
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.
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
ignoreUserAgents: [
// Don't throttle request that have 'googlebot' defined in them.
// Example user agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
/googlebot/gi,
// Don't throttle request that have 'bingbot' defined in them.
// Example user agent: Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)
new RegExp('bingbot', 'gi'),
],
}),
],
})
export 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
and the
MethodName
, 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:
export interface ThrottlerStorage {
getRecord(key: string): Promise<number[]>;
addRecord(key: string, ttl: number): Promise<void>;
}
So long as the Storage service implements this interface, it should be usable by the ThrottlerGuard
.
To work with Websockets you can extend the ThrottlerGuard
and override the handleRequest
method with something like the following method
@Injectable()
export class WsThrottlerGuard extends ThrottlerGuard {
async handleRequest(context: ExecutionContext, limit: number, ttl: number): Promise<boolean> {
const client = context.switchToWs().getClient();
// this is a generic method to switch between `ws` and `socket.io`. You can choose what is appropriate for you
const ip = ['conn', '_socket']
.map((key) => client[key])
.filter((obj) => obj)
.shift().remoteAddress;
const key = this.generateKey(context, ip);
const ttls = await this.storageService.getRecord(key);
if (ttls.length >= limit) {
throw new ThrottlerException();
}
await this.storageService.addRecord(key, ttl);
return true;
}
}
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)@Injectable()
export class GqlThrottlerGuard extends ThrottlerGuard {
getRequestResponse(context: ExecutionContext) {
const gqlCtx = GqlExecutionContext.create(context);
const ctx = gql.getContext();
return { req, ctx.req, res: ctx.res }; // ctx.request and ctx.reply for fastify
}
}
Feel free to submit a PR with your custom storage provider being added to this list.
FAQs
A Rate-Limiting module for NestJS to work on Express, Fastify, Websockets, Socket.IO, and GraphQL, all rolled up into a simple package.
The npm package @nestjs/throttler receives a total of 187,118 weekly downloads. As such, @nestjs/throttler popularity was classified as popular.
We found that @nestjs/throttler demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.