← All Guides

API Key Best Practices

A comprehensive guide to generating, storing, and managing API keys securely.

What Makes a Secure API Key?

API keys are the credentials that authenticate your applications with external services. A compromised API key can lead to data breaches, financial losses, and service abuse. Here's how to keep them secure.

Key Generation Requirements

  • Length: Minimum 32 characters for adequate entropy
  • Randomness: Use cryptographically secure random number generators (CSPRNG)
  • Character Set: Alphanumeric (62 characters) provides good entropy density
  • Entropy: Aim for at least 128 bits of entropy

Recommended entropy levels:

  • 128 bits - Good for most applications
  • 192 bits - High-security applications
  • 256 bits - Maximum security / encryption keys

Use Meaningful Prefixes

Key prefixes help identify the type and environment of a key at a glance, making it easier to detect misuse and prevent accidents.

Common prefix patterns:

  • sk_live_ - Secret key, production
  • sk_test_ - Secret key, test/sandbox
  • pk_live_ - Public key, production
  • pk_test_ - Public key, test/sandbox
  • rk_ - Restricted/limited permissions

Prefixes make it easy to set up automated scanning for leaked keys. Services like GitHub's secret scanning can detect keys with known prefixes.

Storage Best Practices

Do: Use Environment Variables

# .env (never commit this file!)
STRIPE_API_KEY=sk_live_abc123...
DATABASE_URL=postgres://...

# Access in code
const apiKey = process.env.STRIPE_API_KEY;

Do: Use Secret Management Services

  • AWS Secrets Manager - Automatic rotation, IAM integration
  • HashiCorp Vault - Self-hosted, dynamic secrets
  • Google Secret Manager - GCP-native, versioning
  • Azure Key Vault - Azure-native, HSM-backed

Don't: Store in Code or Repos

// NEVER do this!
const apiKey = "sk_live_abc123...";  // Hardcoded
const config = require('./config.json');  // Committed file

Don't: Log API Keys

// NEVER do this!
console.log("Using API key:", apiKey);
logger.info({ apiKey, request });

Key Rotation Strategy

Regular key rotation limits the window of exposure if a key is compromised. Implement a rotation strategy that minimizes downtime.

Rotation Process

  1. Generate new key - Create a new key before revoking the old one
  2. Deploy new key - Update your applications to use the new key
  3. Verify functionality - Ensure everything works with the new key
  4. Revoke old key - Disable the previous key
  5. Monitor - Watch for any failures using the old key

Recommended rotation frequency:

  • High-security keys: Every 30-90 days
  • Standard keys: Every 90-180 days
  • After incidents: Immediately
  • Personnel changes: When developers leave the team

Access Control & Permissions

Follow the principle of least privilege. Each key should have only the permissions it needs to function.

Permission Scoping

  • Read-only keys for analytics and reporting
  • Write keys only where needed
  • Admin keys only for administrative applications
  • Environment separation - different keys for dev/staging/production

Rate Limiting & Quotas

Set rate limits and quotas on your API keys to prevent abuse:

  • Requests per minute/hour/day
  • Maximum data transfer
  • IP allowlisting where possible

Monitoring & Alerting

Active monitoring helps detect compromised keys quickly:

  • Usage anomalies - Sudden spikes in API calls
  • Geographic anomalies - Requests from unexpected locations
  • Failed authentication - Multiple failed auth attempts
  • Secret scanning - Monitor GitHub, GitLab for leaked keys

Pro tip: Use services like HaveIBeenPwned to check if your keys have appeared in data breaches.

Emergency Response

If you suspect an API key has been compromised:

  1. Revoke immediately - Disable the compromised key
  2. Audit usage - Review logs for unauthorized access
  3. Generate new key - Create a replacement with new value
  4. Deploy replacement - Update all applications
  5. Investigate - Determine how the key was exposed
  6. Document - Record the incident and response

Related Tools