Date:

Implementing Rate Limiting in NestJS

1. Introduction

Rate limiting is a crucial security and performance enhancement feature that protects your backend services from malicious or accidental overuse. In NestJS, we can implement rate limiting both on IP-based requests and Device ID-based requests.

This guide provides a step-by-step approach to implementing both methods, along with a clean folder structure and explanations of key components.


2. Prerequisites

Make sure you have the following installed:

  • Node.js (>= 14.x)
  • NestJS CLI (`npm install -g @nestjs/cli`)
  • Basic understanding of NestJS, TypeScript, and Middleware concepts

3. Project Setup

3.1. Create a NestJS Project

nest new rate-limiting-app
cd rate-limiting-app

3.2. Install Required Dependencies

npm install @nestjs/throttler dotenv


4. Folder Structure

Organize your project like this:

src/
│
├── app.module.ts
├── app.controller.ts
├── main.ts
│
├── device/
│   ├── guards/
│   │   └── custom-throttler.guard.ts
│   ├── services/
│   │   └── rate-limiter.service.ts
│   ├── device.controller.ts
│
├── util/
│   └── response.util.ts
│
└── custom-throttler.guard.ts


5. Environment Variables

Create a `.env` file at the root level:

PORT=3000

# Rate Limit Configurations
TTL=60000   # Time-to-live in milliseconds (60 seconds)
LIMIT=3     # Maximum requests allowed in the time window


6. Application Entry Point

6.1. main.ts


import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT);
}
...and so on...

8.3. device.controller.ts


import { Controller, Get, UseGuards } from '@nestjs/common';
import { RateLimiterGuard } from './guards/custom-throttler.guard';
import { ResponseUtil } from '../util/response.util';

@Controller('/api/device')
export class DeviceController {
  @Get('/test')
  @UseGuards(RateLimiterGuard)
  testDeviceEndpoint() {
    return ResponseUtil.success(200, 'Request successful!', { info: 'Device ID-based rate limiting is working as expected.' });
  }
}


9. Advantages of Rate Limiting

  • Prevents Abuse
  • Improved Performance
  • Enhanced Security
  • Fair Usage Policy
  • Cost Management

10. Conclusion

This guide outlined both IP-based and Device ID-based rate-limiting strategies in NestJS.

Run the server:

npm run start:dev

Test Endpoints:

  • By IP: `curl http://localhost:3000/api/ip/test`
  • By Device ID: `curl http://localhost:3000/api/device/test -H ‘device-id: unique-device-id’`

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here