Overview

A store tracks how many hits each client (identified via their IP address) has received and automatically reduce that hit count as time elapses.

The Store Interface

A store must have the increment, decrement, and resetKey public methods. It may optionally have the init, get and resetAll public methods. For backwards compatibility with versions prior to 6.0.0, it may also have the incr and decr public methods. It also may have a constructor and any number of private methods.

The increment method is the primary interface between the middleware and the store. It adds 1 to the internal count for a key and returns an object consisting of the new internal count (totalHits) and the time that the count will reach 0 (resetTime).

The decrement method is used only to ‘uncount’ requests when one or both of the skipSuccessfulRequests or skipFailedRequests options are enabled.

The init method allows the store to set itself up using the options passed to the middleware. The store can get the windowMs option from this method.

The get method takes a string argument (the key that identifies a client) and returns an object consisting of the internal hit count (totalHits) and the time that the count will reach 0 (resetTime) for the given client. It may return undefined if it cannot find the key.

The resetKey method takes a string argument (the key that identifies a client) and sets the internal count for that key to zero.

The resetAll method takes no arguments and sets the internal count for all keys to zero.

The get and resetKey methods can be called from the middleware, like so:

// Create a rate limiter.
const limiter = rateLimit({
	/* ... */
})

// Fetch or reset the hit count for a key.
limiter.get('1.2.3.4')
limiter.resetKey('1.2.3.4')

Tutorial

A step-by-step guide to creating a store is as follows:

1

Configure dependencies

Add express-rate-limit as a peer dependency, and a development dependency to the package:

package.json
{
	"peerDependencies": {
		"express-rate-limit": ">= 6"
	},
	"devDependencies": {
		"express-rate-limit": "7"
	}
}

If the store supports the incr method, replace >= 6 with >= 2.3.0

2

Write the code for the store

3

Use the store

// Use `const ... = require('...')` instead if you are using CommonJS
import rateLimit from 'express-rate-limit'
import SomeStore from './some-store.js'

const limiter = rateLimit({
	store: new SomeStore({ customParam: true }),
})

If you encounter a bug or want to see something added/changed, please go ahead and open an issue! If you need help with something, feel free to start a discussion!