Skip to Content
ZarexDocs

Bun

Protect a Bun.serve server with @zarex/bun.

Installation

bun add @zarex/bun
.env
ZAREX_KEY=zarex_test_...

Protect the server

server.ts
import { zarexBun, shield, rateLimit } from "@zarex/bun";

const wrap = zarexBun({
  key: process.env.ZAREX_KEY!,
  ipSource: "socket",
  rules: [shield(), rateLimit({ max: 100, window: "1m" })],
});

Bun.serve({
  fetch: wrap(async (request) => new Response("ok")),
});

zarexBun(...) returns a function that wraps your fetch handler. A denied request automatically receives 403, or 429 with retry-after.

The visitor's IP address

Bun provides the connection address: every ipSource value works.

ipSourceWhen to use it
"socket"Nothing in front of your Bun server: the connection address.
"cloudflare"Behind Cloudflare.
{ proxies: n }n trusted proxies in front of Bun.
{ trustedProxies: [...] }The exact CIDR ranges of your proxies.

On Vercel and Fly.io, ipSource can be omitted. Anywhere else, the application refuses to start without it.

Identifiers and form data

const wrap = zarexBun({
  key: process.env.ZAREX_KEY!,
  ipSource: "socket",
  rules: [rateLimit({ max: 100, window: "1m", characteristics: ["userId"] })],
  call: (request) => ({
    characteristics: { userId: request.headers.get("x-user-id") ?? undefined },
  }),
});

call can also provide email, phone, text and tokensRequested. Identifiers are hashed (SHA-256) before being sent.

Customize the denial

zarexBun({
  key: process.env.ZAREX_KEY!,
  ipSource: "socket",
  rules: [shield()],
  onDeny: (request, decision) =>
    Response.json({ error: "Request denied", id: decision.id }, { status: 403 }),
});

onDeny and onDegraded receive the full decision. To read it on every request, use createZarex and protect (see the reference).

Security headers and responses

secureHeaders: true and responseGuard: true apply automatically to every response from your handler.

On this page