π¦ Rate Limiter
Understand how to control actions per key over a time interval using Toolkitify RateLimiter.
Overview
The RateLimiter class in Toolkitify lets you control how many times an action can be performed per key within a defined interval. You can customize:
- Limit β Maximum number of allowed actions in the interval.
- Interval β Duration over which the limit applies (milliseconds or string like
"10s","1m","1h"). - Storage β Where the limiter keeps its data:
"memory"β In-memory, per server instance."sessionStorage"β Browser session storage."localStorage"β Browser local storage."redis"β Shared storage across multiple servers (requires a Redis client).
- Key β Identifier for tracking usage.
- Logs β Enable console logs for debugging.
Creating a RateLimiter Instance
import { RateLimiter } from "toolkitify/rate-limit";
const limiter = new RateLimiter({
logs: true // enable logs for debugging
});
You can then use limiter.check() to validate a key against a limit:
const result = await limiter.check({
key: "user:123",
limit: 5,
interval: "10s",
blockDuration: "10s" // Optional: Default value is the same as interval.
storage: "memory"
});
if (!result.success) {
console.log(`Limit reached. Try again at ${new Date(result.reset).toLocaleTimeString()}`);
} else {
console.log(`Action allowed. Remaining: ${result.remaining}/${result.limit}`);
}
Key Points
- The limiter automatically resets the count after the interval expires.
remainingtells you how many actions are left before hitting the limit.resetgives the exact timestamp when the limit resets.- Using Redis allows the limiter to work across multiple server instances.
Example
RateLimiter ExampleCode Sandbox
This focuses entirely on the RateLimiter class and its configuration, without tying it to IPs, email, or any other example.
If you want, I can also make a full MDX page with separate sections for each storage type like memory, sessionStorage, localStorage, and Redis, showing live examples for each. This would match the style of your TTL & Max Uses page. Do you want me to do that?