API Key Security: Best Practices for Developers

Why API Key Security Matters
API keys are the most common form of authentication for web APIs. A leaked key can give attackers full access to your services, data, and infrastructure. Yet many developers still hardcode keys in their source code or commit them to public repositories.
Let's fix that.
Generating Strong API Keys
A secure API key should have enough entropy to be practically unguessable. Here are the minimum recommendations:
- At least 256 bits of entropy (32 bytes)
- Use a cryptographically secure random number generator (like
crypto.getRandomValues()) - Avoid predictable patterns — sequential IDs, timestamps, or user-derived values are not API keys
// Good: using Web Crypto API
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
const key = Array.from(bytes)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
You can use the API Key Generator tool to generate keys with the right entropy.
Storing API Keys
Never store API keys in plain text in your codebase. Instead:
- Use environment variables — Store keys in
.envfiles that are.gitignore'd - Use a secrets manager — AWS Secrets Manager, HashiCorp Vault, or similar
- Encrypt at rest — If you must store keys in a database, encrypt them
# .env file (never commit this)
API_KEY=sk_live_a1b2c3d4e5f6g7h8i9j0...
Rotating Keys
API keys should be rotated periodically. A good rotation strategy:
- Support multiple active keys so you can deploy new keys before revoking old ones
- Set expiration dates on keys
- Log key usage so you can detect if a compromised key is being used
- Have a one-click revoke mechanism for emergencies
Common Mistakes
- Committing keys to Git — Use
.gitignoreand tools likegit-secretsto prevent this - Sharing keys in Slack/email — Use a secrets manager or encrypted channels
- Using the same key everywhere — Create separate keys per environment (dev, staging, prod)
- Not setting permissions — Apply least-privilege: each key should only access what it needs
- Ignoring key leaks — If a key is exposed, rotate it immediately, don't wait
Server-Side Validation
Always validate API keys on the server side:
function authMiddleware(req, res, next) {
const auth = req.headers.authorization;
if (!auth || !auth.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing token' });
}
const token = auth.split(' ')[1];
// Use timing-safe comparison to prevent timing attacks
const valid = crypto.timingSafeEqual(
Buffer.from(token),
Buffer.from(process.env.API_SECRET)
);
if (!valid) {
return res.status(403).json({ error: 'Invalid token' });
}
next();
}
Key Takeaways
- Generate keys with at least 256 bits of entropy
- Never hardcode keys in source code
- Store keys in environment variables or a secrets manager
- Rotate keys regularly and support multiple active keys
- Use timing-safe comparison on the server side
- Monitor and log key usage for anomalies
Use our API Key Generator and JWT Secret Generator to create production-ready keys and secrets.