Cloudflare - v1.3.0
    Preparing search index...

    Class RateLimitService<E>

    Rate limiting capability, backed by Cloudflare's rate limiting binding.

    What this is for is the endpoint that cannot be addressed by an API key — a browser-facing route, or anything named in excludedRoutes — where there is no caller identity to hold accountable and the only lever left is how often one client may knock. The origin allowlist in SecurityMiddleware says who may call; this says how often.

    Enforcement is per Cloudflare location and eventually consistent, so treat the configured rate as a floor rather than a ceiling. That imprecision is fine for shedding abuse and wrong for anything a customer is billed against.

    By default the limiter is optional infrastructure: with no binding declared, every request is admitted. Override rateLimit.failOpen to false where an absent limiter would leave something genuinely exposed.

    const limits = new RateLimitService()

    api.post('/', async ctx => {
    if (!(await limits.admit(ctx.env, ctx.get('clientIp')))) {
    return ctx.json({ message: 'Too many requests', success: false, data: null }, 429)
    }
    // …
    })

    Bayu Dwiyan Satria

    1.0.0

    1.0.0

    Type Parameters

    Implements

    • RateLimiter<E>
    Index
    • Counts one request against a key and says whether to serve it.

      Parameters

      • env: E

        The Worker environment.

      • key: string

        What to count against — a client IP, a user id, a route name. Prefix it when one binding limits more than one thing, since the namespace is shared.

      Returns Promise<boolean>

      true when the request should be served, false when the caller is over its allowance and the route should answer 429.

      Calling this is what increments the counter, so call it once per request and act on the answer. Checking twice charges the caller twice.

    • Reports whether a limiter is bound to this Worker.

      Parameters

      • env: E

        The Worker environment.

      Returns boolean

      true when the binding is present.

      Worth logging at startup of a route that depends on one: with the default fail-open, an unbound limiter is indistinguishable from a limit nobody has reached yet.