2

I Just started implementing API's Nest js and I am using Fastify adapter. I need help to configure Rate limit using FastifyAdapter in Nest JS.

async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
        AppModule,
        new FastifyAdapter(),
    );

    const limiter = fastifyRateLimit(fastify(), {
        timeWindow: 15 * 60 * 1000, // 15 minutes
        max: 100 // limit each IP to 100 requests per windowMs
    }, (err) => {
    });
    app.use(limiter);
    await app.listen(configService.getPort());
}

bootstrap();

Please refer to the above code and correct the mistake

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Gowtham Raj
  • 103
  • 2
  • 13

1 Answers1

2

Install:

npm install fastify-rate-limit --save

Import (In main.ts):

import * as fastifyRateLimit from 'fastify-rate-limit';

Usage:

async function bootstrap() {
  // Create our app, bootstrap using fastify
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter()
  );

  // Apply rate limiter
  app.register(fastifyRateLimit, {
    max: 25,
    timeWindow: '1 minute'
  });
}
Chris Fremgen
  • 4,649
  • 1
  • 26
  • 26
  • By registering it at the app level it will be active for all routes but how can you change the limits for specific routes? I would like to create a decorator to overwrite the default limits for some routes. Is that the correct approach ? – Nicolas Oste Jan 10 '21 at 14:30
  • 2
    @NicolasOste I believe this is not supported for Fastify. I have since moved away from Fastify. While nice in theory, it proved to be incompatible with some features and overall not enough performance increase for the extra headache. – Chris Fremgen Jan 13 '21 at 13:38