Skip to content
GitHub Discord

Cloudflare Rate Limit

This example creates a Cloudflare Rate Limit and a Worker that applies it.

sst.config.ts
const rateLimit = new sst.cloudflare.RateLimit("MyRateLimit", {
namespaceId: 1001,
limit: 100,
period: "1 minute",
});
const worker = new sst.cloudflare.Worker("MyWorker", {
handler: "./index.ts",
url: true,
link: [rateLimit],
});
index.ts
import { Resource } from "sst/resource";
export default {
async fetch(req: Request) {
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 });
},
};

View the full example.