ts-rate-limiter
Version:
High-performance, flexible rate limiting for TypeScript and Bun
53 lines (52 loc) • 2.09 kB
TypeScript
import type { RateLimiterOptions, RateLimitResult } from './types';
/**
* Extract a stable rate-limit identity from a request. The default
* key generator only handles IPs, but most apps want to bucket by
* authenticated user where possible and fall back to IP otherwise.
*
* Prefers (in order):
* 1. `request._authenticatedUser.id` (set by auth middleware)
* 2. `request._currentAccessToken.id`
* 3. `Authorization: Bearer <token>`
* 4. `x-forwarded-for` (first hop)
* 5. `x-real-ip`
* 6. `'anon'`
*
* Returning a stable string per "actor" means a single user behind a
* shared NAT can't trip the bucket for everyone else on the same IP.
*/
export declare function defaultIdentity(request: Request): string;
/**
* Rate limiter class with enhanced performance and features
*/
export declare class RateLimiter {
constructor(options: RateLimiterOptions);
check(request: Request): Promise<RateLimitResult>;
consume(key: string): Promise<RateLimitResult>;
peek(key: string): Promise<RateLimitResult | null>;
enforce(key: string): Promise<RateLimitResult>;
reset(key: string): Promise<void>;
resetAll(): Promise<void>;
middleware(): (req: Request) => Promise<Response | null>;
dispose(): void;
}
/**
* Error thrown by `RateLimiter.enforce(...)` when the bucket is full.
*
* Subclasses `Error` so it survives a `JSON.stringify` round-trip on
* the wire (frameworks that auto-serialize thrown errors will get the
* `name`, `message`, `retryAfter`, and `result` fields out of the box).
*
* Carries a numeric `retryAfter` (in **seconds**, matching the HTTP
* `Retry-After` header convention) and the underlying `RateLimitResult`
* so adapters can build a richer 429 response (Retry-After header,
* `RateLimit-Remaining`, body fields, etc.) without re-running the
* limiter to recover the data.
*/
export declare class RateLimitError extends Error {
readonly name: string;
readonly retryAfter: number;
readonly result: RateLimitResult;
constructor(message: string, result: RateLimitResult);
toHeaders(): Record<string, string>;
}