UsefulKey

Example — Bun

Using UsefulKey in a tiny Bun server.

A minimal Bun HTTP server that creates and verifies API keys using in-memory adapters. It implements the same endpoints as the Hono example.

Source: examples/bun

  • Repo path: examples/bun
  • Run locally:
    • Start: pnpm start (in examples/bun) or pnpm dev for hot reload
    • Server: http://localhost:8789
  • Endpoints:
    • GET /health
    • POST /keys — demo key creation
    • GET /verify — verify via x-api-key
    • POST /verify — verify via JSON { key }

Core server outline:

import { ConsoleAnalytics, MemoryKeyStore, MemoryRateLimitStore, usefulkey } from "betterkey";

const uk = usefulkey({
  keyPrefix: "uk",
  adapters: {
    keyStore: new MemoryKeyStore(),
    rateLimitStore: new MemoryRateLimitStore(),
    analytics: new ConsoleAnalytics(),
  },
});

const server = Bun.serve({
  port: 8789,
  async fetch(req) {
    // implement /health, /keys, /verify
    return new Response("Not Found", { status: 404 });
  },
});

console.log(`Bun minimal example listening on :${server.port}`);

Tips:

  • Restrict POST /keys to trusted callers in production.
  • Use persistent adapters to share state across Bun workers or instances.

See examples/bun in the repo for a complete project.