API Key Best Practices: Generation, Storage & Rotation
A practical guide to API key security: from generating strong keys to storing them safely, rotating them regularly, and following industry-standard conventions.
Why API Keys Matter
API keys are the credentials that authenticate applications, services, and automated systems. Unlike user passwords, API keys are typically long-lived, embedded in code and configuration files, and shared across teams and deployment environments. This makes them simultaneously critical and vulnerable: a leaked API key can grant an attacker full access to your services, data, and infrastructure.
According to GitGuardian's annual reports, millions of secrets are exposed in public repositories every year. Many of these are API keys that were accidentally committed to version control. The consequences can be severe: unauthorized access, data breaches, unexpected billing charges (especially with cloud provider keys), and regulatory compliance violations.
Generating Secure API Keys
The foundation of API key security is generating keys with sufficient randomness (entropy) that they cannot be guessed or brute-forced. Here are the principles for generating strong API keys:
Use Cryptographic Random Number Generators
Never generate API keys using Math.random(), predictable seeds, or sequential counters. Always use a cryptographically secure random number generator (CSPRNG):
Secure Key Generation Examples
const apiKey = crypto.randomBytes(32).toString('hex');
// Output: "a3f8b2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1"
api_key = secrets.token_hex(32)
# or: api_key = secrets.token_urlsafe(32)
const apiKey = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
Our Password Generator uses the Web Crypto API for all key generation, ensuring cryptographic security.
Key Length Recommendations
The length of your API key determines its entropy and resistance to brute-force attacks. Here are recommended minimum lengths:
- Hex-encoded (32 bytes / 64 chars): 256 bits of entropy -- standard for most APIs
- Base64url-encoded (32 bytes / 43 chars): Same 256-bit entropy, more compact representation
- Alphanumeric (40+ chars): Approximately 238 bits with a-z, A-Z, 0-9 -- widely compatible
For reference, 128 bits of entropy is the absolute minimum for security, but 256 bits is the industry standard and provides a generous margin against future advances in computing power. For more on how entropy affects security, see our guide on password strength.
Prefix Conventions
Modern API key design includes a human-readable prefix that identifies the key type and the service it belongs to. This practice, popularized by Stripe and now adopted by GitHub, Slack, Supabase, and many others, serves multiple important purposes:
- Identification: You can immediately tell what a key is for by looking at its prefix
- Secret scanning: GitHub, GitLab, and other platforms can detect leaked keys by matching known prefixes
- Environment separation: Different prefixes for test vs production keys prevent accidental misuse
- Debugging: Log entries that reference
sk_live_...are immediately identifiable
Common Prefix Patterns
| Service | Prefix Pattern | Example |
|---|---|---|
| Stripe | sk_live_ / sk_test_ | sk_live_51J... |
| GitHub | ghp_ / ghs_ / gha_ | ghp_xxxx... |
| Slack | xoxb- / xoxp- | xoxb-xxxx... |
| OpenAI | sk- | sk-xxxx... |
| Supabase | sbp_ / sb_ | sbp_xxxx... |
When designing your own API, adopt the prefix_environment_randompart convention.
Our Password Generator includes an API Key tab with support for custom prefixes, letting you generate properly formatted keys that follow these industry conventions.
Storing API Keys Securely
Generating a strong key is meaningless if it is stored insecurely. Here are the storage patterns ranked from most to least recommended:
1. Secret Managers (Best)
Dedicated secret management services are purpose-built for storing sensitive credentials:
- AWS Secrets Manager / Parameter Store: Native integration with AWS services, automatic rotation support
- Google Cloud Secret Manager: Versioned secrets with IAM-based access control
- Azure Key Vault: HSM-backed storage with audit logging
- HashiCorp Vault: Self-hosted or managed, with dynamic secrets and lease-based access
- Doppler / Infisical: Developer-friendly secret managers with team collaboration features
Secret managers provide versioning, access control, audit logging, and automatic rotation -- capabilities that no other storage method can match.
2. Environment Variables (Good)
Environment variables are the minimum acceptable standard for storing API keys in production. They keep secrets out of your codebase and allow different values per environment:
Environment Variable Setup
DATABASE_URL=postgresql://...
JWT_SIGNING_KEY=your_256bit_key_here
.env.local
.env.*.local
Always add .env* patterns to your .gitignore before creating any environment files. One accidental commit can expose all your secrets.
3. Configuration Files (Acceptable with Encryption)
Some deployment systems use encrypted configuration files (e.g., Kubernetes Sealed Secrets, SOPS, or Rails encrypted credentials). These are acceptable when the decryption key itself is managed securely (typically through a secret manager or environment variable).
What to Never Do
- Never hardcode keys in source code: This is the most common mistake. Even in private repositories, credentials in code can be exposed through forks, CI logs, error messages, or future repository visibility changes.
- Never commit keys to version control: Even if you delete a key in a later commit, it remains in the Git history forever. Removing secrets from Git history requires rewriting history, which is disruptive and error-prone.
- Never share keys via chat or email: These channels are not encrypted end-to-end in most cases, and messages are stored indefinitely on third-party servers. Use a secret manager or encrypted file transfer.
- Never log keys: Ensure your logging framework does not capture request headers, environment variables, or configuration objects that contain secrets. Use secret redaction in your logging pipeline.
Rotation Strategies
Key rotation is the practice of periodically replacing API keys with new ones. Even if a key has not been compromised, regular rotation limits the blast radius of any undetected leak and ensures that former team members or contractors lose access over time.
Zero-Downtime Rotation
The key challenge with rotation is avoiding service interruption. The standard approach is a dual-key (overlap) strategy:
- Generate a new key while keeping the old key active
- Deploy the new key to all consumers (applications, services, partners)
- Verify that all traffic is using the new key (monitor old key usage)
- Revoke the old key once no traffic uses it (or after a grace period)
This overlapping period ensures that no consumer experiences authentication failures during the transition. The server must accept both keys during the overlap window.
Rotation Frequency
How often you rotate depends on the key's risk profile:
- Every 90 days: General-purpose API keys, service-to-service authentication
- Every 30 days: Keys with broad access, keys shared with third parties
- Immediately: After any suspected compromise, team member departure, or security incident
- Automatically: Cloud providers often support automatic rotation (e.g., AWS Secrets Manager can rotate keys on a schedule with a Lambda function)
Server-Side Key Management
If you are building an API that issues keys to users, here are best practices for the server side:
- Store only hashes: Just like passwords, API keys should be hashed (e.g., with SHA-256) before storage. Show the full key to the user exactly once at creation time. When authenticating, hash the incoming key and compare it to the stored hash. For more on hashing, see our guide to hashing.
- Include metadata: Store creation date, last used date, creator, description, and expiration alongside each key hash. This enables auditing and automated cleanup.
- Support multiple keys per user: Users should be able to create separate keys for different purposes (CI/CD, local development, production) and revoke them independently.
- Implement rate limiting: Apply per-key rate limits to prevent abuse and limit the impact of a compromised key.
- Log usage: Record when each key is used (without logging the key itself). This creates an audit trail for security investigations.
Encoding and Format Considerations
The encoding format of your API key affects its usability and compatibility:
- Hexadecimal: Uses characters 0-9 and a-f. Simple and universally compatible but less compact (64 characters for 256 bits). You can create hex-encoded keys using our Hash Generator or the Password Generator's API key mode.
- Base64url: Uses A-Z, a-z, 0-9, hyphen, and underscore. More compact than hex (43 characters for 256 bits) and safe for use in URLs and HTTP headers. OurBase64 Encoder can help you understand this encoding.
- UUID v4: A standardized format that provides 122 bits of randomness. Widely supported but lower entropy than custom key formats. See ourUUID Generator for details.
Generate API Keys Now
Ready to generate secure API keys? Our Password Generator includes a dedicated API Key tab with support for custom prefixes, multiple encoding formats, and configurable key lengths. All keys are generated client-side using the Web Crypto API -- your secrets never leave your browser.
Further Reading
- OWASP API Security Top 10
OWASP's top 10 API security risks and mitigation strategies.
- NIST SP 800-63B — Authentication Guidelines
NIST digital identity guidelines for authentication and lifecycle management.
- Google Cloud — API key best practices
Google Cloud documentation on securing and managing API keys.