๐Ÿšฆ Rate Limit Middleware

Prevent Abuse & Overload

This example demonstrates how to apply a simple rate-limiting middleware using rateLimit(). It limits each client to a maximum number of requests per time window.

Helps protect your API from spamming, scraping, and denial-of-service attacks.

๐Ÿ”ง Example Code

import { Server, json, rateLimit} from "tirne";
import type { Route } from "tirne";

const limiter = rateLimit({
  windowMs: 60_000, // 1 minute window
  max: 5,           // limit each client to 5 requests per window
});

const routes: Route[] = [
  {
    method: "GET",
    path: "/limited",
    handler: () => json({ message: "You are within rate limit!" }),
    middleware: [limiter],
  },
];

const server = new Server(routes);

export default {
  fetch: (req: Request) => server.fetch(req),
};

๐Ÿงช Functionality Check

Test the rate-limited endpoint using curl repeatedly:

1. โœ… First 5 Requests (within 1 minute)

curl http://localhost:3000/limited
{ "message": "You are within rate limit!" }

2. โŒ 6th Request Within the Same Minute

{
  "error": "rate_limit",
  "message": "Too many requests"
}