Hono-compatible middleware for rate limiting requests with Cloudflare Workers.
https://github.com/elithrar/workers-hono-rate-limit.git
Hono middleware for Cloudflare Worker's rate limiting bindings.
npm install @elithrar/workers-hono-rate-limit
wrangler.toml (or wrangler.jsonc)RateLimitKeyFunc that returns the key to rate limit onrateLimit middleware to your routes# wrangler.toml
[[ratelimits]]
binding = "RATE_LIMITER"
namespace_id = "1001"
# 25 requests per 10 seconds
simple = { limit = 25, period = 10 }
import { rateLimit, RateLimitBinding, RateLimitKeyFunc } from "@elithrar/workers-hono-rate-limit";
import { Hono } from "hono";
type Bindings = {
RATE_LIMITER: RateLimitBinding;
};
const app = new Hono<{ Bindings: Bindings }>();
// Rate limit on each API token
const getKey: RateLimitKeyFunc = (c) => c.req.header("Authorization") || "";
// Apply rate limiting to all routes
app.use("*", (c, next) => rateLimit(c.env.RATE_LIMITER, getKey)(c, next));
app.get("/", (c) => c.text("hello!"));
export default app;
You can create multiple rateLimit instances with different configurations and key functions for each use-case, or apply the same instance to multiple route patterns via app.use.
The keyFunc can also be async if you need to look up user information:
const getKey: RateLimitKeyFunc = async (c) => {
const user = await validateToken(c.req.header("Authorization"));
return user?.id || "";
};
keyFunc returns an empty string, rate limiting is bypassed for that request.Apache 2.0 licensed. See the LICENSE file for details.