How to configure rate-limit with fastify-adapter in nest js

1.9k Views Asked by At

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

1

There are 1 best solutions below

2
On

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'
  });
}