rateLimit() middleware uses Cloudflare KV to implement a sliding-window counter at the edge. Because KV is globally distributed, every Cloudflare datacenter enforces the same limit against the same shared counter — making this approach well-suited to API rate limiting where consistency matters more than sub-millisecond precision.
Setup
First, declare a KV namespace binding in yourwrangler.toml:
Env type so req.env.RATE_LIMIT_KV is typed correctly:
Basic usage
RateLimitOptions reference
string | (req) => KVNamespace
required
The KV namespace to use as the counter store. Pass a resolver function (
(req) => req.env.RATE_LIMIT_KV) to resolve it from req.env, or pass the binding name as a string ('RATE_LIMIT_KV') and Blaze resolves it automatically.number
required
Maximum number of requests allowed per
window period. Requests beyond this limit receive a 429 Too Many Requests response.number
required
Window size in seconds. The counter resets at the start of each window. For example,
window: 60 creates per-minute buckets.(req) => string
Function that derives the rate-limit key from the request. Defaults to
req.ip (the CF-Connecting-IP header). Use this to implement per-user, per-token, or per-route-and-IP limits.string
default:"'Too Many Requests'"
The error message returned in the
429 JSON response body.Custom key functions
The default key is the client IP address. OverridekeyFn to implement per-user or per-API-key limits:
Per-route limits
ApplyrateLimit() directly on individual routes to enforce different limits for different endpoints:
Response headers
Every response — whether allowed or blocked — includes rate-limit headers so clients can track their usage and implement backoff:
A client hitting the limit sees:
X-RateLimit-Remaining to slow down proactively before hitting the limit, and Retry-After to implement automatic retry logic on 429 responses.