How to Store API Keys Securely
Best practices for managing sensitive credentials
Storing API keys securely is one of the most important aspects of application security. This guide covers proven methods for protecting your credentials in development and production.
Never Commit Keys to Version Control
The first rule of API key security: never store credentials in git repositories. Add .env files to .gitignore and use pre-commit hooks to prevent accidental commits.
Environment Variables
Environment variables are the minimum standard for configuration. They keep credentials out of source code and allow different values per environment.
# .env.local (add to .gitignore) API_KEY=sk_live_123456789 DATABASE_URL=postgresql://user:pass@localhost:5432/db
Secrets Management Services
For production applications, use dedicated secrets managers:
- AWS Secrets Manager - Automated rotation, fine-grained access
- HashiCorp Vault - Open-source, dynamic secrets, audit logging
- Google Secret Manager - Integration with GCP services
- Azure Key Vault - Secrets, certificates, and key management
- 1Password/LastPass - Developer-focused secret sharing
Encryption at Rest
For additional security, encrypt sensitive configuration files using AES-256 encryption. Decrypt only at runtime in memory, never write decrypted values to disk.
Key Rotation Strategy
Implement automated key rotation to limit the impact of compromised credentials. Most managed services support automatic rotation with zero downtime.