Skip to content
25K
Console

RateLimit

The RateLimit component lets you add a Cloudflare Rate Limit binding to your app.

Minimal example

sst.config.ts
const rateLimit = new sst.cloudflare.RateLimit("MyRateLimit", {
namespaceId: 1001,
limit: 100,
period: "1 minute",
});

You can link RateLimit to a worker.

sst.config.ts
new sst.cloudflare.Worker("MyWorker", {
handler: "./index.ts",
url: true
link: [rateLimit],
});

Once linked, you can use the SDK to interact with the RateLimit binding.

index.ts
import { Resource } from "sst/resource";
export default {
async fetch(req, env): Promise<Response> {
const url = new URL(req.url);
const outcome = await Resource.MyRateLimit.limit({ key: url.pathname });
if (!outcome.success) {
return new Response(`Rate limit exceeded for ${url.pathname}`, { status: 429 });
}
return new Response("OK", { status: 200 });
}
}

Constructor

new RateLimit(name, args, opts?)

Parameters

RateLimitArgs

limit

Type Input<number>

The number of allowed requests within the specified period of time.

namespaceId

Type Input<number>

A positive integer that uniquely defines this rate limiting namespace within your Cloudflare account.

period

Type Input<10 seconds | 1 minute>

The duration of the rate limit window. Must be either 10 seconds or 1 minute.

Properties

limit

Type Output<number>

The number of allowed requests within the specified period of time.

namespaceId

Type Output<string>

A unique identifier for the rate limit namespace.

period

Type Output<number>

The duration of the rate limit window, in seconds.

SDK

Use the SDK in your runtime to interact with your infrastructure.


Bindings

When you link a RateLimit binding, it will be available to the worker and you can interact with it using its API methods.

index.ts
import { Resource } from "sst/resource";
export default {
async fetch(req, env): Promise<Response> {
const url = new URL(req.url);
const outcome = await Resource.MyRateLimit.limit({ key: url.pathname });
if (!outcome.success) {
return new Response(`Rate limit exceeded for ${url.pathname}`, { status: 429 });
}
return new Response("OK", { status: 200 });
}
}