@davaux/rate-limit
v0.9.0
Published
Rate limiting middleware for Davaux
Readme
@davaux/rate-limit
Rate limiting middleware for Davaux.
Installation
npm install @davaux/rate-limitSetup
// davaux.config.ts
import { defineConfig } from 'davaux/config'
import { rateLimit } from '@davaux/rate-limit'
export default defineConfig({
middleware: [
rateLimit({ windowMs: 60_000, max: 100 }),
],
})Or scope it to specific routes via _middleware.ts:
// src/routes/api/_middleware.ts
import { rateLimit } from '@davaux/rate-limit'
export default rateLimit({ windowMs: 60_000, max: 20 })Options
| Option | Type | Default | Description |
|---|---|---|---|
| windowMs | number | — | Time window in milliseconds (required) |
| max | number | — | Maximum requests per window per key (required) |
| keyFn | (ctx) => string | Client IP | Function to derive the rate-limit key |
| message | string | 'Too Many Requests' | Body of the 429 response |
| store | RateLimitStore | MemoryStore | Backing store for counters |
| headers | boolean | true | Send RateLimit-* headers on every response |
| trustProxy | boolean | false | Use X-Forwarded-For as the key. Only enable behind a trusted reverse proxy |
Custom store
Implement RateLimitStore to use Redis, Valkey, or any other distributed backend:
import type { RateLimitStore, RateLimitResult } from '@davaux/rate-limit'
class RedisStore implements RateLimitStore {
async increment(key: string, windowMs: number): Promise<RateLimitResult> {
// ...
}
}
rateLimit({ windowMs: 60_000, max: 100, store: new RedisStore() })