Importing the Library

This library requires node version 16 or above.

This library is provided in esm as well as cjs forms, and works with both Javascript and Typescript projects.

// Your code most likely uses the es module format if the `type` field in your
// `package.json` is set to `module`.

import { rateLimit } from 'express-rate-limit'

Using the Library

The rateLimit function accepts an options object and returns the rate limiting middleware.

An example with the recommended configuration is as follows:

const limiter = rateLimit({
	windowMs: 15 * 60 * 1000, // 15 minutes
	max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
	standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
	legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})

Then use it in your Express application as follows:

app.use(limiter)

To use it only for a certain path (e.g., limit only calls to the /auth/* endpoints), specify the url as the first parameter in app.use:

app.use('/auth', limiter)

To use it only for a certain endpoint (e.g., limit calls to POST /reset_password), add the limiter as a middle argument to app.get/app.post/etc.:

app.post('/reset_password', limiter, (req, res) => {
	// ...
})

Take a look at the configuration page for a list of options you can use to change the behaviour of the limiter.

If your server runs behind a proxy/load balancer, the IP address of the request might be undefined, or the IP of the load balancer/reverse proxy (leading to the rate limiter blocking all requests once the limit is reached).

To fix this, take a look at the guide to troubleshooting proxy issues.

Using External Stores

A store is essentially a javascript/typescript class that allows the library to store hit counts and reset times for clients wherever you want, e.g., in an external database.

To use an external store, pass an instance of the store to the rateLimit function, like so:

const limiter = rateLimit({
	// ... other options,
	store: new ExternalStore(),
})

For a list of stores you can use, take a look at the data stores page.

For a tutorial on how to create your own store, see this.