To create a rate limiting middleware for Cloudflare Hono that limits IP addresses, you can follow the example below. This middleware will track the number of requests from a specific IP address within a given time frame and block further requests if the limit is exceeded.
First, ensure you have Hono installed. If not, you can add it to your project by running:
npm install hono
Here's an example of a simple rate limiting middleware. This example uses a simple in-memory store for demonstration purposes. For a production environment, you might want to use a more robust store like Redis to persist the request counts across server restarts or deployments.
import { Hono } from 'hono';
// Simple in-memory store for rate limiting
const rateLimitStore = new Map();
const rateLimit = (options = {}) => {
const { maxRequests = 100, timeWindow = 60 * 1000 } = options; // 100 requests per minute by default
return async (c, next) => {
const ip = c.req.header('CF-Connecting-IP') || c.req.header('X-Forwarded-For') || c.req.header('X-Real-IP');
if (!ip) {
return c.text('Unable to determine IP address', 403);
}
const now = Date.now();
const key = ip;
if (rateLimitStore.has(key)) {
const { count, timestamp } = rateLimitStore.get(key);
if (now - timestamp < timeWindow) {
if (count >= maxRequests) {
return c.text(`Rate limit exceeded. Try again in ${Math.ceil((timeWindow - (now - timestamp)) / 1000)} seconds.`, 429);
} else {
rateLimitStore.set(key, { count: count + 1, timestamp });
}
} else {
// Reset the count if the time window has passed
rateLimitStore.set(key, { count: 1, timestamp: now });
}
} else {
rateLimitStore.set(key, { count: 1, timestamp: now });
}
await next();
};
};
const app = new Hono();
app.use('*', rateLimit({
maxRequests: 50, // Example: 50 requests
timeWindow: 30 * 1000 // Example: within 30 seconds
}));
app.get('/', (c) => c.text('Hello, World!'));
export default app;
This middleware does the following:
- Checks for the client's IP address using headers typically set by proxies like Cloudflare (
CF-Connecting-IP, X-Forwarded-For, X-Real-IP).
- Uses an in-memory map (
rateLimitStore) to track the number of requests from each IP address.
- For each request, it checks if the IP is within its allowed rate. If not, it returns a 429 response.
- If the request is within the allowed rate, it increments the count for that IP and allows the request to proceed.
For a production-grade solution, consider the following adjustments:
- Use a distributed store: Instead of an in-memory store, use a distributed store like Redis to ensure that the rate limiting is applied across all instances of your application.
- Implement more sophisticated rate limiting logic: Depending on your needs, you might want to implement a sliding window algorithm or a leaky bucket algorithm for more nuanced rate limiting.
- Customize headers and responses: Adjust the headers and response bodies to better fit your application's needs or to comply with specific standards or regulations.
This example provides a basic starting point. Depending on your specific requirements, you may need to adjust or extend it.