API Key Management Best Practices
API Key Management Best Practices
API keys are the keys to your kingdom — literally. A single leaked API key can result in thousands of dollars in unauthorized charges, data breaches, and service disruption. Yet despite the risks, API key mismanagement remains one of the most common security failures in software development. This guide covers comprehensive best practices for generating, storing, distributing, rotating, and monitoring API keys across your organization.
The Fundamentals
Never Hardcode API Keys
This is the most basic rule and the most frequently violated. API keys must never appear in source code, configuration files committed to version control, or client-side applications.
// NEVER do this
const apiKey = 'sk-ant-api03-abc123xyz789';
// Use environment variables instead
const apiKey = process.env.AI_API_KEY;
// Or use a secrets manager
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient();
const [version] = await client.accessSecretVersion({
name: 'projects/my-project/secrets/ai-api-key/versions/latest'
});
const apiKey = version.payload.data.toString();
Use Environment Variables Properly
Environment variables are the minimum acceptable approach for local development. Follow these rules:
- Store keys in a
.envfile that is listed in.gitignore - Provide a
.env.examplefile with placeholder values for documentation - Load environment variables using a library like
dotenvin development - Never echo or log environment variables in your application startup
# .env (never committed)
AI_API_KEY=sk-ant-api03-real-key-here
OPENAI_API_KEY=sk-real-openai-key
# .env.example (committed to repo)
AI_API_KEY=your-api-key-here
OPENAI_API_KEY=your-openai-key-here
Key Generation Best Practices
- Use unique keys per environment. Development, staging, and production should each have their own API keys. This limits the blast radius if any key is compromised.
- Use unique keys per service or team member. When using a relay service, create individual keys for each developer and each microservice so you can track usage and revoke access granularly.
- Use descriptive key names. Label keys with their purpose (e.g., "prod-backend-main", "dev-john-local") for easy identification during audits.
- Set expiration dates. Where supported, create keys that automatically expire and must be renewed.
Secure Storage in Production
In production environments, environment variables alone are not sufficient. Use a dedicated secrets manager:
- AWS Secrets Manager — Integrates with IAM roles, automatic rotation support
- Google Cloud Secret Manager — Versioned secrets with fine-grained access control
- Azure Key Vault — HSM-backed key storage with RBAC
- HashiCorp Vault — Self-hosted, supports dynamic secrets and lease management
- Doppler / Infisical — Modern SaaS options with team management features
// AWS Secrets Manager example
const { SecretsManager } = require('@aws-sdk/client-secrets-manager');
const client = new SecretsManager({ region: 'us-east-1' });
async function getApiKey() {
const response = await client.getSecretValue({
SecretId: 'ai-api/production-key'
});
return JSON.parse(response.SecretString).apiKey;
}
Key Rotation
Regular key rotation limits the window of exposure if a key is compromised. Implement these practices:
- Rotate keys on a schedule. Monthly rotation for production keys, quarterly for development.
- Support overlapping validity. When rotating, keep the old key valid for a transition period while the new key is deployed.
- Automate rotation. Manual rotation processes are error-prone and often skipped. Use your secrets manager's rotation features.
- Rotate immediately on personnel changes. When a team member leaves, rotate all keys they had access to.
Pre-Commit Hooks for Secret Detection
Prevent accidental key commits with automated scanning:
# Install gitleaks for pre-commit secret detection
brew install gitleaks
# Add to .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
Monitoring and Alerting
Proactive monitoring catches compromised keys before the damage escalates:
- Usage anomalies: Alert on sudden spikes in API usage, unusual models being called, or requests from unexpected IP addresses
- Billing alerts: Set up spending alerts at 50%, 80%, and 100% of your expected budget
- Geographic anomalies: Flag requests originating from unusual locations
- Failed authentication: Monitor and alert on repeated authentication failures, which may indicate a brute-force attempt
Client-Side Applications
Never embed API keys in client-side code — browser JavaScript, mobile apps, or desktop applications. These can always be extracted by users.
Instead, proxy all AI API requests through your backend:
// Frontend — calls YOUR backend, no API key exposed
const response = await fetch('/api/ai/chat', {
method: 'POST',
headers: { 'Authorization': `Bearer ${userSessionToken}` },
body: JSON.stringify({ message: userInput })
});
// Backend — uses API key securely
app.post('/api/ai/chat', authenticate, async (req, res) => {
const aiResponse = await openai.chat.completions.create({
model: 'claude-sonnet-4-20250514',
messages: [{ role: 'user', content: req.body.message }]
});
res.json(aiResponse);
});
Organizational Policies
- Document your key management procedures and train all developers
- Conduct quarterly audits of active API keys — remove unused ones
- Implement least-privilege access — give each key only the permissions it needs
- Maintain an inventory of all active keys, their owners, and their purposes
- Have an incident response plan for key compromises
API key management is not glamorous work, but it is essential. A few hours invested in proper key management practices can save your organization from costly security incidents. Whether you manage keys yourself or leverage the key management features of a relay service like claude4u.com, the principles remain the same: minimize exposure, automate rotation, monitor continuously, and always assume breach is possible.
Get Started with 轻舟 AI
Stable, fast AI API relay — supports Claude, OpenAI, Gemini and more
Sign Up Free
轻舟 AI