How to Rate Limit Specific Routes in Cloudflare Workers using @hono-rate-limiter/cloudflare? #29
-
I am using Cloudflare Workers with the Hono framework and the @hono-rate-limiter/cloudflare package to implement rate limiting. However, I only want to apply rate limiting to certain routes (e.g., /api/data, /api/user), rather than all routes in my application. Could anyone guide me on how to configure the rate limiter to apply only on specific routes in Cloudflare Workers using this package? For example, I currently have the following code: const app = new Hono<AppType>().use(
cloudflareRateLimiter<AppType>({
rateLimitBinding: (c) => c.env.RATE_LIMITER,
keyGenerator: (c) => c.req.header("cf-connecting-ip") ?? "", // Method to generate custom identifiers for clients.
})
); This setup applies rate limiting to the entire application. Is there a way to apply rate limiting only to certain routes, while allowing other routes to bypass it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You can control which routes are affected by the rate limiter by applying it as middleware only to the specific routes you want. The rate limiter in Hono works like any other middleware, so instead of using For example, you can do something like this: const app = new Hono<AppType>();
// Apply rate limiter only to /api/data and /api/user
app.get('/api/data', cloudflareRateLimiter<AppType>({
rateLimitBinding: (c) => c.env.RATE_LIMITER,
keyGenerator: (c) => c.req.header("cf-connecting-ip") ?? "",
}), (c) => {
// Your route handler for /api/data
});
app.get('/api/user', cloudflareRateLimiter<AppType>({
rateLimitBinding: (c) => c.env.RATE_LIMITER,
keyGenerator: (c) => c.req.header("cf-connecting-ip") ?? "",
}), (c) => {
// Your route handler for /api/user
}); Or if you have grouped routes, you can do: const userRoutes = new Hono<AppType>();
userRoutes.get('/data', (c) => {
// Your route handler for /api/data
});
userRoutes.get('/user', (c) => {
// Your route handler for /api/user
});
app.route('/api', cloudflareRateLimiter<AppType>({
rateLimitBinding: (c) => c.env.RATE_LIMITER,
keyGenerator: (c) => c.req.header("cf-connecting-ip") ?? "",
}), userRoutes); This way, rate limiting is applied only to the For more details about how the middleware works, you can check the Hono documentation. |
Beta Was this translation helpful? Give feedback.
-
@MathurAditya724 is this also possible using rateLimiter with durable objects or inside the route logic? It seems I can't use hono's context when defining a store. |
Beta Was this translation helpful? Give feedback.
You can control which routes are affected by the rate limiter by applying it as middleware only to the specific routes you want. The rate limiter in Hono works like any other middleware, so instead of using
app.use
globally, you can attach it directly to specific routes or route groups.For example, you can do something like this: