Skip to main content
zerotal

Documentation


Documentation / @zerotal/core / index / RateLimiter

Class: RateLimiter

Defined in: middleware/RateLimiter.ts:150

Named rate-limiter registry.

Example

// In a ServiceProvider (boot time):
RateLimiter.for('api')
  .limit(120).every(60)
  .by(ctx => String(ctx.user?.id ?? ctx.request.headers.get('x-forwarded-for')))
  .register();

RateLimiter.for('login').limit(5).every(60).register();

// On a route:
Router.post('/login', AuthController, 'login', [
  RateLimiter.middleware('login'),
]);

// Manual check:
if (RateLimiter.tooManyAttempts('login', ctx)) {
  ctx.response = Response.json({ message: 'Too Many Requests' }, { status: 429 });
  return;
}

Constructors

Constructor

new RateLimiter(): RateLimiter

Returns

RateLimiter

Methods

for()

static for(name): LimiterDefinition

Defined in: middleware/RateLimiter.ts:174

Start building a named limiter. Call .register() at the end to make it available globally.

Parameters

name

string

Returns

LimiterDefinition

Example

RateLimiter.for('api').limit(100).every(60).register();

middleware()

static middleware(name): () => ThrottleMiddleware

Defined in: middleware/RateLimiter.ts:185

Get the ThrottleMiddleware for a registered named limiter. Throws if the limiter was never registered.

Parameters

name

string

Returns

() => ThrottleMiddleware

Example

Router.post('/login', AuthController, 'login', [RateLimiter.middleware('login')]);

tooManyAttempts()

static tooManyAttempts(name, ctx): Promise<boolean>

Defined in: middleware/RateLimiter.ts:218

Manually record a hit and check whether the limit is exceeded. Returns true when the caller should be throttled.

Unlike the middleware, this does NOT automatically send a 429 response — the caller decides how to handle the throttle condition.

Parameters

name

string

ctx

HttpContext

Returns

Promise<boolean>

Example

if (RateLimiter.tooManyAttempts('login', ctx)) {
  ctx.response = Response.json({ message: 'Too Many Requests' }, { status: 429 });
  return;
}

resetFor()

static resetFor(name, ctx): void

Defined in: middleware/RateLimiter.ts:244

Reset the rate-limit counter for a specific key within a named limiter.

Use this after a successful action to allow the actor to start fresh — e.g. clear failed login attempts after a successful authentication.

Parameters

name

string

ctx

HttpContext

Returns

void

Example

// In your LoginController:
await RateLimiter.resetFor('login', ctx);

clear()

static clear(): void

Defined in: middleware/RateLimiter.ts:251

Remove all registered limiters (useful in tests).

Returns

void