@unkey/ratelimit (version ) is a small wrapper around the ratelimit.limit endpoint for code that user IDs, IP addresses, or anything else without issuing API keys. You set the namespace and limit once, so each check is one line. It also answers from memory for identifiers that are already blocked, and returns a fallback answer if the API takes too long.
You need a root key with the permissions listed on this page. Create one in the dashboard under Settings > Root Keys, and pass it as
Authorization: Bearer <root key>. See Permission reference for every permission.Install
Configure
string
required
Root key used to call the API.
string
required
Rate limit namespace, created on first use. Identifiers are counted separately in each namespace.
number
required
Requests allowed per window.
Duration | number
required
Window length as milliseconds or a string such as
"30s", "5 m", "1h", or "1d" (units ms, s, m, h, d).{ ms: Duration | number, fallback: RatelimitResponse | (identifier) => RatelimitResponse } | false
How long to wait for the API before returning
fallback. Defaults to 5 seconds with a fallback that denies the request. Set false to wait indefinitely.(err: Error, identifier: string) => RatelimitResponse | Promise<RatelimitResponse>
Called when the request fails, and its return value becomes the result. Without it the error is thrown.
string
Alternative API URL. You don’t normally need to set it.
Map<string, RatelimitResponse>
Storage for the local memory of blocked identifiers. Defaults to a new
Map. Pass your own to share it across instances.boolean
Opt out of the library’s telemetry.
Use it
limit(identifier, opts?) returns { success, limit, remaining, reset, overrideId? }. reset is Unix milliseconds, and overrideId is set when an override applied. The optional second argument takes cost (default 1) and limit: { limit, duration } to use a different limit for this call:
reset, so a client hammering a blocked identifier doesn’t cause more API calls.
Make it fail safe
If the API can’t be reached and your rate limiter denies everything, your endpoint goes down too. Set a timeout and an error handler to decide what happens:Scope
Ratelimit wraps ratelimit.limit. The package also has:
Overrides, which takes the samerootKeyandbaseUrland hasgetOverride,setOverride,deleteOverride, andlistOverrides. See ratelimit.setOverride.NoopRatelimit, which works the same way without any network calls. Use it in tests.