Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Tokens, JWT and OAuth

API Keys: Generate, Store and Rotate

Design API keys properly: generate them with crypto randomness, store only a hash, look them up by prefix, scope, revoke and rotate them. Runnable Node.js demo.

An API key is a long random string that identifies an application (not a person) calling your API. Keys are the simplest credential: the client sends one in a header and the server looks it up. Payment providers, map services and weather APIs use them because developers can get started in a minute, with no OAuth flow.

Simple does not mean careless. A key is a password for a machine, so it must be generated randomly, stored as a hash, scoped to what it needs, and easy to revoke and rotate. This lesson builds a complete key system in Node.js.

A good API key

Random 32 bytes from crypto.
Hashed at rest Show the key once.
Scoped Only what the app needs.
Revocable Kill one key, not all.

Treat it like a password.

1 / 2

Key format

Give keys a recognizable structure:

TEXT
sk_live_94e315a61d2b_7Hq2Zr9aBxN4kT1mWcP8dEoLs6VuY3JfQ2w8Rz1xKgA
Piece Why
sk Type: secret key (versus pk, a public key that is safe in browsers)
live Environment (live or test)
Short ID A non-secret public identifier used to find the record (here 12 hex characters)
Random body At least 128 bits, ideally 256, from crypto.randomBytes

A visible prefix lets secret scanners detect leaked keys in source code and lets users tell keys apart in dashboards. Never derive a key from a user ID, timestamp or counter. Use crypto, not Math.random().

Storing keys safely

Show the full key to the user exactly once, at creation. Store only:

  • the key's public ID (for lookup),
  • a hash of the secret part,
  • metadata: owner, name, scopes, created, last used, expires, revoked.

Because the secret has 256 bits of randomness, a fast hash like SHA-256 is enough (slow password hashes such as bcrypt exist to protect low-entropy human passwords, and would only make every API call slow). Look the record up by ID, then compare hashes with timingSafeEqual.

Node.js Create and verify API keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The stored record has no field containing the key. If your database leaks, the attacker gets hashes that cannot be turned back into keys.

Sending the key

Prefer a header over the URL. URLs end up in browser history, server logs and proxies. Common conventions:

HTTP
GET /v1/invoices HTTP/1.1
Authorization: Bearer sk_live_...

or a dedicated header such as X-API-Key: sk_live_.... Never accept keys in query strings except for tiny low-risk cases (public map tiles, for instance), and never in a GET body. Always require HTTPS.

A key-protected API

This demo serves /v1/invoices and /v1/admin. Keys carry scopes, and the server answers 401 for unknown or revoked keys and 403 for a key without the needed scope. It also records usage per key, which is the basis for billing and rate limits (Rate Limiting and Abuse Protection).

Node.js Scoped keys over HTTP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Lifecycle: expire, rotate, revoke

  • Create several keys per customer (one per app or environment), each with a name.
  • Rotate without downtime: create the new key, deploy it, then delete the old one. Allow two active keys at once.
  • Expire keys that have not been used for a long time, and optionally set a hard expiry.
  • Revoke instantly on a leak, and tell the owner. If you publish a secret-scanning pattern, GitHub and others can notify you when a key is found in a public repository.
  • Log which key made each call (by ID, never the secret), so you can investigate abuse.

When API keys are not enough

A key has no user and usually no short expiry, so it suits server-to-server calls and developer access, not user logins. Never ship a secret key inside a mobile app or browser JavaScript: anyone can extract it. For user-facing access use OAuth and short-lived tokens (OAuth 2.0 Flows). For browsers, use a restricted public key limited by allowed origins, never the secret one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How should the server store an API key?

    A hash lets you verify a presented key without being able to reveal it, so a database leak does not expose working keys.
  2. 2. Why is SHA-256 acceptable for API keys but not for user passwords?

    Slow hashes defend low-entropy secrets against brute force. A 256-bit random key cannot be brute-forced anyway.
  3. 3. Where should a client send its API key?

    URLs get logged and cached. Headers are not part of the URL and are not stored in history.
  4. 4. How do you rotate a key without downtime?

    Overlapping validity means clients can switch over before the old key is removed.
  5. 5. Should a secret API key be embedded in a mobile app?

    Anything shipped to a client device can be read by the user. Use short-lived tokens or origin-restricted public keys instead.

Summary

  • An API key identifies an application; make it random (128+ bits), prefixed and long.
  • Show it once, store only a hash plus a public ID, and compare in constant time.
  • Send keys in headers over HTTPS, never in URLs.
  • Scope each key, log usage by key ID, and support revoke, expire and rotate.
  • 401 for unknown or revoked keys, 403 for a valid key that lacks the scope.
  • Secret keys belong on servers only.

Next: Authorization and Object-Level Access