@jfungus/ratelimit-hono
v0.0.2
Published
Hono middleware for @jfungus/ratelimit
Maintainers
Readme
@jfungus/ratelimit-hono
Rate limiting middleware for Hono. Works with Cloudflare Workers, Deno, Bun, and Node.js.
Installation
npm install @jfungus/ratelimit-honoUsage
import { Hono } from "hono";
import { rateLimiter } from "@jfungus/ratelimit-hono";
const app = new Hono();
// Apply rate limiting to all routes
app.use(
rateLimiter({
limit: 100, // 100 requests
windowMs: 60 * 1000, // per 1 minute
}),
);
// Or apply to specific routes
app.use(
"/api/*",
rateLimiter({
limit: 50,
windowMs: 60 * 1000,
}),
);
app.get("/", (c) => c.text("Hello!"));
export default app;Options
| Option | Type | Default | Description |
| -------------- | ----------------------------------------------- | ------------------ | --------------------------------------- |
| limit | number | 100 | Max requests per window |
| windowMs | number | 60 * 1000 | Window size in milliseconds (1 minute) |
| algorithm | "sliding-window" | "fixed-window" | "sliding-window" | Rate limiting algorithm |
| keyGenerator | (c: Context) => string | IP-based | Function to generate unique key |
| skip | (c: Context) => boolean | - | Skip rate limiting for certain requests |
| handler | (c: Context, info: RateLimitInfo) => Response | 429 JSON | Custom rate limit exceeded handler |
| store | Store | MemoryStore | Custom storage backend |
Custom Key Generator
app.use(
rateLimiter({
limit: 100,
windowMs: 60 * 1000,
keyGenerator: (c) => {
// Rate limit by user ID instead of IP
return c.get("userId") || c.req.header("x-forwarded-for") || "anonymous";
},
}),
);Custom Handler
app.use(
rateLimiter({
limit: 100,
windowMs: 60 * 1000,
handler: (c, info) => {
return c.json(
{ error: "Too many requests", retryAfter: info.retryAfter },
429,
);
},
}),
);Distributed Storage
For multi-instance deployments, use @jfungus/ratelimit-unstorage:
import { createStorage } from "unstorage";
import redisDriver from "unstorage/drivers/redis";
import { createUnstorageStore } from "@jfungus/ratelimit-unstorage";
const storage = createStorage({
driver: redisDriver({ url: "redis://localhost:6379" }),
});
app.use(
rateLimiter({
limit: 100,
windowMs: 60 * 1000,
store: createUnstorageStore({ storage }),
}),
);Documentation
License
MIT
