How to Secure API Keys: Complete Guide for Developers
Learn the best practices for securing API keys in Node.js, Python, and Go. Prevent API key leaks and protect your production infrastructure.
How to Secure API Keys: Complete Guide for Developers
To secure API keys, never commit them to version control, store them in environment variables or a secrets manager like XtraSecurity, rotate them every 30 days, restrict permissions to the minimum required, and monitor all usage with audit logs. Here is the complete guide for Node.js, Python, and Go developers.
The Problem with Unsecured API Keys
Every day, hackers scan GitHub for exposed API keys. When they find one, they can:
- Access your cloud infrastructure
- Make unauthorized API calls
- Drain your database
- Access customer data
This costs companies thousands in minutes.
Best Practices for Securing API Keys
1. Never Commit API Keys to Git
The first rule: never commit secrets to your repository.
✅ Bad Example:
const apiKey = "sk-12345678901234567890"; // 🚨 DO NOT DO THIS
✅ Good Example:
const apiKey = process.env.API_KEY;
2. Use Environment Variables
Store secrets in environment variables that are loaded at runtime:
# .env.local (add to .gitignore)
API_KEY=sk_prod_123456789
DATABASE_PASSWORD=secret_password_here
STRIPE_KEY=sk_live_abc123
3. Use a Secrets Manager
For production, use a dedicated secrets manager like XtraSecurity, AWS Secrets Manager, or HashiCorp Vault:
// With XtraSecurity
const xtra = require('@xtrasecurity/sdk');
const apiKey = await xtra.getSecret('api-key-prod');
4. Rotate Keys Regularly
Never use the same API key forever. Rotate keys every:
- 30 days for production
- 7 days for high-risk services
5. Restrict Key Permissions
Create API keys with minimal permissions:
- Only read access if write isn't needed
- Restrict to specific IP addresses
- Set expiration dates
6. Monitor Key Usage
Log all API key access and alert on unusual patterns.
How to Implement in Your Stack
Node.js with dotenv
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_API_KEY);
Python
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('API_KEY')
Go
package main
import (
"os"
)
func main() {
apiKey := os.Getenv("API_KEY")
}
What to Do If You've Exposed a Key
- Immediately revoke the exposed key
- Generate a new key
- Update all services using the old key
- Check logs for unauthorized access
- If in public repository, contact the service provider
Conclusion
Securing API keys isn't optional—it's critical infrastructure security.
About the Author
OM Salunke — Full-stack developer and founder of XtraSecurity. Building secure infrastructure tools for modern engineering teams.