NestJS Adapter
The NestJS adapter provides a module, guard, and decorator for seamless integration with NestJS applications.
Installation
npm install @joint-ops/hitlimit pnpm add @joint-ops/hitlimit yarn add @joint-ops/hitlimit bun add @joint-ops/hitlimit Module Setup
Import the HitLimitModule in your app module:
app.module.ts
import { Module } from '@nestjs/common'
import { HitLimitModule } from '@joint-ops/hitlimit/nest'
@Module({
imports: [
HitLimitModule.register({
limit: 100,
window: '1m'
})
]
})
export class AppModule {} Async Configuration
Use async configuration for dynamic settings:
app.module.ts
HitLimitModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
limit: config.get('RATE_LIMIT'),
window: config.get('RATE_WINDOW')
})
}) Using the Guard
Apply rate limiting globally or per controller:
main.ts
import { HitLimitGuard } from '@joint-ops/hitlimit/nest'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
// Apply globally
app.useGlobalGuards(new HitLimitGuard())
await app.listen(3000)
} Using the Decorator
Apply custom limits to specific routes using the @HitLimit decorator:
users.controller.ts
import { Controller, Get, Post } from '@nestjs/common'
import { HitLimit } from '@joint-ops/hitlimit/nest'
@Controller('users')
export class UsersController {
@Get()
@HitLimit({ limit: 100, window: '1m' })
findAll() {
return this.usersService.findAll()
}
@Post('login')
@HitLimit({ limit: 5, window: '15m' })
login() {
return this.authService.login()
}
} Custom Key Extraction
Extract the rate limit key from the request:
HitLimitModule.register({
limit: 100,
window: '1m',
key: (req) => req.user?.id || req.ip
}) Using with Stores
Configure a Redis store for distributed deployments:
import { redisStore } from '@joint-ops/hitlimit/stores/redis'
HitLimitModule.register({
limit: 100,
window: '1m',
store: redisStore({
url: 'redis://localhost:6379'
})
}) Next Steps
- Configuration Options - All available options
- Stores - Memory, SQLite, Redis
- Express Adapter - Express.js integration