Designing API keys like Stripe and GitHub do
| Part | Example | Why |
|---|---|---|
| Prefix | key_, sk_live_, ghp_ | humans and scanners see what the key is for |
| Environment marker | _live_ / _test_ | prevents using test keys in production by accident |
| Random body | 64 hex chars (32 bytes) | unguessable, URL- and header-safe |
| Optional checksum | last 6 chars = CRC32 of the body | lets scanners reject random strings that only look like keys |
GitHub's token format (ghp_ + 30 random chars + a CRC32 checksum) is the reason its secret scanning has very few false positives. A prefix alone already gets you most of the benefit.
Storing and checking API keys on the server
import { createHash, timingSafeEqual } from "node:crypto";
const sha256 = (s: string) => createHash("sha256").update(s).digest();
// on creation: show apiKey to the user once, store only the hash + a lookup prefix
const record = { prefix: apiKey.slice(0, 12), hash: sha256(apiKey).toString("hex") };
// on each request
function verify(presented: string, stored: { hash: string }) {
const a = sha256(presented);
const b = Buffer.from(stored.hash, "hex");
return a.length === b.length && timingSafeEqual(a, b);
}A fast hash (SHA-256) is fine here, unlike for passwords: the key has 256 random bits, so there is nothing to brute-force. For human passwords use the bcrypt generator instead.
Keeping your own API keys out of git
- Read keys from environment variables (
process.env.PAYMENTS_API_KEY), never hard-code them. - Commit a
.env.examplewith empty values, generated by the .env.example generator. - Scan before pushing: the ENV leak checker flags known key formats in a .env.
- If a key leaks, revoke it first and investigate second. Rotation is cheap when every key has an ID.