XRateLimiter

The XRateLimiter class provides intelligent rate limiting with tiered identification, multiple storage backends, and privacy-preserving hashing. It automatically registers as global middleware and classifies requests by trust level: authenticated users (highest), IP addresses (moderate), or browser fingerprints (lowest).

Contents
  1. Usage
  2. Configuration
  3. Storage Backends
  4. Identification Tiers
  5. Headers

Usage

Normally instantiation of middlewares before routes is accepted and middlewares are correctly applied. However, RateLimiter ignores bundle routes by default and MUST be instantiated after all routes are registered.

Basic setup

import { X } from "@ozanarslan/corpus";

// Default: memory store, 120/60/20 limits per minute
new X.RateLimiter();

Custom limits

new X.RateLimiter({
	limits: { u: 200, i: 100, f: 30 }, // 200 user, 100 IP, 30 fingerprint
	windowMs: 60_000, // 1 minute window
});

Configuration

RateLimitConfig

OptionTypeDefaultDescription
limitsRecord<"u" | "i" | "f", number>{ u: 120, i: 60, f: 20 }Request limits per tier
windowMsnumber60000Time window in milliseconds
saltRotateMsnumber86400000Salt rotation interval (24h)
cleanProbabilitynumber0.005Chance (0-1) of cleanup per request
maxStoreSizenumber50000Force cleanup threshold
storeType"memory" | "file" | "custom""memory"Storage backend
storeRateLimitStoreInterface | undefinedundefinedRequired when storeType is custom
storeDirstringos.tmpdir()Directory for file store
headerNamesobjectSee belowCustom header names

Default header names

{
	limit: "RateLimit-Limit",
	remaining: "RateLimit-Remaining",
	reset: "RateLimit-Reset",
	retryAfter: "Retry-After"
}

Storage Backends

Memory (default)

Fastest option. Resets on server restart. Best for single-instance deployments.

new X.RateLimiter({ storeType: "memory" });

File

Persistent across restarts. Good for single-instance deployments needing persistence.

new X.RateLimiter({
	storeType: "file",
	storeDir: "./data/rate-limits",
});

Custom

You probably want to use Redis for multi-instance deployments. Example adapter code can be found at XRateLimiter DIY.

class CustomStore implements X.RateLimitStoreInterface {
	// ...
}

new X.RateLimiter({
	storeType: "custom",
	store: new CustomStore(),
});

Identification Tiers

Requests are classified into tiers based on available identification:

TierPrefixSourceTrustDefault Limit
Useru:JWT token from Authorization headerHighest120
IPi:CF-Connecting-IP, X-Real-IP, or X-Forwarded-ForModerate60
Fingerprintf:Hash of User-Agent, Accept-Language, Accept-EncodingLowest20

Identification order

  1. Extracts JWT from Authorization: Bearer <token>
  2. Falls back to IP address validation
  3. Falls back to browser fingerprint

Privacy features

Headers

The middleware automatically sets rate limit headers on all responses:

HeaderDescription
RateLimit-LimitMaximum requests allowed in window
RateLimit-RemainingRemaining requests in current window
RateLimit-ResetUnix timestamp when window resets
Retry-AfterSeconds to wait (only when limited)
Access-Control-Expose-HeadersExposes rate limit headers to CORS

Custom header names

new X.RateLimiter({
	headerNames: {
		limit: "X-RateLimit-Limit",
		remaining: "X-RateLimit-Remaining",
		reset: "X-RateLimit-Reset",
		retryAfter: "Retry-After",
	},
});