UsefulKey

Example — Astro

Using UsefulKey with Astro API routes.

This example adds minimal Astro API routes that create and verify API keys using in-memory adapters. It includes endpoints for health, key creation, and verification via header or JSON.

Source: examples/astro

  • Repo path: examples/astro
  • Run locally:
    • Install: pnpm i (in examples/astro)
    • Start: pnpm dev
    • App: http://localhost:4321
  • Endpoints:
    • GET /api/health
    • POST /api/keys — demo key creation
    • GET /api/verify — verify via x-api-key
    • POST /api/verify — verify via JSON { key }

Core routes outline:

// src/pages/api/keys.ts
import type { APIContext } from "astro";
import { ConsoleAnalytics, MemoryKeyStore, MemoryRateLimitStore, usefulkey } from "betterkey";

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

export async function POST(_ctx: APIContext) {
  const res = await uk.createKey();
  if (res.error)
    return new Response(JSON.stringify({ ok: false, reason: res.error.code ?? "error" }), {
      status: 500,
      headers: { "content-type": "application/json" },
    });
  return new Response(JSON.stringify(res.result), {
    headers: { "content-type": "application/json" },
  });
}

Tips:

  • Keep POST /api/keys private in production.
  • Swap the adapters for persistent stores to share state across processes.

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