API Reference
Table of Contents
- RateLimiter
- RateLimiterOptions
- Result Shape
- Store Interface
- RedisStore
- CacheHubStore
- keyGenerators
- Detailed Method Reference
- Configuration Option Details
- Middleware Behavior
- Headers
- Exports
- Examples
- Errors and Troubleshooting
- Related Docs
RateLimiter
check(key, options)
middleware(options)
Creates an Express-style (req, res, next) middleware.
reset(key)
resetAll()
close()
Closes limiter-owned resources, such as Redis clients created from store: 'redis://...' and cache-hub memory cleanup timers.
RateLimiterOptions
Result Shape
Store Interface
Stores must provide generic counter operations and may provide algorithm-specific atomic methods.
RedisStore
External Redis clients are caller-owned by default. Set ownsClient: true when store.close() should close the client.
CacheHubStore
CacheHubStore uses cache-hub@2.2.4 atomic state primitives. It can run with Redis or with a local in-memory cache-hub backend.
keyGenerators
Detailed Method Reference
new RateLimiter(options)
Creates a limiter instance.
Constructor defaults:
check(key, options)
Checks one key directly. This is the framework-agnostic API and is the right integration point for Koa, Egg.js, Fastify, Hapi, workers, queues, and custom runtimes.
Parameters:
Return value:
retryAfter is 0 when the request is allowed. When rejected, it is the suggested wait time in milliseconds.
middleware(options)
Creates an Express-style middleware function:
The middleware signature is:
For non-Express frameworks, wrap check() instead of using the Express-style middleware directly.
reset(key)
Clears rate-limit state for a single key.
Use this when an operator manually unlocks a user, when a test needs a clean key, or when a business workflow resets a quota.
resetAll()
Clears all state for stores that support it.
MemoryStore, RedisStore, and CacheHubStore implement resetAll(). For Redis-backed stores, use a dedicated prefix so reset operations do not touch unrelated application keys.
close()
Closes limiter-owned resources.
Use close() during application shutdown, tests, benchmark scripts, and short-lived CLI tools.
Lifecycle behavior:
Configuration Option Details
windowMs
The size of the rate-limit time window in milliseconds.
Use longer windows for security-sensitive actions and shorter windows for high-throughput operational throttling.
max
Maximum allowed count for the selected algorithm. It can be a number or an async function.
Dynamic example:
algorithm
Supported values:
store
Supported values:
keyGenerator
Generates the limit key from a request object.
skip
Skips rate limiting for a request.
Common uses:
- IP allowlist.
- Health checks.
- Internal service accounts.
- Temporary operational bypasses.
handler
Customizes the response when a request is rejected.
If no handler is provided, middleware returns status 429 with a basic message.
headers
Controls whether middleware writes rate-limit headers.
skipSuccessfulRequests and skipFailedRequests
These options are middleware-focused rollback controls.
skipSuccessfulRequests: count the request during processing, then roll it back if the response status is below400.skipFailedRequests: count the request during processing, then roll it back if the response status is400or above.
Use these options when the quota should count only failed attempts or only successful business actions. They are not needed for direct check() usage.
perRoute
Overrides options for specific routes.
Route matching uses the route context available to the limiter. When integrating manually, pass route to check().
capacity, refillRate, and leakRate
Algorithm-specific tuning options:
Middleware Behavior
Middleware flow:
Default rejection response:
Use a custom handler when your API needs a structured error payload.
Headers
When headers is enabled, middleware writes common rate-limit headers:
Exact header availability can depend on the framework response object because middleware uses the Express-style response API.
Exports
CommonJS:
ESM:
Default export:
Examples
Basic Direct Usage
Express Middleware
Koa Manual Integration
RedisStore
The external Redis client remains caller-owned. Close it in your application shutdown code.
Redis Connection String
In this path the limiter owns the Redis client.
CacheHubStore
Use CacheHubStore when you want to reuse cache-hub atomic state primitives, especially with Redis-backed state.
Business Lock Key
This gives each user an independent budget for each route.
Errors and Troubleshooting
键必须是非空字符串
check() and reset() require a non-empty string key.
Fix:
Redis client is required
new RedisStore() requires a Redis-compatible client.
Fix:
resetAll() is unsupported
The store does not implement resetAll().
Fix: use a built-in store that supports it, or reset known keys individually.
Requests are all sharing one limit
The key generator is probably too coarse.
Fix: include the right identity and route dimensions:
Redis connections remain open in tests
Call close() for limiter-owned clients, and close external clients yourself.