Guide · Developer security
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 bitsGood for most applications192 bitsHigh-security applications256 bitsMaximum security / encryption keysUse 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, productionsk_test_Secret key, test/sandboxpk_live_Public key, productionpk_test_Public key, test/sandboxrk_Restricted/limited permissionsPrefixes 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 fileDon'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
- Generate new key - Create a new key before revoking the old one
- Deploy new key - Update your applications to use the new key
- Verify functionality - Ensure everything works with the new key
- Revoke old key - Disable the previous key
- Monitor - Watch for any failures using the old key
Recommended rotation frequency:
High-security keysEvery 30-90 daysStandard keysEvery 90-180 daysAfter incidentsImmediatelyPersonnel changesWhen developers leave the teamAccess 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
Emergency Response
If you suspect an API key has been compromised:
- Revoke immediately - Disable the compromised key
- Audit usage - Review logs for unauthorized access
- Generate new key - Create a replacement with new value
- Deploy replacement - Update all applications
- Investigate - Determine how the key was exposed
- Document - Record the incident and response