0
0
NestJSframework~5 mins

Rate limiting with throttler in NestJS

Choose your learning style9 modes available
Introduction

Rate limiting helps protect your app from too many requests at once. It keeps your server safe and fair for everyone.

You want to stop users from sending too many requests quickly.
You want to protect your API from overload or abuse.
You want to limit how often a user can try to login.
You want to control traffic spikes during sales or events.
You want to avoid your server slowing down due to too many requests.
Syntax
NestJS
import { Throttle } from '@nestjs/throttler';

@Throttle(limit, ttl)
@Controller('example')
export class ExampleController {
  @Get()
  getExample() {
    return 'Hello!';
  }
}

ttl means time to live in seconds (how long the limit lasts).

limit means how many requests are allowed in that time.

Examples
Allows 10 requests every 60 seconds for this route.
NestJS
@Throttle(10, 60)
@Get('data')
getData() {
  return 'Data here';
}
Allows 5 requests every 30 seconds for this route.
NestJS
@Throttle(5, 30)
@Get('info')
getInfo() {
  return 'Info here';
}
Limits all routes in this controller to 20 requests every 2 minutes.
NestJS
@Throttle(20, 120)
@Controller('users')
export class UsersController {
  @Get()
  getUsers() {
    return ['User1', 'User2'];
  }
}
Sample Program

This controller has one route that allows only 3 requests per minute. If a user sends more, they get blocked until time resets.

NestJS
import { Controller, Get } from '@nestjs/common';
import { Throttle } from '@nestjs/throttler';

@Controller('greet')
export class GreetController {
  @Throttle(3, 60) // 3 requests per 60 seconds
  @Get()
  sayHello() {
    return 'Hello, welcome!';
  }
}
OutputSuccess
Important Notes

Make sure to import and configure ThrottlerModule in your app module to enable throttling.

Rate limits apply per user IP by default, so different users have separate limits.

You can customize error messages when limits are exceeded for better user experience.

Summary

Rate limiting protects your app from too many requests.

Use @Throttle(ttl, limit) to set limits on routes or controllers.

Configure ThrottlerModule to enable throttling in NestJS.