We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

API Keys

API keys are often used to authenticate programmatic requests. They're not user sessions or OAuth tokens: they're often long-lived bearer credentials, which makes them very dangerous if leaked.

Just imagine how much you could run up my Claude bill if you had my API key...

Common Ways API Keys Leak

  • Hard-coded in source repositories
  • Logged during debugging
  • Stored in frontend JavaScript
  • Pasted into Slack messages
  • Committed in .env files

Generating Secure Keys

Keys must be cryptographically random and long enough to resist guessing. Thirty-two random bytes (256 bits) is a strong default.

// unsafe: predictable pattern
const apiKey = `${userId}-${Date.now()}`;

// safer: cryptographically random
import { randomBytes } from "node:crypto";
const apiKey = randomBytes(32).toString("hex");

Never generate keys from user data, timestamps, or anything predictable, just use a secure random generator.

Secure Storage

If your service only needs to verify incoming keys, store a hash of each high-entropy key rather than the plaintext.

import { hash } from "node:crypto";

function hashApiKey(apiKey: string): string {
  return hash("sha256", apiKey, "hex");
}

Generate the raw key, display it once, and then store its hash. That way if an attacker secretly gains read-access to your database, they won't have the plaintext keys to use.

Key Rotation

Rotate keys:

  • Immediately after suspected compromise
  • When the client or owner no longer needs access
  • Before expiration or on the schedule required by your risk policy

If a key is compromised, revoke it immediately, notify the owner, and investigate the incident.

Treat API keys like passwords: transmit them only over HTTPS, keep them out of URLs and logs, and make revocation easy.

Assignment

Bearly Secure has a small machine-to-machine endpoint for a warehouse integration, but anyone can currently call it. The route should authenticate requests with an API key in the X-API-Key header.

Require a valid warehouse API key on the existing orders endpoint.

With Bearly Secure still running, run and submit the CLI tests from the project root.