import { Ratelimit } from "@unkey/ratelimit";
/**
This can be a seperate util for easy configurable ratelimiting across
multiple routes.
namespace = The route identifier you would like to ratelimit
limit = The amount of requests
duration = amount of time to limit against for example "30s"
**/
const limiter = new Ratelimit({
namespace: "bun-example",
limit: 2,
duration: "30s",
rootKey: process.env.UNKEY_ROOT_KEY
})
const server = Bun.serve({
async fetch(req) {
const identifier = req.getUserId() // or ip or anything else you want
const ratelimit = await limiter.limit(identifier)
if (!ratelimit.success){
return Response("try again later", { status: 429 })
}
return return new Response("Success", { status: 200 });
},
port: 8000,
});
console.log(`Listening on ${server.url}`);