An API key is a password your customer will paste into a shell script, commit to a public repository, and forward to a contractor. Design the system as if all three have already happened.
The failure mode is always the same. A key leaks — through a GitHub push, a Slack message, a request logged in full — and because the key was stored in the clear, whoever reaches your database walks away with every customer’s live credentials at once. Most API-key implementations I review get the token generation right and the storage catastrophically wrong. What follows is the scheme I keep rebuilding: hashed storage, identifiable prefixes, scopes carried on the key itself, and rotation that does not take the customer down. The stack here is NestJS 10 on Node 22 with PostgreSQL 17, but the design travels.
Store the hash, never the key
An API key is a bearer token: possession is authentication. That makes your api_keys table a list of live passwords, and it deserves exactly the treatment a password table gets. Hash on the way in, compare hashes on the way out, and accept that once you have shown the customer their key at issuance you can never show it again. If your support flow includes “let me read your key back to you”, you have stored it in plaintext and you have a breach waiting to be discovered.
Free · 4 minutes
Would you survive contact with a determined attacker — or an auditor?
Fourteen questions on access, patching, detection, and recovery — the basics that prevent most real incidents, and the ones most often assumed rather than verified. Banded finding on screen, full sheet by email.
There is an honest nuance here. Unlike a human password, a generated key is high-entropy and random, so brute-forcing its hash is infeasible regardless of the algorithm’s speed — a plain SHA-256, or an HMAC-SHA-256 under a server-side pepper, is a defensible and much cheaper choice per request. I use argon2id in this build because the same verification path already exists for user passwords and the per-request cost is bounded to a single verify. If you are serving tens of thousands of requests a second, reach for the peppered HMAC instead and keep the pepper somewhere the database cannot reach it — the same logic that pushes signing keys towards hardware-backed storage.
The prefix earns its keep
A good key has two parts glued together: a public lookup id and a secret. The token I issue looks like sxp_live_9f3a1c7b2e50.<secret>, and the split does two jobs. The sxp_live_ stem is a fingerprint — secret scanners such as GitHub’s, gitleaks and trufflehog can be taught to match it, and a human glancing at a log line knows immediately what leaked and which environment it belongs to. The lookup id that follows is what makes the database read a single indexed row rather than a full-table scan.
That second point is not cosmetic. If you stored only a hash of the whole token, authenticating a request would mean running argon2 against every row until one matched — ruinously slow, and a denial-of-service lever an attacker pulls with garbage tokens. The lookup id reduces every request to one indexed SELECT and exactly one hash verify.
Scopes and rate tiers belong on the key
A key minted for a read-only reporting integration should not be able to issue a POST that moves money. The place to enforce that is the key, not a note in the customer’s account settings. Store scopes as a Postgres array and check them in the guard against whatever the route declares it needs. A rate_tier column lets you throttle a free-plan key differently from an enterprise one without a second lookup. This is the same posture I argued for when hardening an MCP server: authentication, scoping and rate limits are one decision, taken at the edge, on every request.
Rotation nobody notices
The reason teams do not rotate keys is that rotation breaks the integration on the other side. Revoke the old key at 9am and something goes dark until a human on the customer’s side pastes the new one in. The fix is to allow more than one live key per owner — and the schema above already does, because nothing constrains an owner to a single row.
Rotation then becomes calm: issue key B, hand it over, let A and B both authenticate, and let the customer cut over at their own pace. You revoke A only once its last_used_at has gone quiet, which is precisely what that column is for. The same signal drives cleanup — a key untouched for ninety days is either dead or dangerous, and either way it should not still be live. This is the API-key equivalent of the overlap window that makes JWKS key rotation survivable: two valid credentials at once, never zero.
The schema and issuance
-- PostgreSQL 17
CREATE TABLE api_keys (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
owner_id uuid NOT NULL REFERENCES accounts(id),
key_prefix text NOT NULL UNIQUE, -- public lookup id, e.g. sxp_live_9f3a1c7b2e50
key_hash text NOT NULL, -- argon2id hash of the SECRET half only
scopes text[] NOT NULL DEFAULT '{}',
rate_tier text NOT NULL DEFAULT 'standard',
last_used_at timestamptz,
expires_at timestamptz,
revoked_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
-- One indexed, single-row lookup per request; only live keys are considered.
CREATE INDEX idx_api_keys_prefix_live
ON api_keys (key_prefix) WHERE revoked_at IS NULL;
// issue-api-key.ts (Node 22, argon2 ^0.44)
import { randomBytes } from 'node:crypto';
import * as argon2 from 'argon2';
const LIVE_PREFIX = 'sxp_live_';
export async function issueApiKey(ownerId: string, scopes: string[]) {
// Public lookup id (indexed) and the secret half (never stored raw).
const lookup = randomBytes(6).toString('hex'); // 12 hex chars
const secret = randomBytes(24).toString('base64url'); // ~192 bits of entropy
const keyPrefix = LIVE_PREFIX + lookup;
const keyHash = await argon2.hash(secret, { type: argon2.argon2id });
// A UNIQUE constraint on key_prefix turns the rare collision into a retry.
await db.none(
`INSERT INTO api_keys (owner_id, key_prefix, key_hash, scopes)
VALUES ($1, $2, $3, $4)`,
[ownerId, keyPrefix, keyHash, scopes],
);
// Shown once, at issuance, then gone forever. Format: <prefix>.<secret>
return `${keyPrefix}.${secret}`;
}
The guard
The guard extracts the prefix, fetches the one candidate row, and verifies the secret against the stored hash. Two details matter. It runs a verify even when the prefix is unknown — against a precomputed dummy hash — so an attacker cannot tell an invalid prefix from a wrong secret by timing the response. And the last_used_at write is fire-and-forget; at high volume you would debounce it rather than write on every request, because bookkeeping should never sit on the critical path.
// api-key.guard.ts (NestJS 10)
import {
CanActivate, ExecutionContext, Injectable,
UnauthorizedException, ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import * as argon2 from 'argon2';
// Precomputed once at boot; verified against on a lookup miss to keep timing flat.
const DUMMY_HASH =
'$argon2id$v=19$m=65536,t=3,p=4$c29tZXNhbHR2YWx1ZQ$3g2Xx0Zk...';
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private readonly reflector: Reflector, private readonly db: Db) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
const header: string | undefined = req.headers['authorization'];
if (!header?.startsWith('Bearer ')) throw new UnauthorizedException();
const token = header.slice(7);
const dot = token.lastIndexOf('.');
if (dot < 0) throw new UnauthorizedException();
const keyPrefix = token.slice(0, dot);
const secret = token.slice(dot + 1);
const row = await this.db.oneOrNone(
`SELECT id, key_hash, scopes, expires_at, revoked_at
FROM api_keys WHERE key_prefix = $1`, [keyPrefix]);
// Always run one verify, even on a miss, so response time does not leak
// whether the prefix existed. argon2.verify recomputes in constant time.
const ok = await argon2.verify(row?.key_hash ?? DUMMY_HASH, secret);
const expired = row?.expires_at && row.expires_at < new Date();
if (!row || !ok || row.revoked_at || expired) {
throw new UnauthorizedException();
}
const required =
this.reflector.get<string[]>('scopes', context.getHandler()) ?? [];
if (!required.every((s) => row.scopes.includes(s))) {
throw new ForbiddenException('insufficient scope');
}
// Fire-and-forget: never block the request on a bookkeeping write.
void this.db.none(
`UPDATE api_keys SET last_used_at = now() WHERE id = $1`, [row.id]);
req.apiKey = { id: row.id, scopes: row.scopes };
return true;
}
}
The measure of an API-key scheme is not how it behaves when the key is valid. It is what an attacker holds after they walk off with a copy of your database — and with this one the answer is a table of argon2 hashes and some harmless prefixes, which is to say, nothing they can use.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Free interactive tool
Interactive deadline calculator
Check which regulations apply to you and when
Regulation across the EU, UK, US and Asia-Pacific has moved considerably in the past eighteen months, and several headline dates have shifted more than once. Twelve questions, about three minutes.
Results are shown on screen — no email required. A dated summary is available to download, and can be sent on if that's more useful. What we do with your answers.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.
Full Governance by Sixteen Pillars
Govern your business. Prove your compliance.
A board assurance cockpit for EU-regulated financial firms — tamper-evident, hash-chained proof of governance across DORA, GDPR, NIS2, ISO 27001, the EU AI Act and MiCA. In development.
See what's coming