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

@tresdoce-nestjs-toolkit/rate-limit

v0.2.12

Published

Tresdoce NestJS Toolkit - Módulo para limitar los requests por segundo a los controllers

Readme

⚠️ Es importante tener en cuenta que este módulo se encuentra implementado en el package @tresdoce-nestjs-toolkit/paas, ya que es una funcionalidad core para el starter.

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

El módulo envuelve @nestjs/throttler y re-exporta toda su API pública, por lo que no es necesario instalar @nestjs/throttler por separado.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/rate-limit
yarn add @tresdoce-nestjs-toolkit/rate-limit

📦 Dependencias internas

Este paquete no tiene dependencias internas del toolkit. Puede utilizarse de forma independiente.

⚙️ Configuración

Agregar los datos del rate limit en configuration.ts utilizando la key rateLimits dentro de server. Puedes encontrar más información en la documentación oficial de @nestjs/throttler.

//./src/config/configuration.ts
import { Typings } from '@tresdoce-nestjs-toolkit/core';
import { registerAs } from '@nestjs/config';

export default registerAs('config', (): Typings.AppConfig => {
  return {
    //...
    server: {
      //...
      rateLimits: {
        throttlers: [
          {
            limit: 10,
            ttl: 60,
          },
        ],
      },
    },
    //...
  };
});

RateLimitModule utiliza las opciones de ThrottlerModule para configurar las restricciones. Estas opciones se pueden pasar como un objeto ThrottlerModuleOptions que contiene:

| Property | Type | Description | | ------------------ | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | throttlers | Array<ThrottlerOptions> | Lista de limitadores individuales con sus propias configuraciones de límite de tasa. | | skipIf | (context: ExecutionContext) => boolean | Función que omite la limitación si retorna true. | | ignoreUserAgents | RegExp[] | Lista de expresiones regulares para omitir ciertos User-Agents, como bots de motores de búsqueda. | | getTracker | ThrottlerGetTrackerFunction | Función para obtener el identificador único del cliente (por ejemplo, dirección IP o ID de usuario). | | generateKey | ThrottlerGenerateKeyFunction | Función para personalizar la clave de rastreo única para cada cliente. | | errorMessage | string o ((context, limitDetail) => string) | Mensaje de error personalizado cuando se alcanza el límite de solicitudes. | | storage | ThrottlerStorage | Mecanismo de almacenamiento usado para rastrear las solicitudes, por defecto en memoria. |

Cada item (ThrottlerOptions) permite configurar un limitador específico:

| Property | Type | Description | | ------------------ | ---------------------------------------- | ----------------------------------------------------------------------------------------- | | name | string | Nombre opcional para identificar el limitador de tasa. | | limit | Resolvable<number> | Número máximo de solicitudes permitidas en el intervalo ttl. | | ttl | Resolvable<number> | Intervalo de tiempo en segundos durante el cual se cuentan las solicitudes. | | blockDuration | Resolvable<number> | Duración en segundos durante la cual se bloquea al cliente después de alcanzar el límite. | | ignoreUserAgents | RegExp[] | Lista de User-Agents que serán ignorados para este limitador. | | skipIf | (context: ExecutionContext) => boolean | Función para omitir la limitación de tasa si retorna true. | | getTracker | ThrottlerGetTrackerFunction | Función para rastrear el cliente específico. | | generateKey | ThrottlerGenerateKeyFunction | Personalización de la clave única que rastrea las solicitudes de cada cliente. |

Ejemplos de Configuración Avanzada

  • La configuración con generateKey rastrea las solicitudes por combinación de IP y ruta, permitiendo límites de tasa específicos por ruta.
  • El blockDuration bloquea al cliente durante 5 minutos si supera el límite de 10 solicitudes en 1 minuto.
  • El skipIf omite la limitación de tasa para usuarios administradores autenticados.
//./src/config/configuration.ts
import { Typings } from '@tresdoce-nestjs-toolkit/core';
import { registerAs } from '@nestjs/config';

export default registerAs('config', (): Typings.AppConfig => {
  return {
    //...
    server: {
      //...
      rateLimits: {
        throttlers: [
          {
            limit: 10,
            ttl: 60,
            blockDuration: 300,
          },
        ],
        skipIf: (context) => {
          const request = context.switchToHttp().getRequest();
          return request.user?.isAdmin;
        },
        generateKey: (context, trackerString) => {
          const request = context.switchToHttp().getRequest();
          return `${trackerString}-${request.route.path}`;
        },
      },
    },
    //...
  };
});

👨‍💻 Uso

1. Importar RateLimitModule

Importar RateLimitModule en el módulo principal de la aplicación. Este paso es obligatorio para que la configuración de rate limiting quede activa.

//./src/app.module.ts
import { RateLimitModule } from '@tresdoce-nestjs-toolkit/rate-limit';

@Module({
  imports: [
    //...
    RateLimitModule,
    //...
  ],
  //...
})
export class AppModule {}

2. Aplicar ThrottlerGuard

Para activar el rate limiting, es necesario aplicar el ThrottlerGuard. Puede hacerse de forma global, por controlador o por ruta.

Aplicación Global (main.ts)

//./src/main.ts
import { ConfigService } from '@nestjs/config';
import { ThrottlerGuard } from '@tresdoce-nestjs-toolkit/rate-limit';

//...

async function bootstrap() {
  //...
  app.useGlobalGuards(new ThrottlerGuard());
  //...
}

Aplicación Global (como provider en app.module.ts)

//./src/app.module.ts
import { APP_GUARD } from '@nestjs/core';
import { RateLimitModule, ThrottlerGuard } from '@tresdoce-nestjs-toolkit/rate-limit';

@Module({
  imports: [
    //...
    RateLimitModule,
    //...
  ],
  providers: [
    //...
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard,
    },
    //...
  ],
  //...
})
export class AppModule {}

Aplicación a nivel de controlador

import { Controller, Get, UseGuards } from '@nestjs/common';
import { ThrottlerGuard } from '@tresdoce-nestjs-toolkit/rate-limit';

@Controller('test')
@UseGuards(ThrottlerGuard)
export class TestController {
  @Get()
  getTest() {
    return 'Esta es una ruta protegida por el rate limit';
  }
}

3. Saltear rate limit

El decorador @SkipThrottle() se usa para omitir el rate limit en métodos o controladores específicos que de otro modo estarían protegidos por el ThrottlerGuard.

import { SkipThrottle } from '@tresdoce-nestjs-toolkit/rate-limit';

@SkipThrottle()
@Controller('users')
export class UsersController {
  // Rate limiting is applied to this route.
  @SkipThrottle({ default: false })
  dontSkip() {
    return 'List users work with Rate limiting.';
  }
  // This route will skip rate limiting.
  doSkip() {
    return 'List users work without Rate limiting.';
  }
}

4. Sobreescribir límites por ruta con @Throttle()

El decorador @Throttle() permite definir límites específicos para un controlador o método individual, sobreescribiendo los valores globales configurados en rateLimits.

import { Controller, Get } from '@nestjs/common';
import { Throttle } from '@tresdoce-nestjs-toolkit/rate-limit';

@Controller('upload')
export class UploadController {
  @Get()
  @Throttle({ default: { limit: 3, ttl: 60 } })
  uploadFile() {
    return 'Este endpoint permite máximo 3 requests por minuto';
  }
}

📋 API Reference

RateLimitModule

Módulo global que configura ThrottlerModule de forma asíncrona leyendo las opciones desde config.server.rateLimits de la configuración centralizada.

Re-exports de @nestjs/throttler

Este módulo re-exporta toda la API pública de @nestjs/throttler. Los elementos más usados son:

| Export | Tipo | Descripción | | ----------------- | --------- | --------------------------------------------------------------------------------------- | | ThrottlerGuard | Guard | Guard que aplica el rate limiting a las rutas protegidas. | | SkipThrottle() | Decorador | Omite el rate limiting para un controlador o método. | | Throttle() | Decorador | Sobreescribe los límites de rate limiting para un controlador o método específico. | | ThrottlerModule | Módulo | Módulo base de @nestjs/throttler (ya configurado internamente por RateLimitModule). |

Token de inyección

| Token | Valor | Descripción | | --------------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | RATE_LIMIT_MODULE_OPTIONS | Symbol.for('RATE_LIMIT_MODULE_OPTIONS') | Token para inyectar las opciones de ThrottlerModuleOptions resueltas desde la configuración centralizada. |

Ejemplo de uso del token

import { Inject, Injectable } from '@nestjs/common';
import { ThrottlerModuleOptions } from '@tresdoce-nestjs-toolkit/rate-limit';
import { RATE_LIMIT_MODULE_OPTIONS } from '@tresdoce-nestjs-toolkit/rate-limit';

@Injectable()
export class MyService {
  constructor(
    @Inject(RATE_LIMIT_MODULE_OPTIONS)
    private readonly rateLimitOptions: ThrottlerModuleOptions,
  ) {}
}

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.