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:

# .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

  1. 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.
  2. 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.
  3. Use descriptive key names. Label keys with their purpose (e.g., "prod-backend-main", "dev-john-local") for easy identification during audits.
  4. Set expiration dates. Where supported, create keys that automatically expire and must be renewed.
Relay services like claude4u.com let you create multiple API keys with individual permissions and usage limits. This means each developer on your team gets their own key with a spending cap, and you can revoke any single key without affecting others.

Secure Storage in Production

In production environments, environment variables alone are not sufficient. Use a dedicated secrets manager:

// 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:

  1. Rotate keys on a schedule. Monthly rotation for production keys, quarterly for development.
  2. Support overlapping validity. When rotating, keep the old key valid for a transition period while the new key is deployed.
  3. Automate rotation. Manual rotation processes are error-prone and often skipped. Use your secrets manager's rotation features.
  4. 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
If you discover that an API key has been committed to a Git repository — even if you immediately delete it in a subsequent commit — the key is compromised. Git history preserves it. Rotate the key immediately and consider using tools like BFG Repo-Cleaner to purge the key from history.

Monitoring and Alerting

Proactive monitoring catches compromised keys before the damage escalates:

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

  1. Document your key management procedures and train all developers
  2. Conduct quarterly audits of active API keys — remove unused ones
  3. Implement least-privilege access — give each key only the permissions it needs
  4. Maintain an inventory of all active keys, their owners, and their purposes
  5. 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