@upstash/ratelimit 2.1.0 → 2.2.1-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/index.d.mts +31 -1
- package/dist/index.d.ts +31 -1
- package/dist/index.js +50 -27
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +50 -27
- package/dist/index.mjs.map +1 -1
- package/docs/algorithms.mdx +169 -0
- package/docs/costs.mdx +112 -0
- package/docs/features.mdx +262 -0
- package/docs/gettingstarted.mdx +220 -0
- package/docs/methods.mdx +206 -0
- package/docs/overview.mdx +159 -0
- package/docs/traffic-protection.mdx +110 -0
- package/package.json +1 -1
- package/src/analytics.ts +110 -0
- package/src/cache.ts +55 -0
- package/src/constants.ts +14 -0
- package/src/deny-list/deny-list.ts +124 -0
- package/src/deny-list/index.ts +1 -0
- package/src/deny-list/ip-deny-list.ts +131 -0
- package/src/deny-list/scripts.ts +26 -0
- package/src/deny-list/time.ts +20 -0
- package/src/duration.ts +37 -0
- package/src/hash.ts +29 -0
- package/src/index.ts +18 -0
- package/src/lua-scripts/hash.ts +95 -0
- package/src/lua-scripts/multi.ts +86 -0
- package/src/lua-scripts/reset.ts +23 -0
- package/src/lua-scripts/single.ts +237 -0
- package/src/multi.ts +610 -0
- package/src/ratelimit.ts +506 -0
- package/src/single.ts +676 -0
- package/src/telemetry.ts +43 -0
- package/src/types.ts +132 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Ratelimit TypeScript SDK Getting Started
|
|
3
|
+
sidebarTitle: Getting Started
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
## Create your Redis instance
|
|
7
|
+
|
|
8
|
+
For the rate limit to work, we need to create an Upstash Redis and get its credentials. To create an Upstash Redis, you can follow the [Upstash Redis "Get Started" guide](/redis/overall/getstarted).
|
|
9
|
+
|
|
10
|
+
## Add Ratelimit to Your Project
|
|
11
|
+
|
|
12
|
+
Once we have a Redis instance, next step is adding the rate limit to your project in its most basic form.
|
|
13
|
+
|
|
14
|
+
### Install Ratelimit
|
|
15
|
+
|
|
16
|
+
First, we need to install `@upstash/ratelimit`:
|
|
17
|
+
|
|
18
|
+
<Tabs>
|
|
19
|
+
<Tab title="npm">
|
|
20
|
+
```bash
|
|
21
|
+
npm install @upstash/ratelimit
|
|
22
|
+
```
|
|
23
|
+
</Tab>
|
|
24
|
+
<Tab title="deno">
|
|
25
|
+
```ts
|
|
26
|
+
import { Ratelimit } from "https://cdn.skypack.dev/@upstash/ratelimit@latest";
|
|
27
|
+
```
|
|
28
|
+
</Tab>
|
|
29
|
+
</Tabs>
|
|
30
|
+
|
|
31
|
+
### Add Ratelimit to Your Endpoint
|
|
32
|
+
|
|
33
|
+
Next step is to add Ratelimit to your endpoint. In the example below, you can see how to initialize a Ratelimit and use it:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above
|
|
37
|
+
import { Redis } from "@upstash/redis";
|
|
38
|
+
|
|
39
|
+
// Create a new ratelimiter, that allows 10 requests per 10 seconds
|
|
40
|
+
const ratelimit = new Ratelimit({
|
|
41
|
+
redis: Redis.fromEnv(),
|
|
42
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
43
|
+
analytics: true,
|
|
44
|
+
/**
|
|
45
|
+
* Optional prefix for the keys used in redis. This is useful if you want to share a redis
|
|
46
|
+
* instance with other applications and want to avoid key collisions. The default prefix is
|
|
47
|
+
* "@upstash/ratelimit"
|
|
48
|
+
*/
|
|
49
|
+
prefix: "@upstash/ratelimit",
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// Use a constant string to limit all requests with a single ratelimit
|
|
53
|
+
// Or use a userID, apiKey or ip address for individual limits.
|
|
54
|
+
const identifier = "api";
|
|
55
|
+
const { success } = await ratelimit.limit(identifier);
|
|
56
|
+
|
|
57
|
+
if (!success) {
|
|
58
|
+
return "Unable to process at this time";
|
|
59
|
+
}
|
|
60
|
+
doExpensiveCalculation();
|
|
61
|
+
return "Here you go!";
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
For Cloudflare Workers and Fastly Compute@Edge, you can use the following imports:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { Redis } from "@upstash/redis/cloudflare"; // for cloudflare workers and pages
|
|
68
|
+
import { Redis } from "@upstash/redis/fastly"; // for fastly compute@edge
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
In this example, we initialize a Ratelimit with an Upstash Redis. The Uptash Redis instance is created from the environment variables and passed to the Ratelimit instance. Then, we check the access rate using the `ratelimit.limit(identifier)` method. If the `success` field is true, we allow the expensive calculation to go through.
|
|
72
|
+
|
|
73
|
+
For more examples, see the [Examples](/redis/sdks/ratelimit-ts/overview#examples).
|
|
74
|
+
|
|
75
|
+
### Set Environment Variables
|
|
76
|
+
|
|
77
|
+
Final step is to update the environment variables so that the Ratelimit can communicate with the Upstash Redis. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables must be set in order for the `Redis.fromEnv()` command to work. You can get the values of these environment variables from the [Upstash Console](https://console.upstash.com/redis) by navigating to the page of the Redis instance you created.
|
|
78
|
+
|
|
79
|
+
An alternative of using the `Redis.fromEnv()` method is to pass the variables yourself. This can be useful if you save these environment variables with a different name:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
new Redis({
|
|
83
|
+
url: "https://****.upstash.io",
|
|
84
|
+
token: "********",
|
|
85
|
+
});
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Here is how you can set the environment variables in different cases:
|
|
89
|
+
|
|
90
|
+
<Tabs>
|
|
91
|
+
<Tab title="Vercel">
|
|
92
|
+
Go to the "Settings" tab in your project. In the menu to the left, click "Environment Variables". Add `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables and their values.
|
|
93
|
+
</Tab>
|
|
94
|
+
<Tab title="Cloudflare Worker (Wrangler)">
|
|
95
|
+
Run:
|
|
96
|
+
```
|
|
97
|
+
npx wrangler secret put UPSTASH_REDIS_REST_URL
|
|
98
|
+
```
|
|
99
|
+
When prompted, enter the value of `UPSTASH_REDIS_REST_URL` when prompted. Do the same for `UPSTASH_REDIS_REST_TOKEN`:
|
|
100
|
+
```
|
|
101
|
+
npx wrangler secret put UPSTASH_REDIS_REST_TOKEN
|
|
102
|
+
```
|
|
103
|
+
</Tab>
|
|
104
|
+
<Tab title="Local Nextjs Project">
|
|
105
|
+
Go to the `.env.local` file and add the environment variables:
|
|
106
|
+
```
|
|
107
|
+
UPSTASH_REDIS_REST_URL=****
|
|
108
|
+
UPSTASH_REDIS_REST_TOKEN=****
|
|
109
|
+
```
|
|
110
|
+
</Tab>
|
|
111
|
+
</Tabs>
|
|
112
|
+
|
|
113
|
+
## Serverless Environments
|
|
114
|
+
|
|
115
|
+
When we use ratelimit in a serverless environment like CloudFlare Workers or Vercel Edge,
|
|
116
|
+
we need to be careful about making sure that the rate limiting operations complete correctly
|
|
117
|
+
before the runtime ends after returning the response.
|
|
118
|
+
|
|
119
|
+
This is important in two cases where we do some operations in the background asynchronously after `limit` is called:
|
|
120
|
+
|
|
121
|
+
1. Using MultiRegion: synchronize Redis instances in different regions
|
|
122
|
+
2. Enabling analytics: send analytics to Redis
|
|
123
|
+
|
|
124
|
+
In these cases, we need to wait for these operations to finish before sending the response to the user. Otherwise, the runtime will end and we won't be able to complete our chores.
|
|
125
|
+
|
|
126
|
+
In order to wait for these operations to finish, use the `pending` promise:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
const { pending } = await ratelimit.limit("id");
|
|
130
|
+
context.waitUntil(pending);
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
See more information on `context.waitUntil` at
|
|
134
|
+
[Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil)
|
|
135
|
+
and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil).
|
|
136
|
+
You can also utilize [`waitUntil` from Vercel Functions API](https://vercel.com/docs/functions/functions-api-reference#waituntil).
|
|
137
|
+
|
|
138
|
+
## Customizing the Ratelimit Algorithm
|
|
139
|
+
|
|
140
|
+
There are several algorithms we can use for rate limiting. Explore the different rate-limiting algorithms available; how they work, their advantages and disadvantages in the [Algorithms page](/redis/sdks/ratelimit-ts/algorithms). You can learn about the **cost in terms of the number of commands**, by referring to the [Costs page](/redis/sdks/ratelimit-ts/costs).
|
|
141
|
+
|
|
142
|
+
## Methods
|
|
143
|
+
|
|
144
|
+
In our example, we only used the `limit` method. There are other methods we can use in the Ratelimit. These are:
|
|
145
|
+
|
|
146
|
+
- `blockUntilReady`: Process a request only when the rate-limiting algorithm allows it.
|
|
147
|
+
- `resetUsedTokens`: Reset the rate limiter state for some identifier.
|
|
148
|
+
- `getRemaining`: Get the remaining tokens/requests left for some identifier.
|
|
149
|
+
|
|
150
|
+
To learn more about these methods, refer to the [Methods page](/redis/sdks/ratelimit-ts/methods).
|
|
151
|
+
|
|
152
|
+
## Features
|
|
153
|
+
|
|
154
|
+
To configure the your Ratelimit according to your needs, you can make use of several features:
|
|
155
|
+
|
|
156
|
+
<CardGroup cols={2}>
|
|
157
|
+
<Card
|
|
158
|
+
title="Caching"
|
|
159
|
+
icon="shield-halved"
|
|
160
|
+
href="/redis/sdks/ratelimit-ts/features#caching"
|
|
161
|
+
>
|
|
162
|
+
Handle blocked requests without having to call your Redis Database
|
|
163
|
+
</Card>
|
|
164
|
+
<Card
|
|
165
|
+
title="Timeout"
|
|
166
|
+
icon="stopwatch"
|
|
167
|
+
href="/redis/sdks/ratelimit-ts/features#timeout"
|
|
168
|
+
>
|
|
169
|
+
If the Redis call of the ratelimit is not resolved in some timeframe, allow
|
|
170
|
+
the request by default
|
|
171
|
+
</Card>
|
|
172
|
+
<Card
|
|
173
|
+
title="Analytics & Dashboard"
|
|
174
|
+
icon="magnifying-glass-chart"
|
|
175
|
+
href="/redis/sdks/ratelimit-ts/features#analytics-&-dashboard"
|
|
176
|
+
>
|
|
177
|
+
Collect information on which identifiers made how many requests and how many
|
|
178
|
+
were blocked
|
|
179
|
+
</Card>
|
|
180
|
+
<Card
|
|
181
|
+
title="Traffic Protection"
|
|
182
|
+
icon="lock"
|
|
183
|
+
href="/redis/sdks/ratelimit-ts/traffic-protection"
|
|
184
|
+
>
|
|
185
|
+
Create a deny list to block requests based on user agents, countries, IP
|
|
186
|
+
addresses an more
|
|
187
|
+
</Card>
|
|
188
|
+
<Card
|
|
189
|
+
title="Custom Rates"
|
|
190
|
+
icon="chart-simple"
|
|
191
|
+
href="/redis/sdks/ratelimit-ts/features#custom-rates"
|
|
192
|
+
>
|
|
193
|
+
Consume different amounts of tokens in different requests (example: limiting
|
|
194
|
+
based on request/response size)
|
|
195
|
+
</Card>
|
|
196
|
+
<Card
|
|
197
|
+
title="Multi Region"
|
|
198
|
+
icon="globe"
|
|
199
|
+
href="/redis/sdks/ratelimit-ts/features#multi-region"
|
|
200
|
+
>
|
|
201
|
+
Utilize several Redis databases in different regions to serve users faster
|
|
202
|
+
</Card>
|
|
203
|
+
<Card
|
|
204
|
+
title="Multiple Limits"
|
|
205
|
+
icon="gears"
|
|
206
|
+
href="/redis/sdks/ratelimit-ts/features#using-multiple-limits"
|
|
207
|
+
>
|
|
208
|
+
Use different limits for different kinds of requests (example: paid and free
|
|
209
|
+
users)
|
|
210
|
+
</Card>
|
|
211
|
+
<Card
|
|
212
|
+
title="Dynamic Limits"
|
|
213
|
+
icon="sliders"
|
|
214
|
+
href="/redis/sdks/ratelimit-ts/features#dynamic-limits"
|
|
215
|
+
>
|
|
216
|
+
Change rate limits at runtime without recreating the rate limiter instance
|
|
217
|
+
</Card>
|
|
218
|
+
</CardGroup>
|
|
219
|
+
|
|
220
|
+
For more information about the features, see the [Features page](/redis/sdks/ratelimit-ts/features).
|
package/docs/methods.mdx
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Methods
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
This page contains information on what methods are available in Ratelimit and how they can be used. For information on the
|
|
6
|
+
cost of these operations in term of number of Redis commands, refer to the [Costs page](/redis/sdks/ratelimit-ts/costs).
|
|
7
|
+
|
|
8
|
+
## `limit`
|
|
9
|
+
|
|
10
|
+
The `limit` method is the heart of the Ratelimit algorithm.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
ratelimit.limit(
|
|
14
|
+
identifier: string,
|
|
15
|
+
req?: {
|
|
16
|
+
geo?: Geo;
|
|
17
|
+
rate?: number,
|
|
18
|
+
ip?: string,
|
|
19
|
+
userAgent?: string,
|
|
20
|
+
country?: string
|
|
21
|
+
},
|
|
22
|
+
): Promise<RatelimitResponse>
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
It receives an identifier to rate limit. Additionally, it can be passed a `req` parameter which can contain either a
|
|
26
|
+
`geo` or a `rate` field. `geo` field is passed to the analytics but is not in use currently. The `rate` field determines
|
|
27
|
+
the amount of tokens/requests to subtract from the state of the algorithm with regards to the provided identifier.
|
|
28
|
+
|
|
29
|
+
The `limit` method returns some more metadata that might be useful to you:
|
|
30
|
+
|
|
31
|
+
````ts
|
|
32
|
+
export type RatelimitResponse = {
|
|
33
|
+
/**
|
|
34
|
+
* Whether the request may pass(true) or exceeded the limit(false)
|
|
35
|
+
*/
|
|
36
|
+
success: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Maximum number of requests allowed within a window.
|
|
39
|
+
*/
|
|
40
|
+
limit: number;
|
|
41
|
+
/**
|
|
42
|
+
* How many requests the user has left within the current window.
|
|
43
|
+
*/
|
|
44
|
+
remaining: number;
|
|
45
|
+
/**
|
|
46
|
+
* Unix timestamp in milliseconds when the limits are reset.
|
|
47
|
+
*/
|
|
48
|
+
reset: number;
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* For the MultiRegion setup we do some synchronizing in the background, after returning the current limit.
|
|
52
|
+
* Or when analytics is enabled, we send the analytics asynchronously after returning the limit.
|
|
53
|
+
* In most case you can simply ignore this.
|
|
54
|
+
*
|
|
55
|
+
* On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this:
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* const { pending } = await ratelimit.limit("id")
|
|
59
|
+
* context.waitUntil(pending)
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* See `waitUntil` documentation in
|
|
63
|
+
* [Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#contextwaituntil)
|
|
64
|
+
* and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil)
|
|
65
|
+
* for more details.
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
pending: Promise<unknown>;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Reason behind the result in `success` field.
|
|
72
|
+
* - Is set to "timeout" when request times out
|
|
73
|
+
* - Is set to "cacheBlock" when an identifier is blocked through cache without calling redis because it was
|
|
74
|
+
* rate limited previously.
|
|
75
|
+
* - Is set to "denyList" when identifier or one of ip/user-agent/country parameters is in deny list. To enable
|
|
76
|
+
* deny list, see `enableProtection` parameter. To edit the deny list, see the Upstash Ratelimit Dashboard
|
|
77
|
+
* at https://console.upstash.com/ratelimit.
|
|
78
|
+
* - Is set to undefined if rate limit check had to use Redis. This happens in cases when `success` field in
|
|
79
|
+
* the response is true. It can also happen the first time sucecss is false.
|
|
80
|
+
*/
|
|
81
|
+
reason?: RatelimitResponseType;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The value which was in the deny list if reason: "denyList"
|
|
85
|
+
*/
|
|
86
|
+
deniedValue?: string;
|
|
87
|
+
};
|
|
88
|
+
````
|
|
89
|
+
|
|
90
|
+
## `blockUntilReady`
|
|
91
|
+
|
|
92
|
+
In case you don't want to reject a request immediately but wait until it can be
|
|
93
|
+
processed, we also provide
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
ratelimit.blockUntilReady(
|
|
97
|
+
identifier: string,
|
|
98
|
+
timeout: number
|
|
99
|
+
): Promise<RatelimitResponse>
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
It is very similar to the `limit` method and takes an identifier and returns the
|
|
103
|
+
same response. However if the current limit has already been exceeded, it will
|
|
104
|
+
automatically wait until the next window starts and will try again. Setting the
|
|
105
|
+
timeout parameter (in milliseconds) will cause the returned Promise to resolve
|
|
106
|
+
in a finite amount of time.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
// Create a new ratelimiter, that allows 10 requests per 10 seconds
|
|
110
|
+
const ratelimit = new Ratelimit({
|
|
111
|
+
redis: Redis.fromEnv(),
|
|
112
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
113
|
+
analytics: true,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds
|
|
117
|
+
const { success } = await ratelimit.blockUntilReady("id", 30_000);
|
|
118
|
+
|
|
119
|
+
if (!success) {
|
|
120
|
+
return "Unable to process, even after 30 seconds";
|
|
121
|
+
}
|
|
122
|
+
doExpensiveCalculation();
|
|
123
|
+
return "Here you go!";
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
<Warning>
|
|
127
|
+
In **Cloudflare**, `blockUntilReady` will not work as intended due to
|
|
128
|
+
`Date.now()` not behaving the same as in Node environments.
|
|
129
|
+
<br />
|
|
130
|
+
<br />
|
|
131
|
+
**For more information, check**: <br />
|
|
132
|
+
https://developers.cloudflare.com/workers/runtime-apis/web-standards
|
|
133
|
+
</Warning>
|
|
134
|
+
|
|
135
|
+
## `resetUsedTokens`
|
|
136
|
+
|
|
137
|
+
This method resets the state of the algorithm with respect to some identifier:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
ratelimit.resetUsedTokens(identifier: string): Promise<void>
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## `getRemaining`
|
|
144
|
+
|
|
145
|
+
This method returns the remaining tokens/requests available for some identifier:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
ratelimit.getRemaining(identifier: string): Promise<{
|
|
149
|
+
remaining: number;
|
|
150
|
+
reset: number;
|
|
151
|
+
}>
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
`remaining` is the remaining tokens. `reset` is the reset timestamp.
|
|
155
|
+
|
|
156
|
+
## `setDynamicLimit`
|
|
157
|
+
|
|
158
|
+
This method sets or removes a [global dynamic rate limit](/redis/sdks/ratelimit-ts/features#dynamic-limits). Dynamic limits override the default limiter settings for all subsequent rate limit checks.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
ratelimit.setDynamicLimit(options: {
|
|
162
|
+
limit: number | false;
|
|
163
|
+
}): Promise<void>
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
**Parameters:**
|
|
167
|
+
- `limit`: The new limit value (number), or `false` to remove the dynamic limit and fall back to the default
|
|
168
|
+
|
|
169
|
+
**Example:**
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const ratelimit = new Ratelimit({
|
|
173
|
+
redis: Redis.fromEnv(),
|
|
174
|
+
limiter: Ratelimit.slidingWindow(10, "10s"),
|
|
175
|
+
dynamicLimits: true,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// Set a new dynamic limit
|
|
179
|
+
await ratelimit.setDynamicLimit({ limit: 5 });
|
|
180
|
+
|
|
181
|
+
// Remove dynamic limit (falls back to default of 10)
|
|
182
|
+
await ratelimit.setDynamicLimit({ limit: false });
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## `getDynamicLimit`
|
|
186
|
+
|
|
187
|
+
This method retrieves the current [dynamic limit](/redis/sdks/ratelimit-ts/features#dynamic-limits) if one is set.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
ratelimit.getDynamicLimit(): Promise<{ dynamicLimit: number | null }>
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
**Returns:** The current dynamic limit value, or `null` if no dynamic limit is set
|
|
194
|
+
|
|
195
|
+
**Example:**
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const ratelimit = new Ratelimit({
|
|
199
|
+
redis: Redis.fromEnv(),
|
|
200
|
+
limiter: Ratelimit.slidingWindow(10, "10s"),
|
|
201
|
+
dynamicLimits: true,
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
await ratelimit.setDynamicLimit({ limit: 5 });
|
|
205
|
+
const { dynamicLimit } = await ratelimit.getDynamicLimit(); // returns 5
|
|
206
|
+
```
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Ratelimit TypeScript SDK Overview
|
|
3
|
+
sidebarTitle: Overview
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Upstash Rate Limit
|
|
7
|
+
|
|
8
|
+
[](https://www.npmjs.com/package/@upstash/ratelimit)
|
|
9
|
+
|
|
10
|
+
It is the only connectionless (HTTP based) rate limiting library and designed
|
|
11
|
+
for:
|
|
12
|
+
|
|
13
|
+
- Serverless functions (AWS Lambda, Vercel ...)
|
|
14
|
+
- Cloudflare Workers
|
|
15
|
+
- Vercel Edge
|
|
16
|
+
- Fastly Compute@Edge
|
|
17
|
+
- Next.js, Jamstack ...
|
|
18
|
+
- Client side web/mobile applications
|
|
19
|
+
- WebAssembly
|
|
20
|
+
- and other environments where HTTP is preferred over TCP.
|
|
21
|
+
|
|
22
|
+
## Quick Links:
|
|
23
|
+
|
|
24
|
+
- [Github Repository](https://github.com/upstash/ratelimit)
|
|
25
|
+
- [Getting Started](/redis/sdks/ratelimit-ts/gettingstarted)
|
|
26
|
+
- [Costs](/redis/sdks/ratelimit-ts/costs)
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
<CardGroup cols={2}>
|
|
31
|
+
<Card
|
|
32
|
+
title="Caching"
|
|
33
|
+
icon="shield-halved"
|
|
34
|
+
href="/redis/sdks/ratelimit-ts/features#caching"
|
|
35
|
+
>
|
|
36
|
+
Handle blocked requests without having to call your Redis Database
|
|
37
|
+
</Card>
|
|
38
|
+
<Card
|
|
39
|
+
title="Timeout"
|
|
40
|
+
icon="stopwatch"
|
|
41
|
+
href="/redis/sdks/ratelimit-ts/features#timeout"
|
|
42
|
+
>
|
|
43
|
+
If the Redis call of the ratelimit is not resolved in some timeframe, allow
|
|
44
|
+
the request by default
|
|
45
|
+
</Card>
|
|
46
|
+
<Card
|
|
47
|
+
title="Analytics & Dashboard"
|
|
48
|
+
icon="magnifying-glass-chart"
|
|
49
|
+
href="/redis/sdks/ratelimit-ts/features#analytics-&-dashboard"
|
|
50
|
+
>
|
|
51
|
+
Collect information on which identifiers made how many requests and how many
|
|
52
|
+
were blocked
|
|
53
|
+
</Card>
|
|
54
|
+
<Card
|
|
55
|
+
title="Traffic Protection"
|
|
56
|
+
icon="lock"
|
|
57
|
+
href="/redis/sdks/ratelimit-ts/traffic-protection"
|
|
58
|
+
>
|
|
59
|
+
Create a deny list to block requests based on user agents, countries, IP
|
|
60
|
+
addresses and more
|
|
61
|
+
</Card>
|
|
62
|
+
<Card
|
|
63
|
+
title="Custom Rates"
|
|
64
|
+
icon="chart-simple"
|
|
65
|
+
href="/redis/sdks/ratelimit-ts/features#custom-rates"
|
|
66
|
+
>
|
|
67
|
+
Consume different amounts of tokens in different requests (example: limiting
|
|
68
|
+
based on request/response size)
|
|
69
|
+
</Card>
|
|
70
|
+
<Card
|
|
71
|
+
title="Multi Region"
|
|
72
|
+
icon="globe"
|
|
73
|
+
href="/redis/sdks/ratelimit-ts/features#multi-region"
|
|
74
|
+
>
|
|
75
|
+
Utilize several Redis databases in different regions to serve users faster
|
|
76
|
+
</Card>
|
|
77
|
+
<Card
|
|
78
|
+
title="Multiple Limits"
|
|
79
|
+
icon="gears"
|
|
80
|
+
href="/redis/sdks/ratelimit-ts/features#using-multiple-limits"
|
|
81
|
+
>
|
|
82
|
+
Use different limits for different kinds of requests (example: paid and free
|
|
83
|
+
users)
|
|
84
|
+
</Card>
|
|
85
|
+
<Card
|
|
86
|
+
title="Dynamic Limits"
|
|
87
|
+
icon="sliders"
|
|
88
|
+
href="/redis/sdks/ratelimit-ts/features#dynamic-limits"
|
|
89
|
+
>
|
|
90
|
+
Change rate limits at runtime without recreating the rate limiter instance
|
|
91
|
+
</Card>
|
|
92
|
+
</CardGroup>
|
|
93
|
+
|
|
94
|
+
For more information about the features, see the [Features tab](/redis/sdks/ratelimit-ts/features).
|
|
95
|
+
|
|
96
|
+
## Examples
|
|
97
|
+
|
|
98
|
+
<CardGroup cols={2}>
|
|
99
|
+
<Card
|
|
100
|
+
title="Nextjs"
|
|
101
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/nextjs"
|
|
102
|
+
>
|
|
103
|
+
Rate limit an API in a Nextjs project
|
|
104
|
+
</Card>
|
|
105
|
+
<Card
|
|
106
|
+
title="Nextjs with Middleware"
|
|
107
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/nextjs-middleware"
|
|
108
|
+
>
|
|
109
|
+
Rate limit an API with a Middleware in a Nextjs project
|
|
110
|
+
</Card>
|
|
111
|
+
<Card
|
|
112
|
+
title="Vercel Edge"
|
|
113
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/vercel-edge"
|
|
114
|
+
>
|
|
115
|
+
Rate limit an Vercel Edge Function
|
|
116
|
+
</Card>
|
|
117
|
+
<Card
|
|
118
|
+
title="Enabling Protection"
|
|
119
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/enable-protection"
|
|
120
|
+
>
|
|
121
|
+
Use Deny Lists to Protect Your Website
|
|
122
|
+
</Card>
|
|
123
|
+
<Card
|
|
124
|
+
title="Cloudflare Pages"
|
|
125
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/cloudflare-pages"
|
|
126
|
+
>
|
|
127
|
+
Rate limit access to your Cloudflare Pages app
|
|
128
|
+
</Card>
|
|
129
|
+
<Card
|
|
130
|
+
title="Cloudflare Workers"
|
|
131
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/cloudflare-workers"
|
|
132
|
+
>
|
|
133
|
+
Rate limit access to your Cloudflare Workers
|
|
134
|
+
</Card>
|
|
135
|
+
<Card
|
|
136
|
+
title="Remix"
|
|
137
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/remix"
|
|
138
|
+
>
|
|
139
|
+
Rate limit access to a Remix App
|
|
140
|
+
</Card>
|
|
141
|
+
<Card
|
|
142
|
+
title="Rate limit using Vercel KV"
|
|
143
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/with-vercel-kv"
|
|
144
|
+
>
|
|
145
|
+
Rate limit a Nexjs app using Vercel KV
|
|
146
|
+
</Card>
|
|
147
|
+
<Card
|
|
148
|
+
title="Deno App"
|
|
149
|
+
href="https://github.com/upstash/ratelimit/tree/main/examples/deno"
|
|
150
|
+
>
|
|
151
|
+
Rate limit your deno app
|
|
152
|
+
</Card>
|
|
153
|
+
<Card
|
|
154
|
+
title="Rate limit your Chatbot"
|
|
155
|
+
href="https://upstash.com/blog/degree-guru#rate-limiting"
|
|
156
|
+
>
|
|
157
|
+
Limiting requests to a Chatbot endpoint which streams LLM outputs
|
|
158
|
+
</Card>
|
|
159
|
+
</CardGroup>
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Traffic Protection
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
### Deny List
|
|
6
|
+
|
|
7
|
+
Imagine that you want to block requests from certain countries or from some
|
|
8
|
+
user agents. In this case, you can make use of deny lists introduced in
|
|
9
|
+
ratelimit version 1.2.1.
|
|
10
|
+
|
|
11
|
+
Deny lists allow you to block based on IP addresses, user agents, countries
|
|
12
|
+
and [identifiers](/redis/sdks/ratelimit-ts/methods#limit).
|
|
13
|
+
|
|
14
|
+
To enable checking the deny list in your Ratelimit client, simply pass
|
|
15
|
+
`enableProtection` as `true`:
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
const ratelimit = new Ratelimit({
|
|
19
|
+
redis: Redis.fromEnv(),
|
|
20
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
21
|
+
enableProtection: true,
|
|
22
|
+
analytics: true,
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
When `limit` is called, the client will check whether any of these values
|
|
27
|
+
are in the deny list and block the request if so.
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
const { success, pending, reason, deniedValue } = await ratelimit.limit("userId", {
|
|
31
|
+
ip: "ip-address",
|
|
32
|
+
userAgent: "user-agent",
|
|
33
|
+
country: "country",
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
await pending; // await pending if you have analytics enabled
|
|
37
|
+
|
|
38
|
+
console.log(success, reason, deniedValue);
|
|
39
|
+
// prints: false, "denyList", "ip-address"
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
If a request fails because a value was in deny list, `reason` field will
|
|
43
|
+
be `"denyList"`. `deniedValue` will contain the value in the deny list.
|
|
44
|
+
See [limit method](/redis/sdks/ratelimit-ts/methods#limit)
|
|
45
|
+
for more detailts.
|
|
46
|
+
|
|
47
|
+
Client also keeps a **cache** of denied values. When a value is found
|
|
48
|
+
in the deny list, the client stores this value in the cache. If this value
|
|
49
|
+
is encountered in the following requests, it is **denied without calling
|
|
50
|
+
Redis at all**. Items are stored in the cache for a minute. This means that if
|
|
51
|
+
you add a new value to the deny list, it will immediately take affect but when you
|
|
52
|
+
remove a value, it can take up to a minute for clients to start
|
|
53
|
+
accepting the value. This can significantly reduce the number of calls to Redis.
|
|
54
|
+
|
|
55
|
+
Contents of the deny lists are managed from the [Ratelimit Dashboard](/redis/sdks/ratelimit-ts/features#dashboard).
|
|
56
|
+
You can use the dashboard to add items to the deny list or remove them.
|
|
57
|
+
If you have analytics enabled, you can also view the number of denied
|
|
58
|
+
requests per country/ip address/user agent/identifier on the dashboard.
|
|
59
|
+
|
|
60
|
+

|
|
61
|
+
|
|
62
|
+
Note that we look for exact match when checking a value to see if it's in
|
|
63
|
+
the deny lists. **Pattern matching is not supported**.
|
|
64
|
+
|
|
65
|
+
### Auto IP Deny List
|
|
66
|
+
|
|
67
|
+
The Auto IP Deny List feature enables the automatic blocking of IP addresses
|
|
68
|
+
identified as malicious through open-source IP deny lists. This functionality
|
|
69
|
+
uses the [ipsum repository on GitHub](https://github.com/stamparm/ipsum),
|
|
70
|
+
which aggregates data from over 30 different deny lists.
|
|
71
|
+
|
|
72
|
+
To enable protection, set the enableProtection parameter to true. Once activated,
|
|
73
|
+
your SDK will automatically block IP addresses by leveraging the IP deny lists
|
|
74
|
+
when you provide the request IPs in the limit method.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
const ratelimit = new Ratelimit({
|
|
78
|
+
redis: Redis.fromEnv(),
|
|
79
|
+
limiter: Ratelimit.slidingWindow(10, "10 s"),
|
|
80
|
+
enableProtection: true,
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The IP deny list is updated daily at 2 AM UTC. Upon expiration, the
|
|
85
|
+
first call to limit after 2 AM UTC will trigger an update, downloading
|
|
86
|
+
the latest IPs from GitHub and refreshing the list in your Redis
|
|
87
|
+
instance. The update process occurs asynchronously, allowing you to
|
|
88
|
+
return the result to the user while the IP list updates in the
|
|
89
|
+
background. To ensure the update completes successfully, utilize the
|
|
90
|
+
pending field:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const { success, pending } = await ratelimit.limit(
|
|
94
|
+
content,
|
|
95
|
+
{ip: "ip-address"}
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
await pending;
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
For more information on effectively using pending, refer to the
|
|
102
|
+
["Asynchronous synchronization between databases" section](/redis/sdks/ratelimit-ts/features#asynchronous-synchronization-between-databases).
|
|
103
|
+
|
|
104
|
+
Blocked IPs will be listed in the "Denied" section of the Ratelimit
|
|
105
|
+
dashboard, providing a clear overview of the addresses that have
|
|
106
|
+
been automatically blocked.
|
|
107
|
+
|
|
108
|
+
If you prefer to disable the Auto IP Deny List feature while still
|
|
109
|
+
using the deny lists, you can do so via the [Ratelimit dashboard on
|
|
110
|
+
the Upstash Console](https://console.upstash.com/ratelimit).
|