API Key Security: 10 Best Practices Every Developer Should Follow
Learn how to secure your API keys, detect compromised credentials, and implement proper key rotation strategies for your SaaS application.

API keys are the backbone of modern application security. They authenticate requests, authorize access, and track usage. But when mishandled, they become your biggest vulnerability.
The Cost of Leaked API Keys
In 2025 alone, over 6 million API keys were exposed in public GitHub repositories. The consequences ranged from unauthorized data access to complete infrastructure takeovers costing companies millions.
Here's what we've seen at LiteSOC:
- Average time from key leak to exploitation: 12 minutes
- Average cost of a compromised API key: $47,000
- Percentage of incidents caused by hardcoded keys: 68%
10 Best Practices for API Key Security
1. Never Hardcode Keys in Source Code
This seems obvious, but it's still the #1 cause of key leaks.
// ❌ Never do this
const API_KEY = "lsoc_live_a1b2c3d4e5f6";
// ✅ Use environment variables
const API_KEY = process.env.LITESOC_API_KEY;
2. Use Different Keys for Each Environment
Maintain separate keys for development, staging, and production:
lsoc_test_*for development/testinglsoc_live_*for production only
If a test key leaks, your production data remains safe.
3. Implement Key Rotation
Rotate your API keys regularly, even if you don't suspect a breach:
| Environment | Rotation Frequency |
|---|---|
| Production | Every 90 days |
| Staging | Every 30 days |
| Development | On developer offboarding |
4. Use Short-Lived Tokens When Possible
For client-side applications, use short-lived tokens instead of long-lived API keys:
// Request a short-lived token (expires in 1 hour)
const { token, expiresAt } = await litesoc.createSessionToken({
permissions: ["events:write"],
expiresIn: "1h",
});
5. Restrict Key Permissions
Apply the principle of least privilege. If a key only needs to write events, don't give it admin access:
// Create a key with limited scope
const key = await litesoc.createApiKey({
name: "Event Ingestion Only",
permissions: ["events:write"],
// No admin, read, or delete permissions
});
6. Allowlist IP Addresses
Restrict where your API keys can be used from:
- Production servers only
- Specific CIDR ranges
- Reject requests from unknown IPs
7. Monitor Key Usage Patterns
Set up alerts for anomalous behavior:
- Sudden spike in API calls
- Requests from new geographic locations
- Usage outside business hours
- Failed authentication attempts
LiteSOC automatically tracks all of these and alerts you in real-time.
8. Use Git Pre-Commit Hooks
Prevent accidental commits of API keys:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
9. Encrypt Keys at Rest
Store API keys encrypted in your database:
// Use AES-256 encryption for stored keys
const encryptedKey = await encrypt(apiKey, process.env.ENCRYPTION_KEY);
await db.apiKeys.create({
hash: sha256(apiKey), // For lookup
encrypted: encryptedKey // For recovery
});
10. Have an Incident Response Plan
Know what to do when a key is compromised:
- Revoke immediately - Don't wait to investigate
- Generate new key - Update all services
- Review audit logs - Understand the blast radius
- Notify affected users - If customer data was accessed
- Post-mortem - Prevent future leaks
How LiteSOC Helps
LiteSOC monitors your API key usage and detects:
- Credential stuffing - Multiple failed auth attempts
- Anomalous usage - Unusual request patterns
- Geographic anomalies - Requests from unexpected locations
- Privilege escalation - Attempts to access unauthorized resources
When we detect suspicious activity, you get an alert within seconds—not days.
Conclusion
API key security isn't just about preventing leaks. It's about building a defense-in-depth strategy that assumes keys will eventually be compromised.
By following these best practices and implementing proper monitoring with tools like LiteSOC, you can detect and respond to threats before they become breaches.
Ready to secure your API keys? Start your free trial and get real-time alerts for credential compromises.
Stay Updated
Get the latest security insights and product updates delivered to your inbox. No spam, unsubscribe anytime.