Add API keys and usage limits to an Express API
Short version: an API-key check is ten lines; a correct one is not. Store only hashes, match by route and method, treat HEAD like GET and never charge OPTIONS, count usage atomically, make revocation immediate, and fail closed on paid routes only. Below is a minimal version and the checklist it doesn’t cover.
A minimal API-key middleware
This is what most tutorials (and most AI assistants) produce. It works for a demo on one server:
import crypto from "node:crypto";
// Store only SHA-256 hashes of keys, never the keys themselves.
const keys = new Map([
// hash -> { plan, remaining, revoked? }
[sha256("demo-key-123"), { plan: "reports", remaining: 1000, revoked: false }],
]);
function sha256(s) { return crypto.createHash("sha256").update(s).digest("hex"); }
function requireKey(plan) {
return (req, res, next) => {
const m = /^Bearer\s+(\S+)$/.exec(req.headers.authorization ?? "");
if (!m) return res.status(402).json({ error: "payment_required" });
const entry = keys.get(sha256(m[1]));
if (!entry || entry.revoked) return res.status(403).json({ error: "forbidden" });
if (entry.plan !== plan || entry.remaining <= 0)
return res.status(402).json({ error: "payment_required" });
entry.remaining -= 1;
next();
};
}
app.get("/api/reports", requireKey("reports"), listReports);
Looking up by hash means a leaked database doesn’t leak working keys. Returning 402 when there's no key and 403 for a wrong one tells honest clients what to do. So far so good.
What the minimal version gets wrong
1. Methods, not just paths
app.get() also answers HEAD requests in Express, so the route is protected for both. But if you mount the check with app.use("/api/reports", …) instead, it also runs on POST, DELETE and the OPTIONS preflight that browsers send automatically. Rules should name the methods they charge: typically GET and HEAD share a quota, and OPTIONS is never charged. A POST under the same prefix that has its own user authentication should be left alone.
2. Atomic counting
entry.remaining -= 1 is fine in one process. With two instances, or with the counter in a database read-then-write, concurrent requests can both see “1 left” and both be served. The decrement must be a single atomic operation (a conditional UPDATE … WHERE remaining > 0, or an atomic script in Redis/Valkey), and the response should be served only if it succeeded.
3. Immediate revocation
If keys are cached per instance, revoking one may take minutes to reach every server. Revocation should be checked at decision time, not on cache refresh.
4. Failing closed, only where it matters
When the store that holds keys is unreachable, the tempting code path is catch { next() }. That serves every paid route for free during an outage. Paid routes must answer 503; public routes, health checks and login must keep working. This also applies at startup: if your app boots while the key service is down, it must still know which routes are paid.
5. Tokens out of logs and downstream
Once the key is checked, remove it from the request before your handlers and loggers see it, and never log the Authorization header.
6. A machine-readable “pay first”
A bare 402 tells a client it must pay, not what to buy. Include the plan, price and a checkout link so programs and AI agents can act on it. See HTTP 402 for AI agents.
Checklist
| Case | Expected |
|---|---|
| No key on a paid route | 402 with plan info |
| Valid key | 200, one unit used |
| Key for another plan | 402 |
| Invented key | 403 |
| Quota used up (GET and HEAD share it) | 402 |
| Revoked key | 403 on the next request |
OPTIONS preflight | 200, never charged |
| Key service down (also at startup) | 503 on paid routes, public routes unaffected |
| Public route, health check, login | 200, never charged |
Doing it with LicenRoute
LicenRoute is an open-source CLI and Express 4/5 middleware that covers that checklist. The CLI reads your app without running it, proposes plans per route prefix and method, and writes only the diff you approved, by typing a one-time challenge in your terminal, which an AI assistant can’t do for you. This is the block it adds to your app:
import { licenroute } from "@licenroute/connect-express";
const licenRouteProtection = licenroute({
apiKey: process.env.LICENROUTE_API_KEY ?? "",
siteId: process.env.LICENROUTE_SITE_ID ?? "",
endpoint: process.env.LICENROUTE_ENDPOINT ?? "",
licensedPaths: [{ path: "/api/reports/**", methods: ["GET", "HEAD"] }],
withoutPolicy: "deny",
fallback: "allow",
// …
});
app.use(licenRouteProtection);
licensedPaths are always denied when the decision service doesn’t answer; fallback: "allow" applies only to everything else. Then licenroute test runs every case in the checklist against a local simulator, including the outage and the recovery, and licenroute undo reverts the change byte for byte.
Try it
git clone https://github.com/licenroute/licenroute.git licenroute && cd licenroute npm ci --ignore-scripts && npm run build && ./demo/demo.sh
Then follow the tutorial. Or let your AI assistant do it with the prompt on the home page.