npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@khoativi/nestjs-rate-limit

v1.0.1

Published

A flexible and efficient rate limiting library for NestJS that supports multiple storage backends (Redis via ioredis and Valkey), with customizable keys and error handling.

Downloads

0

Readme

@khoativi/nestjs-rate-limit ⚡

A flexible and efficient rate limiting library for NestJS that supports multiple storage backends—such as Redis (via ioredis) and Valkey (via iovalkey).
Easily configurable, lightweight, and designed for both global and per-route usage.

✨ Features

  • 🔁 Multiple Storage Support — Works with Redis (ioredis) and Valkey (iovalkey)
  • 🧠 Custom Key Generation — Use headers, parameters, or override the default logic
  • 📊 Flexible Counting — Choose to count all requests or only successful ones
  • 🛡️ Automatic Headers — Adds standard rate limit headers to responses
  • ⚙️ Global & Route-Level Config — Configure globally or override per endpoint
  • 🚫 Skip Rate Limit — Easily skip rate limiting for specific routes
  • 🔥 Fastify & Express Compatible — Works out of the box with both

📦 Installation

# With npm
npm install @khoativi/nestjs-rate-limit

# With yarn
yarn add @khoativi/nestjs-rate-limit

# With pnpm
pnpm add @khoativi/nestjs-rate-limit

Install one of the supported store clients:

# Redis support
npm install ioredis

# Valkey support
npm install iovalkey

⚙️ Usage in Your Application

Global Configuration in AppModule

You can configure the module using forRoot or forRootAsync.


✅ Using forRoot (Synchronous)

Redis

// redis.config.ts
import Redis from 'ioredis';
import { RedisAdapter } from '@khoativi/nestjs-rate-limit';

export const storeClient = new RedisAdapter(
  new Redis({ host: 'localhost', port: 6379 })
);
// app.module.ts
@Module({
  imports: [
    RateLimitModule.forRoot({
      duration: 30,
      limit: 5,
      storeClient,
      errorMessage: 'Too Many Requests',
      countAllRequests: true
    })
  ],
  providers: [
    { provide: APP_GUARD, useClass: RateLimitGuard }
  ]
})
export class AppModule {}

Valkey

// valkey.config.ts
import Valkey from 'iovalkey';
import { ValkeyAdapter } from '@khoativi/nestjs-rate-limit';

export const storeClient = new ValkeyAdapter(
  new Valkey('redis://localhost:6379')
);

🔄 Using forRootAsync (Asynchronous)

// rate-limit.config.ts
import { RateLimitOptions, RedisAdapter } from '@khoativi/nestjs-rate-limit';
import Redis from 'ioredis';

export const rateLimitConfig = async (): Promise<RateLimitOptions> => {
  const redisClient = new Redis({ host: 'localhost', port: 6379 });
  return {
    duration: 30,
    limit: 5,
    storeClient: new RedisAdapter(redisClient),
    errorMessage: 'Too Many Requests',
    countAllRequests: true
  };
};
// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    RateLimitModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: rateLimitConfig
    })
  ],
  providers: [
    { provide: APP_GUARD, useClass: RateLimitGuard }
  ]
})
export class AppModule {}

🚀 Using in Controller

You can apply rate limits using the @RateLimit() decorator.

@Controller('posts')
export class PostsController {
  @Get()
  @RateLimit({ duration: 30, limit: 5 })
  @UseGuards(RateLimitGuard)
  getAll() {
    return 'Limited endpoint';
  }
}

🔐 Customizing the Guard for Authorization Header or Message

@Injectable()
export class CustomRateLimitGuard extends RateLimitGuard {
  /**
   * Override this method to customize the rate limit key.
   * This version uses the `authorization` header if available.
   */
  protected async getTracker(req: any): Promise<string> {
    return req.headers?.authorization;
  }

  /**
   * Override this method to customize the error message.
   * You can integrate with a translation service like nestjs-i18n here.
   */
  protected async getErrorMessage(context: ExecutionContext): Promise<string> {
    // Example: hardcoded, you can replace with i18n service logic
    return 'Too many login attempts. Please try again later.';
  }
}
@Controller('secure')
export class SecureController {
  @Get()
  @RateLimit({ duration: 60, limit: 3 })
  @UseGuards(CustomRateLimitGuard)
  secureData() {
    return 'Rate limited by Authorization header';
  }
}

⚙️ Configuration Options

| Name | Type | Description | |------------------|-----------|--------------------------------------------------------------| | duration | number | Time window in seconds | | limit | number | Max allowed requests per window | | storeClient | Store | Store adapter (Redis, Valkey, or custom) | | errorMessage | string | Custom error message when throttled | | countAllRequests | boolean | If true, count all requests; otherwise only success (via interceptor) |


💾 Supported Storage Backends


🛠️ Issues and Contributing

Feel free to open issues or submit pull requests for improvements, bug fixes.

📄 License

MIT License © Khoa Trần