@chirag127/rate-limit
v1.0.0
Published
Edge-ready rate limiter for CF Workers and Astro endpoints
Maintainers
Readme
@chirag127/rate-limit
Edge-ready rate limiter for Cloudflare Workers and Astro API endpoints.
Supports CF KV as store or falls back to in-memory Map with TTL.
Install
npm i @chirag127/rate-limitUsage
Core
import { rateLimit } from '@chirag127/rate-limit';
const limiter = rateLimit({ limit: 10, window: 60, keyPrefix: 'api' });
// CF Worker — pass env.MY_KV as store
const { allowed, remaining, resetAt } = await limiter.check(clientIp, env.MY_KV);
// In-memory fallback (no store arg)
const result = await limiter.check(clientIp);Astro middleware
// src/middleware.js
import { rateLimitMiddleware } from '@chirag127/rate-limit/middleware';
export const onRequest = rateLimitMiddleware({
limit: 20,
window: 60,
keyPrefix: 'web',
// optional: provide CF KV binding via Astro locals / runtime
// store: runtime.env.RATE_LIMIT_KV,
// optional: custom key function
// keyFn: (req) => req.headers.get('cf-connecting-ip') ?? 'anon',
});API
rateLimit(opts)
| Option | Type | Default | Description |
|---|---|---|---|
| limit | number | 10 | Max requests per window |
| window | number | 60 | Window duration in seconds |
| keyPrefix | string | 'rl' | KV/memory key prefix |
Returns a limiter object.
limiter.check(key, store?)
| Param | Type | Description |
|---|---|---|
| key | string | Client identifier (IP, user ID, etc.) |
| store | CF KV namespace | Optional; falls back to in-memory |
Returns Promise<{ allowed: boolean, remaining: number, resetAt: Date }>.
rateLimitMiddleware(opts)
Same opts as rateLimit plus:
| Option | Type | Description |
|---|---|---|
| store | CF KV namespace | Optional KV binding |
| keyFn | (req: Request) => string | Custom key extractor |
Returns an Astro onRequest middleware function. Sends 429 with Retry-After header when limit exceeded. Adds X-RateLimit-* headers to every response.
License
MIT
