Learn how to safely store, rotate, and manage your API keys to prevent unauthorized access and data breaches.
A compromised API key can grant attackers full access to your services, data, and user information.
Malicious actors can use your key for malicious activities, resulting in unexpected charges and service abuse.
A breach compromises user data and damages your reputation. Secure key management is essential for compliance.
Always use environment variables or secret management tools. Add .env files to .gitignore to prevent accidental commits of sensitive data.
Store API keys in environment variables on your server or application runtime. Tools like dotenv help manage these securely.
Regularly rotate your API keys every 30-90 days. This limits the window of exposure if a key is compromised.
Leverage services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault for enterprise-grade encryption and access control.
Create API keys with minimal required permissions (principle of least privilege). Different keys for different services reduces risk.
Set up alerts for unusual API activity. Log all key usage and review periodically for suspicious patterns.
API_KEY=sk-YOUR_KEY_HERE
DATABASE_URL=postgresql://user:pass@host/db
DEBUG=false
LOG_LEVEL=info
⚠️ Important: Add .env to your .gitignore file to prevent committing secrets.
require('dotenv').config();
const apiKey = process.env.API_KEY;
if (!apiKey) {
throw new Error('API_KEY not defined in environment');
}
app.get('/api/endpoint', (req, res) => {
// Use apiKey from memory, never hardcode
callExternalAPI(apiKey)
.then(data => res.json(data))
.catch(err => res.status(500).json({error: err.message}));
});
Install: npm install dotenv
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('API_KEY')
if not API_KEY:
raise ValueError('API_KEY not defined in environment')
@app.route('/api/endpoint')
def endpoint():
# Use API_KEY from environment
response = requests.get(
'https://api.service.com/data',
headers={'Authorization': f'Bearer {API_KEY}'}
)
return response.json()
Install: pip install python-dotenv requests
# Use Docker secrets for production
# docker secret create api_key -
docker run -d \
--name myapp \
--secret api_key \
-e API_KEY_FILE=/run/secrets/api_key \
myapp:latest
# Inside container, read secret:
API_KEY=$(cat /run/secrets/api_key)
Note: Docker secrets are encrypted and injected at runtime, never exposed in images.
Enterprise secret management with encryption, audit logging, and fine-grained access control.
AWS service for storing, encrypting, and rotating secrets with automatic lifecycle management.
Microsoft's cloud solution for managing cryptographic keys and secrets with compliance certifications.
Developer-friendly secrets management with team collaboration and zero-knowledge encryption.
Secrets management platform designed for development teams with real-time secret syncing.
Lightweight Python library for loading environment variables from .env files during development.
An API key is a token used for programmatic access to services, while a password is for human authentication. API keys are typically longer, don't expire automatically, and grant access to specific resources. Passwords are shorter and intended for human-readable authentication. Both should be protected equally.
Industry best practice recommends rotating API keys every 30-90 days. However, you should rotate immediately if you suspect compromise. For critical infrastructure, consider more frequent rotation. Some organizations use automated key rotation every 30 days as a security baseline.
Yes, environment variables are safe for production when properly configured. They're loaded at runtime and not stored in code. However, for maximum security in enterprise environments, use dedicated secret management services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault which provide encryption, audit logging, and access controls.
Act immediately: 1) Revoke the exposed key immediately, 2) Review logs for unauthorized access, 3) Generate a new key, 4) Update all systems using the old key, 5) Monitor for suspicious activity, 6) If user data was accessed, follow your incident response protocol and notify users if required by law.
It's not recommended. Use separate API keys for each application or service. This follows the principle of least privilege—if one application is compromised, only that service is affected. Additionally, you can grant each key only the permissions needed for its specific application.
Implement custom logging filters that redact sensitive data. Mask API keys in logs by showing only the first and last few characters (e.g., "sk-****...****"). Use log levels appropriately—never log secrets at debug level. Most modern logging frameworks support redaction filters for this purpose.
Start implementing these best practices today and protect your applications from unauthorized access.