Last updated
What Is an API Key?
An API key is a unique identifier used to authenticate requests to an API. Unlike OAuth tokens, API keys are simple strings — typically 32–64 random characters — that are included in requests via a header, query parameter, or request body. They identify the calling application and are used for rate limiting, usage tracking, and access control.
API Key Formats
| Format | Example | Entropy |
|---|---|---|
| Hex (32 chars) | a3f8c2d1e4b5... | 128 bits |
| Base64 (32 chars) | Xk9mP2qR7sT... | ~192 bits |
| UUID v4 | 550e8400-e29b-41d4-a716-... | 122 bits |
| Prefixed (Stripe-style) | sk_live_abc123... | Varies |
| Base58 (no ambiguous chars) | 3mFpqR7sT9... | ~190 bits |
Generating Secure API Keys
// Browser: cryptographically secure random bytes
function generateApiKey(length = 32) {
const bytes = new Uint8Array(length);
crypto.getRandomValues(bytes);
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
}
// With prefix (like Stripe's sk_live_ format)
function generatePrefixedKey(prefix = 'key', length = 32) {
const random = generateApiKey(length);
return `${prefix}_${random}`;
}
// Node.js
import { randomBytes } from 'crypto';
const apiKey = randomBytes(32).toString('hex');
const base64Key = randomBytes(32).toString('base64url');
console.log(generateApiKey());
// → 'a3f8c2d1e4b5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1'
API Key Security Best Practices
- Never commit API keys to version control — use environment variables.
- Use different keys for development and production environments.
- Implement key rotation — allow multiple active keys during transition.
- Store keys hashed (SHA-256) in the database, not in plaintext.
- Set expiration dates and scope restrictions on keys.
- Log all API key usage for audit trails.