> ## Documentation Index
> Fetch the complete documentation index at: https://express-quota-limiter.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# createQuotaLimiter() — Express quota middleware factory

> Full reference for createQuotaLimiter: options, behavior, error responses, and storage error handling for the Express quota limiter middleware.

`createQuotaLimiter` is the main entry point of `express-quota-limiter`. You call it once with your configuration and it returns a standard Express middleware function — `(req, res, next) => Promise<void>` — that you attach directly to any route or router.

## Function signature

```typescript theme={null}
createQuotaLimiter(options: QuotaOptions): (req, res, next) => Promise<void>
```

## Options

**storage** `QuotaStorage` *required*

The storage driver that persists quota state. Use `RedisDriver` in production and `MemoryDriver` for tests. You can also supply any object that implements the `QuotaStorage` interface.

**keyGenerator** `(req) =\> string` *required*

A function that receives the incoming request and returns the quota key for that request. Keys are typically scoped to a tenant, user, or route — for example `quota:emails:${req.tenantId}`. When this function returns an empty string the quota check is skipped entirely and the request passes through.

**limit** `number | (req) =\> number | Promise\<number\>` (default: 100)

The maximum number of allowed operations per quota window. You can pass a static number or an async function that resolves a per-request limit — useful for multi-tenant apps where different plans have different quotas.

```typescript theme={null}
// Static
limit: 500

// Dynamic — resolve from database
limit: async (req) => {
  const tenant = await db.query(
    "SELECT plan FROM tenants WHERE id = $1",
    [req.tenantId]
  );
  return tenant.plan === "pro" ? 5000 : 500;
}
```

**errorMessage** `string` (default: "Quota exceeded")

The human-readable message sent in the `message` field of the HTTP 429 JSON response body. Override this to provide context-specific messages such as `"Monthly email quota exceeded"`.

**failOpen** `boolean` (default: true)

Controls how the middleware behaves when the storage driver throws an error. When `true` (the default), the error is logged and the request passes through. When `false`, the middleware returns HTTP 500.

**onQuotaChecked** `(ctx: QuotaCheckedContext) =\> void`

An optional callback invoked after **every** quota check, whether the request was allowed or blocked. It runs fire-and-forget — any error it throws is caught and logged, and never affects the HTTP response. Use it to sync remaining quota to your database, push metrics to Datadog or Prometheus, or power usage dashboards.

**onQuotaExceeded** `(ctx: QuotaExceededContext) =\> void`

An optional callback invoked only when a request is **blocked** because the quota is exhausted. Like `onQuotaChecked`, it runs fire-and-forget. Use it to log violations, send billing alerts, or notify the tenant.

**quotaWeight** `(req) =\> number | Promise\<number\>`

An optional function that returns how much quota the current request should consume. Defaults to `1` when omitted. Use this for endpoints where some requests are more expensive than others — for example, charging by the number of emails in a bulk send.

```typescript theme={null}
quotaWeight: (req) => req.body.count || 1
```

## Behavior

On every request the middleware:

1. Calls `keyGenerator(req)` to determine the quota key. If the key is an empty string, it logs a warning and calls `next()` without checking quota.
2. Resolves the `limit` value — static or dynamic.
3. Resolves the `quotaWeight` value (defaults to `1`).
4. Calls `storage.decrement(key, limit, weight)` atomically.
5. Sets `Quota-Remaining` and `Quota-Limit` headers on the response **regardless of whether the request was allowed or blocked**.
6. Fires `onQuotaChecked` as a fire-and-forget callback if provided.
7. If the quota is exceeded, fires `onQuotaExceeded` as a fire-and-forget callback if provided, then returns the HTTP 429 JSON response below.
8. If the quota is not exceeded, calls `next()` to pass the request to the next handler.

## HTTP 429 response

When a request exceeds the quota, the middleware responds with status `429 Too Many Requests` and the following JSON body:

```json theme={null}
{
  "error": "Too Many Requests",
  "message": "Monthly email quota exceeded",
  "quota": { "limit": 500, "remaining": 0 }
}
```

The `message` field reflects the value of the `errorMessage` option. The `quota.remaining` field is always `0` in a 429 response.

## Storage error behavior

When `storage.decrement` throws, the middleware logs the error to `console.error` and then does one of the following based on `failOpen`:

| `failOpen` value | Behavior |
| - | - |
| `true` (default) | Logs the error and calls `next()` — the request passes through |
| `false` | Returns HTTP 500 with `{ "error": "Internal Server Error", "message": "Quota service unavailable" }` |

> [!TIP]
>
> Keep `failOpen: true` in production so that a Redis outage does not take down your API. Set `failOpen: false` in scenarios where you must enforce hard limits — for example, paid usage where over-consumption is not acceptable.

## Example

```typescript theme={null}
import express from "express";
import { createQuotaLimiter, RedisDriver } from "express-quota-limiter";
import { redis } from "./services/redis";

const app = express();

const emailQuota = createQuotaLimiter({
  storage: new RedisDriver(redis),
  limit: 500,
  keyGenerator: (req) => `quota:emails:${req.tenantId}`,
  errorMessage: "Monthly email quota exceeded",
  onQuotaChecked: async ({ remaining, req }) => {
    await db.query(
      "UPDATE tenants SET quota_remaining = $1 WHERE id = $2",
      [remaining, req.tenantId]
    );
  },
  onQuotaExceeded: async ({ req }) => {
    await slack.send(`Tenant ${req.tenantId} exhausted their email quota`);
  },
});

app.post("/send-email", emailQuota, (req, res) => {
  res.json({ ok: true });
});
```


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