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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@betsys-nestjs/rate-limiter

v4.0.0

Published

This library serves as an abstraction for specific rate limiting of requests.

Downloads

20

Readme

Rate limiter library

  • Serves as an abstraction for specific rate limiting of requests.
  • Specific rate limit can be set for either the whole application, controller, or a specific endpoint based on the placement of the decorator (examples below).
  • Supports any type of storage (Redis, Memory, etc.).

Dependencies

| Package | Version | | ---------------- | --------------- | | @nestjs/common | ^9.0.0 | | express | ^4.0.0 | | @nestjs/core | >=9.0.0 <10.0.0 | | reflect-metadata | >=0.1.13 <0.2.0 | | @nestjs/terminus | ^9.0.0 | | rxjs | >=7.8.0 <8.0.0 |

Usage

@Module({
  imports: [
    RateLimiterModule.forFeature()
  ],
})
export class AppModule {}

Rate limit counter

By default Rate limit module uses memory counter, but you can implement your own rate limit counter based on the abstraction provided by this library.

Example of redis rate limit counter using @betsys-nestjs/redis:

import { Injectable } from '@nestjs/common';
import { InjectClientWithoutKeyPrefixProvider, RedisClientWithoutKeyPrefix } from '@betsys-nestjs/redis';
import { RateLimitCounterInterface } from '@betsys-nestjs/rate-limiter'

@Injectable()
export class RedisRateLimitCounter implements RateLimitCounterInterface {
    protected TTL = 3600;
    private readonly mainRedisKey = 'REDIS_KEY'
    constructor(
      @InjectClientWithoutKeyPrefixProvider()
      protected readonly redisClientService: RedisClientWithoutKeyPrefix,
    ) {
    }

    async inc(key: string, keyType?: string): Promise<void> {
        const redisKey = `${this.mainRedisKey}:${keyType ?? 'default'}:${key}`;
        const nowInMicroseconds = Date.now() / 1000;

        await this.redisClientService.zadd(redisKey, nowInMicroseconds, nowInMicroseconds);
        await this.redisClientService.expire(redisKey, this.TTL);
    }

    async getCount(key: string, timeSpanMs: number, keyType?: string): Promise<number> {
        const redisKey = `${this.mainRedisKey}:${keyType ?? 'default'}:${key}`;
        const nowInMicroseconds = Date.now() / 1000;

        return this.redisClientService.eval(
            this.getCountLuaScript(),
            1,
            [redisKey, timeSpanMs, nowInMicroseconds],
        ) as unknown as Promise<number>;
    }

    private getCountLuaScript = (): string => `
        -- NAME: nestjs:rate_limiter

        local key = KEYS[1]
        local window = tonumber(ARGV[1])
        local now = tonumber(ARGV[2])

        redis.call('ZREMRANGEBYSCORE', key, '-inf', now - window)

        return redis.call('ZLEXCOUNT', key, '-', '+')
    `;
}

To start using RedisRateLimitCounter, insert class reference, with RedisModule to forFeature method in RateLimiter.module like this:

import { RedisModule } from '@betsys-nestjs/redis'

@Module({
  imports: [
    RateLimiterModule.forFeature({
        imports: [RedisModule.forFeature({
            prefix: 'REDIS_PREFIX',
            redisOptions: {
                commandTimeout: 360000,
            },
        })],
        counter: RedisRateLimitCounter,
    })
  ],
})
export class AppModule {}

Guards

  • The main logic of rate limiting in this library is based on the functionality of Nest.js guards.
  • Every guard needs to extend the abstract RateLimiterGuard and be Injectable.

Example implementation:

@Injectable()
export class IpRateLimiterGuard extends RateLimiterGuard {
    constructor(
        @InjectRateLimitCounter() protected readonly limitCounter: RateLimitCounterInterface,
        @Inject(KEY) protected readonly config: RateLimiterInstanceConfig,
    ) {
        super(
            config, // Config can also be declared here directly, instead of having a separate config file
            (req: Request): KeyResolverInterface => {
                return {
                    key: req.ip,
                    keyType: 'ip',
                };
            },
            limitCounter, // Counter can also be constructed here if it does not require DI (e.g. Memory storage)
            () => {
                // This is the callback, that is called upon exceeding the set limit from the configuration
                throw new TooManyRequestsForPhoneException();
            },
        );
    }
}

Example usage:

  • whole application or a module:
@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: IpRateLimiterGuard,
    },
  ],
})
export class AppModule {}
  • whole controller with all its methods:
@UseGuards(IpRateLimiterGuard)
export class CatsController {}
  • single method in controller:
@UseGuards(IpRateLimiterGuard)
async verify(@Req() req: Request, @Res() res: Response) {}

Exception filter

  • Since in most of the use cases it is wanted to return a custom HTTP response based on the thrown exceeded rate limit exception, we have created a simple exception filter, that can be used to do so.

Example implementation:

  • Every exception thrown in the exceeded limit callback must extend the RateLimitExceededBaseException from within the library.
export class TooManyRequestsFromIpException extends RateLimitExceededBaseException {
    constructor() {
        super('You have had too many requests from your IP address.');
    }
}

Example usage:

  • you must register the exception filter in the application bootstrap
app.useGlobalFilters(new RateLimitExceededExceptionFilter());

FAQ

  • Q: How can I use multiple rate limits at the same time?
  • A: Simply provide all of them to the @UseGuards decorator or the application globals. Their order is from the first one to the last one if setup with one decorator and the other way around if set up by multiple @UseGuards decorators. @UseGuards(PhoneRateLimiterGuard, IpRateLimiterGuard, ...)