> ## Documentation Index
> Fetch the complete documentation index at: https://www.unkey.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Unkey is two separate products. Compute builds, deploys, and runs apps behind a gateway. API Management issues API keys, enforces rate limits, manages identities and permissions, and reports usage. Say which product a page belongs to; a reader can use either without the other.
> Every Unkey API endpoint is an HTTP POST to https://api.unkey.com/v2/{service}.{procedure} with a root key in the Authorization: Bearer header. Root keys are workspace scoped.
> Error codes have the form err:{system}:{category}:{specific} and each has a page at /errors/{system}/{category}/{specific}.
> The word environment means production or preview in Compute. Rate limiting has four meanings on this site; the glossary lists them.

# @unkey/ratelimit

> Rate limit from serverless functions with a timeout fallback built in.

Use `@unkey/ratelimit` (version 2.1.4) to rate limit a Next.js route, an Express handler, or any other TypeScript server. You pass a user id, a customer id, or an IP address, and Unkey keeps the counters, so there's no Redis to run. The old Next.js and Express rate limit quickstarts point here.

The package wraps `ratelimit.limit`. You set the namespace and limit once, so each check is one line. It answers from memory for identifiers that are already blocked, and it returns a fallback answer if the API takes too long. It doesn't issue API keys. For a limit stored on a key, including a monthly credit quota, see [Key and identity rate limits](https://www.unkey.com/docs/api-management/ratelimiting/key-and-identity-limits.md).

> [!NOTE]
>
> Create a root key with the permissions listed on this page under **Root Keys** in the dashboard sidebar. CLI commands can instead use a session from [unkey login](https://www.unkey.com/docs/platform/cli/login.md) with the required permissions. See [Permission reference](https://www.unkey.com/docs/platform/root-keys/permissions-legacy.md) for every permission.

## Install

```bash theme={"system"}
npm install @unkey/ratelimit
```

## Configure

```typescript theme={"system"}
import { Ratelimit } from "@unkey/ratelimit";

const limiter = new Ratelimit({
  rootKey: process.env.UNKEY_ROOT_KEY ?? "",
  namespace: "email.send",
  limit: 10,
  duration: "30s",
});
```

**rootKey** `string` *required*

Root key used to call the API.

**namespace** `string` *required*

Rate limit namespace, created on first use. Identifiers are counted separately in each namespace.

**limit** `number` *required*

Requests allowed per window.

**duration** `Duration | number` *required*

Window length as milliseconds or a string such as `"30s"`, `"5 m"`, `"1h"`, or `"1d"` (units `ms`, `s`, `m`, `h`, `d`).

**timeout** `\{ 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.

**onError** `(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.

**baseUrl** `string`

Alternative API URL. You don't normally need to set it.

**cache** `Map\<string, RatelimitResponse\>`

Storage for the local memory of blocked identifiers. Defaults to a new `Map`. Pass your own to share it across instances.

**disableTelemetry** `boolean`

Opt out of the library's telemetry.

## Use it

The same `limiter` works in a Next.js route handler and in Express. `limit` returns `{ success, limit, remaining, reset }`. Unkey's HTTP response to your server is 200 even when `success` is `false`, so your handler is the one that returns `429 Too Many Requests`. [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585#section-4) defines that status and allows `Retry-After` in seconds. `reset` is Unix milliseconds. This package doesn't set rate limit headers for you.

```typescript app/api/search/route.ts theme={"system"}
export async function POST(request: Request) {
  const userId = request.headers.get("x-user-id") ?? "anonymous";
  const result = await limiter.limit(userId);

  if (!result.success) {
    const retryAfter = Math.max(1, Math.ceil((result.reset - Date.now()) / 1000));
    return new Response("Too many requests", {
      status: 429,
      headers: {
        "Retry-After": String(retryAfter),
        "X-RateLimit-Limit": String(result.limit),
        "X-RateLimit-Remaining": String(result.remaining),
        "X-RateLimit-Reset": String(Math.floor(result.reset / 1000)),
      },
    });
  }

  return new Response("ok");
}
```

```typescript middleware.ts theme={"system"}
import { Ratelimit } from "@unkey/ratelimit";
import type { NextFunction, Request, Response } from "express";

function rateLimit(limiter: Ratelimit) {
  return async (req: Request, res: Response, next: NextFunction) => {
    const userId = req.header("x-user-id") ?? req.ip ?? "anonymous";
    const result = await limiter.limit(userId);
    if (result.success) {
      next();
      return;
    }
    const retryAfter = Math.max(1, Math.ceil((result.reset - Date.now()) / 1000));
    res.set("Retry-After", String(retryAfter));
    res.status(429).send("Too many requests");
  };
}
```

`X-RateLimit-Reset` in the route handler is Unix seconds, matching the Compute gateway. The JSON field `reset` stays in milliseconds. Which headers Unkey itself sends is on [Rate limiting](https://www.unkey.com/docs/api-management/ratelimiting/overview.md#what-a-limited-request-looks-like). `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:

```typescript theme={"system"}
await limiter.limit(identifier, { cost: 5 });
await limiter.limit(identifier, { limit: { limit: 100, duration: "1h" } });
```

Once an identifier is blocked, the library answers further calls for it from memory until `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:

```typescript theme={"system"}
const fallback = (identifier: string) => ({
  success: true, // let the request through when Unkey is unreachable
  limit: 0,
  remaining: 0,
  reset: 0,
});

const limiter = new Ratelimit({
  rootKey: process.env.UNKEY_ROOT_KEY ?? "",
  namespace: "email.send",
  limit: 10,
  duration: "30s",
  timeout: { ms: 3000, fallback },
  onError: (err, identifier) => {
    console.error(`ratelimit failed for ${identifier}: ${err.message}`);
    return fallback(identifier);
  },
});
```

Allowing keeps your service up during an outage. Denying protects an expensive downstream service.

## Scope

`Ratelimit` wraps [ratelimit.limit](https://www.unkey.com/docs/api-management/api-reference/ratelimit/apply-rate-limiting.md). The package also has:

* **`Overrides`**, which takes the same `rootKey` and `baseUrl` and has `getOverride`, `setOverride`, `deleteOverride`, and `listOverrides`. See [ratelimit.setOverride](https://www.unkey.com/docs/api-management/api-reference/ratelimit/set-ratelimit-override.md).
* **`NoopRatelimit`**, which works the same way without any network calls. Use it in tests.

For [ratelimit.multiLimit](https://www.unkey.com/docs/api-management/api-reference/ratelimit/apply-multiple-rate-limit-checks.md) and analytics, use [@unkey/api](https://www.unkey.com/docs/api-management/sdks/typescript/api.md). For rate limits on keys, see [Key and identity limits](https://www.unkey.com/docs/api-management/ratelimiting/key-and-identity-limits.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.