APIs · Intermediate · 24 min
Protect an API with API keys you can rotate and revoke
By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · Express 5.3 · node:26 image
You will build an API key system for an Express 5.3 API on Node.js 26 that issues prefixed random keys, stores only their SHA-256 hashes, checks scopes, records last use, and rotates or revokes any key without breaking the partners who hold the others.
On this page
An API key is a long random string that a partner's server sends with every request, so your API knows who is calling and what they may do. Keys are the plain, durable choice for server-to-server access: a logistics partner pulling orders every night, a reporting job, an internal service. They go wrong in predictable ways. A key is stored in plain text and leaks with a database backup. It lands in a URL and from there in proxy logs. One key does everything, so a read-only dashboard can also delete data. Or a key cannot be changed without a coordinated outage, so nobody changes it.
This tutorial builds a small orders API and a key system that avoids each of those. Keys carry a recognisable prefix, so leaked ones are easy to spot. The server keeps only a SHA-256 hash, looks keys up by an id inside them and compares hashes in constant time. Keys travel only in a header, carry scopes, record when they were last used, and can be rotated with an overlap window or revoked at once.
Everything runs on your own computer. The API listens on 127.0.0.1:3000 and keys live in a JSON file, which stands in for a database table.
Step 1 · Create the project
Make a throwaway folder, add Express 5.3 and switch the project to ES modules. Tell Git to ignore the key store and the key files you will create, before any of them exist (see keep secrets out of Git for the wider habit):
mkdir -p ~/apikey-demo
cd ~/apikey-demo
npm init -y > /dev/null
npm pkg set type=module
npm install express@5.3.0
printf '%s\n' node_modules/ keys.json '*.key' '*.hdr' > .gitignoreCheck it worked
cd ~/apikey-demo
node -p "require('express/package.json').version"
cat .gitignoreThe first line is 5.3.0. The .gitignore lists node_modules/, keys.json, *.key and *.hdr.
Step 2 · Decide what a key looks like
A key here has three parts joined by underscores:
ordk, a fixed prefix for this product. Anyone who findsordk_...in a log, a chat or a public repository knows at once what it is. GitHub uses the same idea for its own tokens (ghp_and friends), and its secret scanning service can match registered prefixes in public code and alert the issuer.- A 12-character hex id, from 6 random bytes. It is not secret. The server uses it to find the right record without scanning every key, and you use it in logs and support conversations.
- A secret of 32 random bytes from
crypto.randomBytes, written as 43 characters of base64url. That is 256 bits, far beyond any guessing attack.
A finished key looks like ordk_3f9a0c1b7d2e_Vq8... and is 61 characters long. Create the module that makes, hashes and checks keys:
cd ~/apikey-demo
cat > keys-store.js <<'JS'
import crypto from 'node:crypto';
import fs from 'node:fs';
const FILE = process.env.KEYS_FILE ?? 'keys.json';
const PREFIX = 'ordk';
const KEY_PATTERN = /^ordk_([0-9a-f]{12})_[A-Za-z0-9_-]{43}$/;
export function load() {
try {
return JSON.parse(fs.readFileSync(FILE, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return {};
throw err;
}
}
// Write a new file and rename it over the old one, so a crash never leaves half a file.
export function save(keys) {
const tmp = `${FILE}.tmp`;
fs.rmSync(tmp, { force: true });
fs.writeFileSync(tmp, JSON.stringify(keys, null, 2) + '\n', { mode: 0o600 });
fs.renameSync(tmp, FILE);
}
export function hash(key) {
return crypto.createHash('sha256').update(key).digest('hex');
}
// Returns the full key (show it once, never store it) and the record to store.
export function newKey(name, scopes) {
const id = crypto.randomBytes(6).toString('hex');
const secret = crypto.randomBytes(32).toString('base64url');
const key = `${PREFIX}_${id}_${secret}`;
const record = {
id,
name,
scopes,
hash: hash(key),
createdAt: new Date().toISOString(),
lastUsedAt: null,
expiresAt: null,
revokedAt: null,
};
return { key, record };
}
export function status(record, now = new Date()) {
if (record.revokedAt) return 'revoked';
if (record.expiresAt && new Date(record.expiresAt) <= now) return 'expired';
if (record.expiresAt) return `active until ${record.expiresAt}`;
return 'active';
}
// Returns { ok: true, record, keys } or { ok: false, reason, id? }.
export function check(presented, now = new Date()) {
const match = KEY_PATTERN.exec(presented ?? '');
if (!match) return { ok: false, reason: 'missing or malformed key' };
const keys = load();
const record = keys[match[1]];
if (!record) return { ok: false, reason: 'unknown key id' };
const given = Buffer.from(hash(presented), 'hex');
const stored = Buffer.from(record.hash, 'hex');
if (!crypto.timingSafeEqual(given, stored)) return { ok: false, reason: 'wrong secret', id: record.id };
const state = status(record, now);
if (state === 'revoked' || state === 'expired') return { ok: false, reason: state, id: record.id };
return { ok: true, record, keys };
}
// Record the last use, at most once a minute per key, so busy keys do not write on every request.
export function touch(record, keys, now = new Date()) {
const last = record.lastUsedAt ? Date.parse(record.lastUsedAt) : 0;
if (now - last < 60_000) return;
keys[record.id].lastUsedAt = now.toISOString();
save(keys);
}
JSWhy SHA-256 and not bcrypt or Argon2? Slow password hashes exist because people pick guessable passwords. These secrets are 256 random bits, so nobody can work backwards from a fast hash by guessing, and a fast hash keeps every request cheap. If you want extra protection against someone who steals only the database, use an HMAC with a server-side secret held outside it, read from an environment variable, in place of the plain hash.
Check it worked
Make one key in memory and look at its shape, without saving it:
cd ~/apikey-demo
node -e "import('./keys-store.js').then(({ newKey }) => { const { key, record } = newKey('try', []); console.log(key.length, key.startsWith('ordk_'), key.split('_')[1] === record.id, record.hash.length); })"The output is 61 true true 64: a 61-character key with the prefix, the id inside it matching the record, and a 64-character hex hash.
Step 3 · Issue keys and store only the hash
A small command-line tool manages the keys. create prints the key once on standard output and everything else on standard error, so you can send the key straight into a private file. There is no way to show it again, because the server never had it in a form it could show:
cd ~/apikey-demo
cat > keys.js <<'JS'
import { load, save, newKey, status } from './keys-store.js';
const SCOPES = new Set(['orders:read', 'orders:write']);
const [command, ...args] = process.argv.slice(2);
const keys = load();
function fail(message) {
console.error(message);
process.exit(1);
}
function issue(name, scopes) {
const { key, record } = newKey(name, scopes);
keys[record.id] = record;
return { key, record };
}
if (command === 'create') {
const [name, ...scopes] = args;
if (!name || scopes.length === 0) fail('usage: node keys.js create <name> <scope> [scope...]');
const unknown = scopes.filter((s) => !SCOPES.has(s));
if (unknown.length) fail(`unknown scope: ${unknown.join(', ')}`);
const { key, record } = issue(name, scopes);
save(keys);
console.error(`created ${record.id} for ${name} with ${scopes.join(' ')}`);
console.log(key);
} else if (command === 'list') {
for (const r of Object.values(keys)) {
console.log(`${r.id} ${r.name} ${r.scopes.join(',')} ${status(r)} last used ${r.lastUsedAt ?? 'never'}`);
}
} else if (command === 'rotate') {
const [id, hours = '24'] = args;
const old = keys[id];
if (!old || !status(old).startsWith('active')) fail(`no active key with id ${id}`);
const overlap = Number(hours);
if (!Number.isFinite(overlap) || overlap < 0) fail('overlap must be a number of hours, 0 or more');
const { key, record } = issue(old.name, old.scopes);
const until = new Date(Date.now() + overlap * 3_600_000).toISOString();
if (!old.expiresAt || until < old.expiresAt) old.expiresAt = until;
old.replacedBy = record.id;
save(keys);
console.error(`rotated ${id} to ${record.id}; ${id} stops working at ${old.expiresAt}`);
console.log(key);
} else if (command === 'revoke') {
const [id] = args;
if (!keys[id]) fail(`no key with id ${id}`);
keys[id].revokedAt = new Date().toISOString();
save(keys);
console.error(`revoked ${id}`);
} else {
fail('usage: node keys.js create|list|rotate|revoke');
}
JSIssue a read-only key for a reporting partner. umask 077 in the subshell makes acme.key private from the moment it exists:
cd ~/apikey-demo
(umask 077; node keys.js create acme-reporting orders:read > acme.key)
ls -l keys.json acme.keyIn a real handover you send the key to the partner over a channel that does not keep it, such as a password manager's sharing feature, and then delete your copy. Here you keep it to test with.
Check it worked
The tool prints created <id> for acme-reporting with orders:read, and both files are listed with -rw-------. Confirm the key itself is nowhere in the store. grep -F -f acme.key reads the key from the file, so it never appears on a command line:
cd ~/apikey-demo
grep -qFf acme.key keys.json && echo "the key is stored in plain text: fix this" || echo "only the hash is stored"
node keys.js listThe first line is only the hash is stored. The list shows one line ending in orders:read active last used never.
Step 4 · Check the key on every request
The server reads the key from the X-API-Key header only. A key in the query string is refused, because URLs end up in proxy and server access logs, browser history and analytics tools, where nobody treats them as secrets. Each failure gets the same 401 body, and the reason goes to your log, so a caller cannot probe which ids exist. HTTP requires a 401 to say how to authenticate, which the WWW-Authenticate header does:
cd ~/apikey-demo
cat > server.js <<'JS'
import express from 'express';
import { check, touch } from './keys-store.js';
const app = express();
app.use(express.json({ limit: '16kb' }));
const orders = [{ id: 1, item: 'Maize flour 10kg', quantity: 3 }];
const KEY_PARAMS = ['api_key', 'apikey', 'key'];
function requireKey(scope) {
return (req, res, next) => {
if (KEY_PARAMS.some((p) => p in req.query)) {
console.log(`refused: key sent in the URL for ${req.path}`);
return res.status(400).json({ error: 'send the API key in the X-API-Key header, never in the URL' });
}
const result = check(req.get('X-API-Key'));
if (!result.ok) {
console.log(`refused: ${result.reason}${result.id ? ` (${result.id})` : ''}`);
res.set('WWW-Authenticate', 'ApiKey realm="orders", header="X-API-Key"');
return res.status(401).json({ error: 'invalid or missing API key' });
}
const { record } = result;
if (!record.scopes.includes(scope)) {
console.log(`forbidden: ${record.id} lacks ${scope}`);
return res.status(403).json({ error: `this key does not have the ${scope} scope` });
}
touch(record, result.keys);
req.apiKey = record;
console.log(`allowed: ${record.id} ${req.method} ${req.path}`);
next();
};
}
app.get('/health', (req, res) => res.json({ ok: true }));
app.get('/v1/orders', requireKey('orders:read'), (req, res) => {
res.json(orders);
});
app.post('/v1/orders', requireKey('orders:write'), (req, res) => {
const { item, quantity } = req.body ?? {};
if (typeof item !== 'string' || !item.trim() || !Number.isInteger(quantity) || quantity < 1) {
return res.status(422).json({ error: 'item (text) and quantity (a whole number from 1) are required' });
}
const order = { id: orders.length + 1, item: item.trim(), quantity };
orders.push(order);
res.status(201).json(order);
});
app.listen(3000, '127.0.0.1', () => {
console.log('listening on http://127.0.0.1:3000');
});
JSThe log names the key id, never the key. The store is read on every request, so a key you revoke stops working on the next call without a restart.
Start the server in a second terminal and leave it running:
cd ~/apikey-demo
node server.jsIt prints listening on http://127.0.0.1:3000.
Back in the first terminal, put the key into a private header file. curl reads headers from a file with -H @file, which keeps the key out of your shell history and the process list:
cd ~/apikey-demo
(umask 077; printf 'X-API-Key: %s\n' "$(cat acme.key)" > acme.hdr)
node -e "import('./keys-store.js').then((m) => console.log('X-API-Key: ' + m.newKey('never-issued', []).key))" > stranger.hdr
curl -s -w ' %{http_code}\n' -H @acme.hdr http://127.0.0.1:3000/v1/orders
curl -s -w ' %{http_code}\n' http://127.0.0.1:3000/v1/orders
curl -s -w ' %{http_code}\n' -H @stranger.hdr http://127.0.0.1:3000/v1/orders
curl -s -w ' %{http_code}\n' 'http://127.0.0.1:3000/v1/orders?api_key=anything'stranger.hdr holds a well-formed key that was never saved, the kind of thing an attacker might try.
Check it worked
The four lines end in 200, 401, 401 and 400:
[{"id":1,"item":"Maize flour 10kg","quantity":3}] 200with the real key.{"error":"invalid or missing API key"} 401with no key and with the never-issued key.{"error":"send the API key in the X-API-Key header, never in the URL"} 400for the query string.
The server terminal shows allowed: <id> GET /v1/orders, refused: missing or malformed key, refused: unknown key id and refused: key sent in the URL for /v1/orders. If a partner ever does send a key in a URL, treat that key as leaked and rotate it.
Step 5 · Limit each key with scopes
The reporting key has orders:read only. Try to create an order with it, then issue a second key for a warehouse system that needs to write:
cd ~/apikey-demo
curl -s -w ' %{http_code}\n' -H @acme.hdr -H 'Content-Type: application/json' \
-d '{"item":"Rice 5kg","quantity":2}' http://127.0.0.1:3000/v1/orders
(umask 077; node keys.js create warehouse-sync orders:read orders:write > warehouse.key)
(umask 077; printf 'X-API-Key: %s\n' "$(cat warehouse.key)" > warehouse.hdr)
curl -s -w ' %{http_code}\n' -H @warehouse.hdr -H 'Content-Type: application/json' \
-d '{"item":"Rice 5kg","quantity":2}' http://127.0.0.1:3000/v1/orders401 means "I do not know who you are". 403 means "I know who you are, and you may not do this". Keeping them apart tells a partner's developer whether to check their key or ask you for more access.
Check it worked
The first request prints {"error":"this key does not have the orders:write scope"} 403. The second prints {"id":2,"item":"Rice 5kg","quantity":2} 201. The server logs forbidden: <acme id> lacks orders:write before the warehouse request is allowed.
Give each integration its own key with the fewest scopes it needs. One key per partner, per environment, means you can cut off one without touching the rest.
Step 6 · See which keys are in use
Every allowed request stamps lastUsedAt, at most once a minute per key so a busy key does not write on every call. List the keys:
cd ~/apikey-demo
node keys.js listThis is the column you check before a rotation (is the partner still using the old key?) and in a regular review (keys unused for 90 days are candidates for revocation). In production, keep it in a database column and update it with one UPDATE ... SET last_used_at = now() WHERE id = $1: the JSON file here can lose an update if the tool and the server write at the same instant.
Check it worked
Both lines end in active last used 2026-..., a timestamp from your requests a moment ago, not never.
Step 7 · Rotate a key with an overlap window
Rotation replaces a key on a schedule, or when someone who knew it leaves. If the old key stopped at once, the partner would have an outage until they deployed the new one. So the tool issues a replacement with the same name and scopes and gives the old key a deadline. Both work until then. The id is the second part of the key, so cut can read it:
cd ~/apikey-demo
ACME_ID=$(cut -d_ -f2 acme.key)
(umask 077; node keys.js rotate "$ACME_ID" 24 > acme-new.key)
(umask 077; printf 'X-API-Key: %s\n' "$(cat acme-new.key)" > acme-new.hdr)
curl -s -o /dev/null -w 'old key: %{http_code}\n' -H @acme.hdr http://127.0.0.1:3000/v1/orders
curl -s -o /dev/null -w 'new key: %{http_code}\n' -H @acme-new.hdr http://127.0.0.1:3000/v1/orders
node keys.js listChoose the overlap to fit the partner. A team that deploys daily needs a day. A partner whose integration goes through an agency or a monthly release may need a week or two, so agree the window in writing.
Check it worked
The tool prints rotated <old id> to <new id>; <old id> stops working at <time 24 hours from now>. Both requests print 200. In the list, the old acme key reads active until <that time> and the new one reads active last used ....
Step 8 · Revoke a key, and handle a leak
When the partner's traffic has moved to the new key (its last used time keeps moving and the old one's stops), revoke the old key rather than waiting for the deadline:
cd ~/apikey-demo
node keys.js revoke "$(cut -d_ -f2 acme.key)"
curl -s -o /dev/null -w 'old key: %{http_code}\n' -H @acme.hdr http://127.0.0.1:3000/v1/orders
curl -s -o /dev/null -w 'new key: %{http_code}\n' -H @acme-new.hdr http://127.0.0.1:3000/v1/ordersA leak is different: the key must stop now. Suppose the warehouse key was pasted into a public chat. Rotate it with a zero-hour overlap, so the replacement exists and the old key dies in the same command. Then hand the new key to the warehouse team:
cd ~/apikey-demo
(umask 077; node keys.js rotate "$(cut -d_ -f2 warehouse.key)" 0 > warehouse-new.key)
(umask 077; printf 'X-API-Key: %s\n' "$(cat warehouse-new.key)" > warehouse-new.hdr)
curl -s -o /dev/null -w 'leaked key: %{http_code}\n' -H @warehouse.hdr http://127.0.0.1:3000/v1/orders
curl -s -o /dev/null -w 'replacement: %{http_code}\n' -H @warehouse-new.hdr http://127.0.0.1:3000/v1/ordersAfter a leak, also look at what the key did: search your logs for its id between the moment it leaked and the moment you rotated it.
Check it worked
The output is old key: 401, new key: 200, then leaked key: 401 and replacement: 200. The server logs refused: revoked (<old acme id>) and refused: expired (<old warehouse id>), and node keys.js list shows those two keys as revoked and expired.
Step 9 · Know when keys are not enough, then clean up
API keys answer one question: which system is calling. That fits server-to-server work where a partner's backend holds the key. Move to OAuth 2.1 when any of these is true:
- A third-party app acts on behalf of your users, and each user must agree to what it can do.
- The caller is a browser or a mobile app. Anything shipped to a device can be read by its owner: an Android APK can be unpacked and its strings read, so never put a key in one. For many products in Nigeria, Kenya and across Africa, an Android app on a low-cost phone is the main client, so plan for this from the start. Have users sign in and give the app short-lived tokens.
- You need tokens that expire in minutes, or many integrations that register themselves without you issuing keys by hand.
Before you trust this system with partners, also put the API behind HTTPS (a key over plain HTTP can be read on the network), rate limit by key id, and alert on bursts of 401s from one address.
Stop the server with Ctrl+C in its terminal. Then delete the folder, which holds the key store and every key file:
cd ~
rm -rf ~/apikey-demoCheck it worked
ls ~/apikey-demo reports No such file or directory, and curl http://127.0.0.1:3000/health fails to connect.
Next steps
- Learn the token-based alternative: understand OAuth 2.1 and OpenID Connect with PKCE.
- If you issue signed tokens as well as keys: avoid the JWT mistakes that break API security.
- Limit each key's request rate: rate limit an API in application code.
- Sign what you send to partners as well as checking what they send you: verify webhook signatures in Node.js.
Part of these paths
Related tutorials
- Avoid the JWT mistakes that break API securityYou will break a deliberately weak Node.js API with forged, misdirected and expired JSON Web Tokens, then replace its checks with a jose 6.2 verifier that pins the algorithm and every claim, so each attack ends in a 401.
- How to Keep Passwords and API Keys Out of GitYou will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.
- How to Build a REST API with Express 5You will build a small items API with Express 5.3 on Node.js 26 that validates its input, returns the right HTTP status codes, never sends a stack trace to callers, and has automated tests that use only Node's built-in test runner.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials