express-rate-limit
- Version 7.4.1
- Published
- 117 kB
- No dependencies
- MIT license
Install
npm i express-rate-limit
yarn add express-rate-limit
pnpm add express-rate-limit
Overview
Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
Index
Variables
Functions
Classes
Type Aliases
Variables
variable validations
const validations: { enabled: { [key: string]: boolean }; disable(): void; ip(ip: string | undefined): void; trustProxy(request: Request): void; xForwardedForHeader(request: Request): void; positiveHits(hits: any): void; unsharedStore(store: Store): void; singleCount(request: Request, store: Store, key: string): void; limit(limit: number): void; draftPolliHeaders(draft_polli_ratelimit_headers?: any): void; onLimitReached(onLimitReached?: any): void; headersResetTime(resetTime?: Date): void; validationsConfig(): void; creationStack(store: Store): void;};
Functions
function rateLimit
rateLimit: (passedOptions?: Partial<Options>) => RateLimitRequestHandler;
Create an instance of IP rate-limiting middleware for Express.
Parameter passedOptions
Options to configure the rate limiter.
Returns
{RateLimitRequestHandler} - The middleware that rate-limits clients based on your configuration.
Modifiers
@public
Classes
class MemoryStore
class MemoryStore implements Store {}
A
Store
that stores the hit count for each client in memory.Modifiers
@public
property current
current: Map<string, Client>;
property interval
interval?: NodeJS.Timeout;
A reference to the active timer.
property localKeys
localKeys: boolean;
Confirmation that the keys incremented in once instance of MemoryStore cannot affect other instances.
property previous
previous: Map<string, Client>;
These two maps store usage (requests) and reset time by key (for example, IP addresses or API keys).
They are split into two to avoid having to iterate through the entire set to determine which ones need reset. Instead,
Client
s are moved fromprevious
tocurrent
as they hit the endpoint. OncewindowMs
has elapsed, all clients left inprevious
, i.e., those that have not made any recent requests, are known to be expired and can be deleted in bulk.
property windowMs
windowMs: number;
The duration of time before which all hit counts are reset (in milliseconds).
method decrement
decrement: (key: string) => Promise<void>;
Method to decrement a client's hit counter.
Parameter key
The identifier for a client.
Modifiers
@public
method get
get: (key: string) => Promise<ClientRateLimitInfo | undefined>;
Method to fetch a client's hit count and reset time.
Parameter key
The identifier for a client.
Returns
{ClientRateLimitInfo | undefined} - The number of hits and reset time for that client.
Modifiers
@public
method increment
increment: (key: string) => Promise<ClientRateLimitInfo>;
Method to increment a client's hit counter.
Parameter key
The identifier for a client.
Returns
{ClientRateLimitInfo} - The number of hits and reset time for that client.
Modifiers
@public
method init
init: (options: Options) => void;
Method that initializes the store.
Parameter options
The options used to setup the middleware.
method resetAll
resetAll: () => Promise<void>;
Method to reset everyone's hit counter.
Modifiers
@public
method resetKey
resetKey: (key: string) => Promise<void>;
Method to reset a client's hit counter.
Parameter key
The identifier for a client.
Modifiers
@public
method shutdown
shutdown: () => void;
Method to stop the timer (if currently running) and prevent any memory leaks.
Modifiers
@public
Type Aliases
type AugmentedRequest
type AugmentedRequest = Request & { [key: string]: RateLimitInfo;};
The extended request object that includes information about the client's rate limit.
type Client
type Client = { totalHits: number; resetTime: Date;};
The record that stores information about a client - namely, how many times they have hit the endpoint, and when their hit count resets.
Similar to
ClientRateLimitInfo
, exceptresetTime
is a compulsory field.
type ClientRateLimitInfo
type ClientRateLimitInfo = { totalHits: number; resetTime: Date | undefined;};
Data returned from the
Store
when a client's hit counter is incremented.totalHits {number} - The number of hits for that client so far. resetTime {Date | undefined} - The time when the counter resets.
type DraftHeadersVersion
type DraftHeadersVersion = 'draft-6' | 'draft-7';
type EnabledValidations
type EnabledValidations = { [key in keyof Omit<Validations, 'enabled' | 'disable'> | 'default']?: boolean;};
Validate configuration object for enabling or disabling specific validations.
The keys must also be keys in the validations object, except
enable
,disable
, anddefault
.
type IncrementCallback
type IncrementCallback = ( error: Error | undefined, totalHits: number, resetTime: Date | undefined) => void;
Callback that fires when a client's hit counter is incremented.
Parameter error
The error that occurred, if any.
Parameter totalHits
The number of hits for that client so far.
Parameter resetTime
The time when the counter resets.
type IncrementResponse
type IncrementResponse = ClientRateLimitInfo;
type LegacyStore
type LegacyStore = { /** * Method to increment a client's hit counter. * * @param key {string} - The identifier for a client. * @param callback {IncrementCallback} - The callback to call once the counter is incremented. */ incr: (key: string, callback: IncrementCallback) => void; /** * Method to decrement a client's hit counter. * * @param key {string} - The identifier for a client. */ decrement: (key: string) => void; /** * Method to reset a client's hit counter. * * @param key {string} - The identifier for a client. */ resetKey: (key: string) => void; /** * Method to reset everyone's hit counter. */ resetAll?: () => void;};
An interface that all hit counter stores must implement.
Deprecated
6.x - Implement the
Store
interface instead.
type Options
type Options = { /** * How long we should remember the requests. * * Defaults to `60000` ms (= 1 minute). */ windowMs: number; /** * The maximum number of connections to allow during the `window` before * rate limiting the client. * * Can be the limit itself as a number or express middleware that parses * the request and then figures out the limit. * * Defaults to `5`. */ limit: number | ValueDeterminingMiddleware<number>; /** * The response body to send back when a client is rate limited. * * Defaults to `'Too many requests, please try again later.'` */ message: any | ValueDeterminingMiddleware<any>; /** * The HTTP status code to send back when a client is rate limited. * * Defaults to `HTTP 429 Too Many Requests` (RFC 6585). */ statusCode: number; /** * Whether to send `X-RateLimit-*` headers with the rate limit and the number * of requests. * * Defaults to `true` (for backward compatibility). */ legacyHeaders: boolean; /** * Whether to enable support for the standardized rate limit headers (`RateLimit-*`). * * Defaults to `false` (for backward compatibility, but its use is recommended). */ standardHeaders: boolean | DraftHeadersVersion; /** * The name of the property on the request object to store the rate limit info. * * Defaults to `rateLimit`. */ requestPropertyName: string; /** * If `true`, the library will (by default) skip all requests that have a 4XX * or 5XX status. * * Defaults to `false`. */ skipFailedRequests: boolean; /** * If `true`, the library will (by default) skip all requests that have a * status code less than 400. * * Defaults to `false`. */ skipSuccessfulRequests: boolean; /** * Method to generate custom identifiers for clients. * * By default, the client's IP address is used. */ keyGenerator: ValueDeterminingMiddleware<string>; /** * Express request handler that sends back a response when a client is * rate-limited. * * By default, sends back the `statusCode` and `message` set via the options. */ handler: RateLimitExceededEventHandler; /** * Method (in the form of middleware) to determine whether or not this request * counts towards a client's quota. * * By default, skips no requests. */ skip: ValueDeterminingMiddleware<boolean>; /** * Method to determine whether or not the request counts as 'succesful'. Used * when either `skipSuccessfulRequests` or `skipFailedRequests` is set to true. * * By default, requests with a response status code less than 400 are considered * successful. */ requestWasSuccessful: ValueDeterminingMiddleware<boolean>; /** * The `Store` to use to store the hit count for each client. * * By default, the built-in `MemoryStore` will be used. */ store: Store | LegacyStore; /** * The list of validation checks that should run. */ validate: boolean | EnabledValidations; /** * Whether to send `X-RateLimit-*` headers with the rate limit and the number * of requests. * * @deprecated 6.x - This option was renamed to `legacyHeaders`. */ headers?: boolean; /** * The maximum number of connections to allow during the `window` before * rate limiting the client. * * Can be the limit itself as a number or express middleware that parses * the request and then figures out the limit. * * @deprecated 7.x - This option was renamed to `limit`. However, it will not * be removed from the library in the foreseeable future. */ max?: number | ValueDeterminingMiddleware<number>; /** * If the Store generates an error, allow the request to pass. */ passOnStoreError: boolean;};
The configuration options for the rate limiter.
type RateLimitExceededEventHandler
type RateLimitExceededEventHandler = ( request: Request, response: Response, next: NextFunction, optionsUsed: Options) => void;
Express request handler that sends back a response when a client is rate-limited.
Parameter request
The Express request object.
Parameter response
The Express response object.
Parameter next
The Express
next
function, can be called to skip responding.Parameter optionsUsed
The options used to set up the middleware.
type RateLimitInfo
type RateLimitInfo = { limit: number; used: number; remaining: number; resetTime: Date | undefined;};
The rate limit related information for each client included in the Express request object.
type RateLimitReachedEventHandler
type RateLimitReachedEventHandler = ( request: Request, response: Response, optionsUsed: Options) => void;
Event callback that is triggered on a client's first request that exceeds the limit but not for subsequent requests. May be used for logging, etc. Should *not* send a response.
Parameter request
The Express request object.
Parameter response
The Express response object.
Parameter optionsUsed
The options used to set up the middleware.
type RateLimitRequestHandler
type RateLimitRequestHandler = RequestHandler & { /** * Method to reset a client's hit counter. * * @param key {string} - The identifier for a client. */ resetKey: (key: string) => void; /** * Method to fetch a client's hit count and reset time. * * @param key {string} - The identifier for a client. * * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. */ getKey: ( key: string ) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined;};
A modified Express request handler with the rate limit functions.
type Store
type Store = { /** * Method that initializes the store, and has access to the options passed to * the middleware too. * * @param options {Options} - The options used to setup the middleware. */ init?: (options: Options) => void; /** * Method to fetch a client's hit count and reset time. * * @param key {string} - The identifier for a client. * * @returns {ClientRateLimitInfo} - The number of hits and reset time for that client. */ get?: ( key: string ) => Promise<ClientRateLimitInfo | undefined> | ClientRateLimitInfo | undefined; /** * Method to increment a client's hit counter. * * @param key {string} - The identifier for a client. * * @returns {IncrementResponse | undefined} - The number of hits and reset time for that client. */ increment: (key: string) => Promise<IncrementResponse> | IncrementResponse; /** * Method to decrement a client's hit counter. * * @param key {string} - The identifier for a client. */ decrement: (key: string) => Promise<void> | void; /** * Method to reset a client's hit counter. * * @param key {string} - The identifier for a client. */ resetKey: (key: string) => Promise<void> | void; /** * Method to reset everyone's hit counter. */ resetAll?: () => Promise<void> | void; /** * Method to shutdown the store, stop timers, and release all resources. */ shutdown?: () => Promise<void> | void; /** * Flag to indicate that keys incremented in one instance of this store can * not affect other instances. Typically false if a database is used, true for * MemoryStore. * * Used to help detect double-counting misconfigurations. */ localKeys?: boolean; /** * Optional value that the store prepends to keys * * Used by the double-count check to avoid false-positives when a key is counted twice, but with different prefixes */ prefix?: string;};
An interface that all hit counter stores must implement.
type Validations
type Validations = typeof validations;
type ValueDeterminingMiddleware
type ValueDeterminingMiddleware<T> = ( request: Request, response: Response) => T | Promise<T>;
Method (in the form of middleware) to generate/retrieve a value based on the incoming request.
Parameter request
The Express request object.
Parameter response
The Express response object.
Returns
{T} - The value needed.
Package Files (1)
Dependencies (0)
No dependencies.
Dev Dependencies (22)
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/express-rate-limit
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/express-rate-limit)
- HTML<a href="https://www.jsdocs.io/package/express-rate-limit"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 3664 ms. - Missing or incorrect documentation? Open an issue for this package.