Here's a Hono middleware for IP rate limiting using an in-memory store. This example assumes you're running behind Cloudflare, which sets the CF-Connecting-IP header:
javascript
// rate-limit.js
import { Hono } from 'hono';
// Function to extract client IP from Cloudflare headers
const getIP = (req) => {
const cfIp = req.headers.get('cf-connecting-ip');
if (cfIp) return cfIp;
const xff = req.headers.get('x-forwarded-for');
if (xff) {
return xff.split(',', 1)[0].trim();
}
// Fallback to remote address (may not be available in some environments)
return req.socket?.remoteAddress;
};
// Rate limiting middleware factory
export const rateLimitMiddleware = (maxRequests, windowMs) => {
const store = new Map(); // { [ip]: { count, timestamp } }
return async (ctx, next) => {
const ip = getIP(ctx.req);
if (!ip) {
return ctx.unauthorized('Invalid IP address');
}
const now = Date.now();
// Check existing entry
if (store.has(ip)) {
const { count, timestamp } = store.get(ip);
// Window expired - reset
if (now - timestamp > windowMs) {
store.set(ip, { count: 1, timestamp: now });
} else {
// Check limit
if (count >= maxRequests) {
return ctx.status(429).send('Too Many Requests');
}
// Increment count
store.set(ip, { count: count + 1, timestamp });
}
} else {
// First request from new IP
store.set(ip, { count: 1, timestamp: now });
}
// Proceed to next middleware/route
await next();
};
};
To use this middleware in your Hono app:
javascript
// app.js
import { Hono } from 'hono';
import { rateLimitMiddleware } from './rate-limit';
const app = new Hono();
// Apply rate limit to all routes (max 100 requests per minute)
app.use('*', rateLimitMiddleware(100, 60 * 1000));
// Your routes go here
app.get('/', (c) => c.text('Hello World'));
export default app;
Key features:
Uses Cloudflare's CF-Connecting-IP header for accurate IP detection
Fallbacks to X-Forwarded-For and remote address
In-memory storage with automatic window expiration
Returns proper 429 status for exceeded limits
Important considerations:
This uses an in-memory store - not suitable for multi-process deployments
For production, consider using a persistent store like Redis
The rate limit window is fixed (e.g., 60 seconds)
Doesn't handle IP spoofing - relies on Cloudflare's headers
No persistence between server restarts
To make this production-ready, you could:
Add Redis integration using redis package
Add metrics and logging
Add configurable headers (like Retry-After)
Add support for different rate limits per route
Implement distributed locks if needed
Would you like me to show an example with Redis integration?