Security

Rate Limiting

Protect your API from brute-force attacks and abuse.

Rate Limit

Limit the number of requests a client can make within a time window.

Installation

bun add @bklarjs/rate-limit
npm install @bklarjs/rate-limit

Usage

import { rateLimit } from "@bklarjs/rate-limit";

// Limit to 100 requests per 15 minutes
app.use(
  rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
    message: "Too many requests, please try again later.",
  })
);

Custom Key Generator

By default, it limits by IP. You can limit by API Key or User ID.

app.use(
  rateLimit({
    keyGenerator: (ctx) => {
      // Limit by Authenticated User ID
      return ctx.state.jwt?.sub || ctx.req.headers.get("x-api-key");
    },
  })
);

On this page