Hono Rate Limiter Middleware

0.5.3 · active · verified Wed Apr 22

hono-rate-limiter is a middleware library designed for the Hono web framework, providing robust rate-limiting capabilities for both HTTP API endpoints and WebSocket connections. Its current stable version is 0.5.3, with minor releases occurring relatively frequently, indicating active development. The library is inspired by the widely-used `express-rate-limit` and aims to bring similar comprehensive functionality to Hono applications, focusing on developer experience and flexibility. A key differentiator is its flexible storage mechanism, now supporting Unstorage, which allows developers to integrate various backends like Redis, Cloudflare KV, or file systems for persistent rate limit tracking. It simplifies the process of protecting Hono routes from abuse and ensures API stability under high traffic, offering fine-grained control over rate limits and responses.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and apply the `rateLimiter` middleware to a Hono application, configure basic limits, and use an in-memory store.

import { Hono } from 'hono';
import { rateLimiter } from 'hono-rate-limiter';
import { MemoryStore } from 'hono-rate-limiter/stores';

const app = new Hono();

// Configure the rate limiter middleware
const limiter = rateLimiter({
  windowMs: 60 * 1000, // 1 minute
  limit: 5, // Limit each IP to 5 requests per minute
  standardHeaders: 'draft-7', // Set standard rate limit headers
  legacyHeaders: false, // Disable X-RateLimit-* headers
  // keyGenerator: (c) => c.req.ip, // Uses client IP by default if not provided
  store: new MemoryStore(), // In-memory store (not recommended for production)
  message: 'You are making too many requests. Please try again soon.',
  handler: (c) => {
    return c.json({
      status: 429,
      message: 'Too many requests, please try again after some time.'
    }, 429)
  }
});

// Apply the rate limiter globally or to specific routes
app.use(limiter);

app.get('/', (c) => {
  return c.text('Welcome to the Hono Rate Limited API!');
});

app.get('/protected', (c) => {
  return c.json({ data: 'This is protected data.' });
});

export default app;

view raw JSON →