Skip to main content

Rate limiting

A common technique to protect applications from brute-force attacks is rate-limiting. Many Express packages exist to provide a rate-limiting feature. A popular one is express-rate-limit.

Getting started#

Start by installing the required package:

$ npm i --save express-rate-limit

Once the installation is complete, apply the rate-limiter as global middleware.

import * as rateLimit from 'express-rate-limit';// somewhere in your initialization fileapp.use(  rateLimit({    windowMs: 15 * 60 * 1000, // 15 minutes    max: 100, // limit each IP to 100 requests per windowMs  }),);

When there is a load balancer or reverse proxy between the server and the internet, Express may need to be configured to trust the headers set by the proxy in order to get the correct IP for the end user. To do so, first use the NestExpressApplication platform interface when creating your app instance, then enable the trust proxy setting:

const app = await NestFactory.create<NestExpressApplication>(AppModule);// see https://expressjs.com/en/guide/behind-proxies.htmlapp.set('trust proxy', 1);

info Hint If you use the FastifyAdapter, use the fastify-rate-limit package instead.