Example — Next.js
Using UsefulKey in a Next.js App Router project.
This example shows a minimal Next.js (App Router) project that creates API keys and verifies them using in-memory adapters. It includes endpoints for health, key creation, and verification via header or JSON.
Source: examples/nextjs
- Repo path:
examples/nextjs
- Run locally:
- Install:
pnpm i
(inexamples/nextjs
) - Start:
pnpm dev
- App:
http://localhost:3000
- Install:
- Endpoints:
GET /api/health
POST /api/keys
— demo key creationGET /api/verify
— verify viax-api-key
POST /api/verify
— verify via JSON{ key }
Core setup: create an instance and wire API routes.
// lib/usefulkey.ts
import { usefulkey, MemoryKeyStore, MemoryRateLimitStore, ConsoleAnalytics } from "betterkey";
export const uk = usefulkey({
keyPrefix: "uk",
adapters: {
keyStore: new MemoryKeyStore(),
rateLimitStore: new MemoryRateLimitStore(),
analytics: new ConsoleAnalytics(),
},
});
// app/api/verify/route.ts
import { NextRequest, NextResponse } from "next/server";
import { uk } from "@/lib/usefulkey";
export async function POST(req: NextRequest) {
const { key } = await req.json();
const ip = req.ip ?? "0.0.0.0";
const res = await uk.verifyKey({ key, ip });
return NextResponse.json(res.result ?? { error: res.error }, { status: 200 });
}
Tips:
- Protect
POST /api/keys
behind admin auth or remove it in production. - Swap in persistent adapters (e.g., Postgres, Redis) to share state across instances.
- If you need global rate limits, add the rate-limit plugin to
usefulkey
.
See examples/nextjs
in the repo for a complete project.