@elithrar/workers-hono-rate-limit
v0.5.1
Published
Hono-compatible middleware for rate limiting requests with Cloudflare Workers.
Readme
@elithrar/workers-hono-rate-limit
Hono middleware for Cloudflare Worker's rate limiting bindings.
Install
npm install @elithrar/workers-hono-rate-limitUsage
- Add a rate limiting binding to your
wrangler.toml(orwrangler.jsonc) - Define a
RateLimitKeyFuncthat returns the key to rate limit on - Apply the
rateLimitmiddleware 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.
Async Key Functions
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 || "";
};Notes
- The key should represent a unique characteristic of a user or class of user. Good choices include API keys, user IDs, or tenant IDs.
- Avoid using IP addresses or locations as keys—these can be shared by many users.
- If your
keyFuncreturns an empty string, rate limiting is bypassed for that request.
License
Apache 2.0 licensed. See the LICENSE file for details.
