📦 elithrar / workers-hono-rate-limit

Hono-compatible middleware for rate limiting requests with Cloudflare Workers.

106 stars 1 forks 👁 106 watching ⚖️ Apache License 2.0
📥 Clone https://github.com/elithrar/workers-hono-rate-limit.git
HTTPS git clone https://github.com/elithrar/workers-hono-rate-limit.git
SSH git clone git@github.com:elithrar/workers-hono-rate-limit.git
CLI gh repo clone elithrar/workers-hono-rate-limit
Loading files...
📄 README.md

@elithrar/workers-hono-rate-limit

Build & Test

Hono middleware for Cloudflare Worker's rate limiting bindings.

Install

npm install @elithrar/workers-hono-rate-limit

Usage

  • Add a rate limiting binding to your wrangler.toml (or wrangler.jsonc)
  • Define a RateLimitKeyFunc that returns the key to rate limit on
  • Apply the rateLimit 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.

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 keyFunc returns an empty string, rate limiting is bypassed for that request.

License

Apache 2.0 licensed. See the LICENSE file for details.