API keys are the most common form of API authentication, and they are also the most commonly leaked. A quick search on GitHub reveals thousands of exposed API keys — in committed configuration files, README examples, and frontend JavaScript bundles. Each one is a potential security incident waiting to happen.

This guide covers how to store, scope, rotate, and protect API keys properly. Whether you are building an API that issues keys or an application that consumes them, these practices keep your systems secure.

Why API Keys Get Leaked

Understanding how keys end up exposed helps you prevent it:

  • Committed to version control: The most common leak. A developer hard-codes a key during development and pushes it to a public or shared repository.
  • Client-side code: Keys embedded in JavaScript, mobile apps, or desktop applications are visible to anyone who inspects the code.
  • Log files: Keys included in URLs (query parameters) end up in server logs, proxy logs, and browser history.
  • Shared in plaintext: Keys sent via Slack, email, or shared documents persist in those systems indefinitely.
  • Screenshots and recordings: Keys visible in terminal sessions, IDE screenshots, or demo recordings.
  • Docker images: Keys baked into Docker layers are extractable even if deleted in later layers.

Secure Storage

Environment Variables

For most applications, environment variables are the standard approach:

# .env file (never committed)
STRIPE_API_KEY=sk_live_abc123
DATABASE_URL=postgres://user:pass@host:5432/db
SENDGRID_API_KEY=SG.xyz789
// Access in your application
const stripe = require('stripe')(process.env.STRIPE_API_KEY);

Use the .env file generator to scaffold a .env and .env.example pair. Put the real values only in .env, and commit the example file with placeholders.

Critical rules for environment variables:

  1. Add .env to .gitignore before creating the file. Always.
  2. Provide a .env.example with placeholder values so other developers know which variables are needed.
  3. Never log environment variables. Sanitize your logging to exclude secrets.
  4. Do not pass secrets in command-line arguments. They appear in process listings (ps aux).
# .env.example (committed to repo)
STRIPE_API_KEY=sk_test_your_key_here
DATABASE_URL=postgres://localhost:5432/myapp_dev
SENDGRID_API_KEY=your_key_here

Secrets Managers

For production systems, dedicated secrets managers provide better security than environment variables:

Service Best For
AWS Secrets Manager AWS-hosted applications
Google Secret Manager GCP applications
Azure Key Vault Azure applications
HashiCorp Vault Multi-cloud and on-premise
Doppler Cross-platform, developer-friendly

Secrets managers offer advantages over plain environment variables:

  • Access control: Fine-grained permissions on who and what can read each secret
  • Audit logging: Every access is recorded
  • Automatic rotation: Some support rotating secrets on a schedule
  • Encryption at rest: Secrets are encrypted, not stored as plaintext files
  • Versioning: Previous values are retained for rollback
# AWS Secrets Manager example
import boto3
import json

client = boto3.client('secretsmanager')
response = client.get_secret_value(SecretId='prod/api-keys')
secrets = json.loads(response['SecretString'])
stripe_key = secrets['stripe_api_key']

Platform-Specific Storage

  • CI/CD pipelines: Use GitHub Actions secrets, GitLab CI/CD variables, or your platform’s secrets feature
  • Kubernetes: Use Kubernetes Secrets (preferably with an external secrets operator)
  • Mobile apps: Use platform keystores (iOS Keychain, Android Keystore) — never embed keys in the app bundle

Key Scoping

An API key with full admin access is a bigger risk than one scoped to read-only access on a single resource. Scoping limits the damage from a leaked key.

Permission Scoping

Design your API keys with the minimum necessary permissions:

{
  "key": "pk_proj_abc123",
  "permissions": ["read:projects", "read:issues"],
  "restrictions": {
    "ip_allowlist": ["203.0.113.0/24"],
    "referer_allowlist": ["https://myapp.com/*"]
  }
}

Good scoping practices:

  • Separate keys for different services: Your email service key should not have access to your payment system
  • Read vs write separation: If a service only reads data, its key should not have write access
  • Environment separation: Never use production keys in development or testing
  • Per-application keys: Each application or integration gets its own key

IP and Referrer Restrictions

Many API providers let you restrict keys to specific IP addresses or HTTP referrers:

  • Server-side keys: Restrict to your server’s IP addresses
  • Browser keys: Restrict to your domain’s referrer
  • Mobile keys: Use additional attestation mechanisms

Key Rotation

Keys should be rotated regularly and immediately if a compromise is suspected. Design your systems to make rotation painless.

Rotation Strategy

  1. Generate a new key without invalidating the old one
  2. Update all services to use the new key
  3. Verify that everything works with the new key
  4. Revoke the old key after a grace period
# Support multiple active keys for zero-downtime rotation
VALID_API_KEYS = {
    os.environ['API_KEY_CURRENT'],
    os.environ.get('API_KEY_PREVIOUS', ''),  # Grace period
}

def authenticate(request):
    key = request.headers.get('X-API-Key')
    if key not in VALID_API_KEYS:
        return unauthorized()

Rotation Schedule

Key Type Recommended Rotation
Production API keys Every 90 days
Database credentials Every 90 days
Service account keys Every 90 days
CI/CD tokens Every 30-90 days
Personal access tokens Every 30 days
Compromised keys Immediately

Automate rotation wherever possible. Manual rotation is easily forgotten.

Rate Limiting and Monitoring

Even with perfect key management, you need defenses against misuse.

Rate Limiting

Implement rate limits per API key:

const rateLimit = require('express-rate-limit');
const keyLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100,                  // limit each key to 100 requests per window
  keyGenerator: (req) => req.headers['x-api-key'],
  message: { error: 'Rate limit exceeded. Try again later.' }
});

app.use('/api/', keyLimiter);

Different tiers of access can have different limits:

Tier Rate Limit Use Case
Free 100 requests/hour Evaluation, hobby projects
Basic 1,000 requests/hour Small applications
Pro 10,000 requests/hour Production applications
Enterprise Custom High-volume integrations

Monitoring and Alerting

Set up alerts for unusual API key activity:

  • Sudden spike in request volume
  • Requests from unexpected IP addresses or regions
  • High error rates from a single key
  • Requests outside normal business hours
  • Access to sensitive endpoints from keys that normally access benign ones
# Log API key usage for monitoring
import logging

logger = logging.getLogger('api_access')

def log_api_access(key_id, endpoint, status_code, ip_address):
    logger.info(
        "API access",
        extra={
            'key_id': key_id[:8] + '...',  # Never log full keys
            'endpoint': endpoint,
            'status': status_code,
            'ip': ip_address,
        }
    )

Generating Strong Keys

API keys should be cryptographically random and long enough to resist brute force:

import secrets

# Generate a 32-byte (256-bit) random key, URL-safe base64 encoded
api_key = secrets.token_urlsafe(32)
# Example: "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"

Good API key properties:

  • At least 32 bytes of entropy: Makes brute force infeasible
  • URL-safe characters: Avoids encoding issues when keys are passed in headers or URLs
  • Prefixed by type: sk_live_, pk_test_, api_ — helps identify the key’s purpose and environment
  • Not derived from predictable data: Never use hashes of usernames, timestamps, or sequential IDs

For generating strong random strings for development and testing, our password generator creates cryptographically random values. You can also use the hash generator to understand the hashing algorithms often used in key validation.

Pre-Commit Protection

Prevent accidental commits of secrets by using tools that scan for them:

git-secrets

# Install
brew install git-secrets

# Add patterns
git secrets --add 'sk_live_[a-zA-Z0-9]+'
git secrets --add 'AKIA[0-9A-Z]{16}'

# Install hooks
git secrets --install

gitleaks

# Scan a repository
gitleaks detect --source .

# Install as pre-commit hook
# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.0
    hooks:
      - id: gitleaks

GitHub Secret Scanning

GitHub automatically scans public repositories for known secret patterns and alerts the repository owner. Many API providers participate in the secret scanning partner program and automatically revoke leaked keys.

What to Do When a Key Is Leaked

  1. Revoke the key immediately. Do not wait. Generate a new one and update your services.
  2. Audit usage. Check the API provider’s logs for unauthorized activity during the exposure window.
  3. Assess impact. Determine what data or actions the key had access to.
  4. Rotate related credentials. If the leaked key could access other secrets, rotate those too.
  5. Remove from history. Use git filter-branch or BFG Repo-Cleaner to remove the key from git history. Note: anyone who has cloned the repo may still have it.
  6. Post-mortem. Understand how the leak happened and implement controls to prevent recurrence.

Summary

API key security comes down to layered defense: store keys in environment variables or secrets managers, scope them to minimum permissions, rotate them regularly, monitor for misuse, and prevent accidental commits. No single practice is sufficient on its own, but together they make key compromises unlikely and limit the damage when they happen. Treat every API key as a credential that grants access to your systems, because that is exactly what it is.