First we need a bun project, so create a new directory and init bun.
Copy
Ask AI
mkdir unkey-with-buncd unkey-with-bunbun init -y
2
Install
Now install the @unkey/ratelimit package
Copy
Ask AI
bun install @unkey/ratelimit
3
Add Root Key to env
Add your root key to your .env file
Copy
Ask AI
UNKEY_ROOT_KEY="YOUR_KEY"
4
Modify the server
Open up the file called index.ts and add the following code
index.ts
Copy
Ask AI
import { Ratelimit } from "@unkey/ratelimit";/**This can be a seperate util for easy configurable ratelimiting acrossmultiple routes.namespace = The route identifier you would like to ratelimitlimit = The amount of requestsduration = 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}`);
5
Running the server
Copy
Ask AI
bun run index.ts
6
Try it out
Copy
Ask AI
curl http://localhost:8000
You will need to curl a few times to see the ratelimiting error. Once you do, you, you will need to wait to perform the action again.