@unkey/ratelimit
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

@unkey/ratelimit

@unkey/ratelimit is a library for fast global ratelimiting in serverless functions.

Installation

npm install @unkey/ratelimit

Quickstart

  1. Configure your ratelimiter:
import { Ratelimit } from "@unkey/ratelimit";

const unkey = new Ratelimit({
  rootKey: process.env.UNKEY_ROOT_KEY,
  namespace: "my-app",
  limit: 10,
  duration: "30s",
  async: true,
});
  1. Use it:
async function handler(request) {
  const identifier = request.getUserId(); // or IP or anything else you want

  const ratelimit = await unkey.limit(identifier);
  if (!ratelimit.success) {
    return new Response("try again later", { status: 429 });
  }

  // handle the request here
}

Making it Bullet Proof

To ensure reliability, you can configure timeout and error handling:

import { Ratelimit } from "@unkey/ratelimit";

const fallback = (identifier: string) => ({
  success: true,
  limit: 0,
  reset: 0,
  remaining: 0,
});

const unkey = new Ratelimit({
  // ... standard configuration
  timeout: {
    ms: 3000, // only wait 3s at most before returning the fallback
    fallback,
  },
  onError: (err, identifier) => {
    console.error(`${identifier} - ${err.message}`);
    return fallback(identifier);
  },
});

API Overview

Create a new instance for ratelimiting by providing the necessary configuration.

new Ratelimit(config: RatelimitConfig)

Check whether a specific identifier is currently allowed to do something or if they have currently exceeded their limit.

.limit(identifier: string, opts: LimitOptions): Promise<RatelimitResponse>

Documentation

Read the full documentation

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
2.0.0285latest
2.0.0-canary.010next
0.0.21canary

Version History

VersionDownloads (Last 7 Days)Published
2.0.0285
2.0.0-canary.010
0.5.51,528
0.5.42
0.5.329
0.5.21
0.5.11
0.5.0194
0.4.7606
0.4.61
0.4.586
0.4.4220
0.4.33
0.4.21
0.4.11
0.4.04
0.3.2147
0.3.11
0.3.01
0.2.01
0.1.12125
0.1.111
0.1.101
0.1.91
0.1.81
0.1.71
0.1.61
0.1.51
0.1.41
0.1.314
0.1.21
0.1.11,941
0.1.01
0.0.31
0.0.21
0.0.11

Package Sidebar

Install

npm i @unkey/ratelimit

Weekly Downloads

5,215

Version

2.0.0

License

MIT

Unpacked Size

50 kB

Total Files

9

Last publish

Collaborators

  • chronark
  • domeccleston
  • perkinsjr