nestjs-selective-throttler
Version:
A NestJS package that provides true selective throttling capabilities, applying only the named throttlers explicitly declared in route decorators.
309 lines (235 loc) โข 8.38 kB
Markdown
# NestJS Selective Throttler
๐ฏ **Build-time selective throttling for NestJS applications** - Apply specific throttlers to specific endpoints with zero runtime overhead.
[](https://badge.fury.io/js/nestjs-selective-throttler)
[](https://opensource.org/licenses/MIT)
## ๐ Features
- **๐ฏ Selective Throttling**: Apply only specific throttlers to endpoints
- **๐ง Build-time Discovery**: Automatic throttler name detection at build time
- **โก Zero Runtime Overhead**: All processing done at build time
- **๐ก๏ธ Type Safe**: Full TypeScript support with generated declarations
- **๐ Drop-in Replacement**: Works with existing ` /throttler` setup
- **๐ฆ Minimal Dependencies**: Only peer dependency on ` /throttler`
## ๐ฆ Installation
```bash
npm install nestjs-selective-throttler /throttler
```
## ๐ฏ Problem Solved
With standard ` /throttler`, when you have multiple throttlers, **ALL of them apply to every endpoint**:
```typescript
// โ Problem: ALL throttlers apply to this endpoint
processPayment() {
// This endpoint gets ALL 8 configured throttlers:
// 'burst', 'sustained', 'sensitive', 'public', 'api-gateway', etc.
// Even though you only specified 'sensitive'
}
```
**Workaround with ** (verbose and unmaintainable):
```typescript
// โ ๏ธ Workaround: Manually skip unwanted throttlers
processPayment() {
// Works but requires manually listing 6 other throttlers
// Breaks when new throttlers are added to the module
}
```
**nestjs-selective-throttler** solves this cleanly:
```typescript
// โ
Solution: Only specified throttlers apply
processPayment() {
// This endpoint gets ONLY 'sensitive' throttling
// All other 7 throttlers are automatically skipped
}
```
## ๐๏ธ Setup
### 1. Configure ThrottlerModule (as usual)
```typescript
// app.module.ts
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
export class AppModule {}
```
### 2. Add build scripts to package.json
```json
{
"scripts": {
"prebuild": "npm run generate",
"generate": "node node_modules/nestjs-selective-throttler/scripts/generate-throttler-names.js",
"build": "nest build"
}
}
```
### 3. Use Selective Throttling in Controllers
```typescript
// user.controller.ts
import { Controller, Get, Post } from '@nestjs/common';
import { SingleThrottle, SelectiveThrottle } from 'nestjs-selective-throttler/decorators';
export class UserController {
// ๐ Public endpoint - high rate limit
// Only 'default' throttler (10 req/min)
getPublicUsers() {
return { users: ['user1', 'user2'] };
}
// ๐ Protected endpoint - multiple throttlers
getProtectedUsers() {
return { users: ['admin1', 'admin2'] };
}
// ๐ฐ Sensitive operation - custom override
// Override: 1 req/30sec
processPayment() {
return { success: true };
}
}
```
## ๐ฏ API Reference
### ` `
Applies **only one specific throttler** to an endpoint.
```typescript
// Use global configuration
// Override global configuration
```
### ` `
Applies **multiple specific throttlers** to an endpoint.
```typescript
// Use global configurations
// Mix global and override configurations
```
## ๐ง How It Works
### Build-time Discovery
1. **Build Script**: Scans all `.ts` files for ` `, ` `, and ` ` decorators
2. **Code Generation**: Creates optimized decorators in `node_modules/nestjs-selective-throttler/.generated/`
3. **Selective Skip**: Generated decorators use build-time discovered names to skip unwanted throttlers
### Compatibility with
You can continue using the official ` ` decorator alongside selective throttlers:
```typescript
import { Throttle } from '@nestjs/throttler';
import { SingleThrottle } from 'nestjs-selective-throttler/decorators';
export class MixedController {
// Official @Throttle - all throttlers apply
legacyEndpoint() {}
// Selective throttling - only specified throttlers apply
selectiveEndpoint() {}
}
```
The build script automatically detects throttler names from both decorator types.
### Generated Files
```
node_modules/nestjs-selective-throttler/
โโโ .generated/
โโโ decorators.js # Runtime decorators
โโโ decorators.d.ts # TypeScript declarations
โโโ throttler-names.js # Discovered names
โโโ throttler-names.d.ts # TypeScript declarations
```
## ๐จ Real-world Example
```typescript
export class EcommerceController {
// Product catalog - high volume
// 10 req/min
getProducts() {}
// User actions - burst protection
addToCart() {}
// Payment processing - strict limits
// 1 req/30sec
processPayment() {}
}
```
## ๐งช Examples
- **[Basic Usage](examples/basic-usage/)** - Complete single-module implementation with test endpoints
- **[Multi-Module Usage](examples/multi-module-usage/)** - Cross-module throttler issues and solutions
## ๐ Debugging
To see which throttlers are discovered at build time:
```typescript
import { ALL_THROTTLER_NAMES } from 'nestjs-selective-throttler/throttler-names';
console.log('Discovered throttlers:', ALL_THROTTLER_NAMES);
// Output: ['default', 'sensitive', 'burst-protection', ...]
```
## ๐ง Advanced Features
### Multi-Module Support
The package automatically detects throttlers across multiple modules and validates cross-module usage:
```bash
npm run generate
```
**Output:**
```
โ CROSS-MODULE THROTTLER ISSUES DETECTED:
๐ src/api/api.controller.ts
Module: src/api/api.module.ts
Available throttlers: [api-public, api-premium]
Used throttlers: [api-public, auth-login]
โ Unavailable: [auth-login]
```
### Supported ThrottlerModule Formats
- `ThrottlerModule.forRoot([...])` - Array format
- `ThrottlerModule.forRoot({ throttlers: [...] })` - Object format
- `ThrottlerModule.forRootAsync({ useFactory: ... })` - Async configuration
- Mixed configurations with additional options
## ๐ค Compatibility
- **NestJS**: ^10.0.0 || ^11.0.0
- ** /throttler**: ^6.0.0
- **TypeScript**: ^5.0.0
- **Node.js**: ^18.0.0
## ๐ License
MIT ยฉ [Orkun](https://github.com/orknist)
## ๐ค Contributing
Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
## ๐ Issues
Found a bug? Please [open an issue](https://github.com/orknist/nestjs-selective-throttler/issues).
---
**Made with โค๏ธ for the NestJS community**