Protect Your API Keys

Learn how to safely store, rotate, and manage your API keys to prevent unauthorized access and data breaches.

Why API Key Security Matters

🚨 Prevent Unauthorized Access

A compromised API key can grant attackers full access to your services, data, and user information.

💰 Avoid Financial Loss

Malicious actors can use your key for malicious activities, resulting in unexpected charges and service abuse.

🛡️ Protect User Trust

A breach compromises user data and damages your reputation. Secure key management is essential for compliance.

Best Practices for API Key Storage

1

Never Commit Keys to Version Control

Always use environment variables or secret management tools. Add .env files to .gitignore to prevent accidental commits of sensitive data.

2

Use Environment Variables

Store API keys in environment variables on your server or application runtime. Tools like dotenv help manage these securely.

3

Implement Key Rotation

Regularly rotate your API keys every 30-90 days. This limits the window of exposure if a key is compromised.

4

Use Secret Management Services

Leverage services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault for enterprise-grade encryption and access control.

5

Restrict Key Permissions

Create API keys with minimal required permissions (principle of least privilege). Different keys for different services reduces risk.

6

Monitor Key Usage

Set up alerts for unusual API activity. Log all key usage and review periodically for suspicious patterns.

Implementation Examples

.env file
API_KEY=sk-YOUR_KEY_HERE DATABASE_URL=postgresql://user:pass@host/db DEBUG=false LOG_LEVEL=info

⚠️ Important: Add .env to your .gitignore file to prevent committing secrets.

Node.js / Express
require('dotenv').config(); const apiKey = process.env.API_KEY; if (!apiKey) { throw new Error('API_KEY not defined in environment'); } app.get('/api/endpoint', (req, res) => { // Use apiKey from memory, never hardcode callExternalAPI(apiKey) .then(data => res.json(data)) .catch(err => res.status(500).json({error: err.message})); });

Install: npm install dotenv

Python / Flask
import os from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv('API_KEY') if not API_KEY: raise ValueError('API_KEY not defined in environment') @app.route('/api/endpoint') def endpoint(): # Use API_KEY from environment response = requests.get( 'https://api.service.com/data', headers={'Authorization': f'Bearer {API_KEY}'} ) return response.json()

Install: pip install python-dotenv requests

Docker / Secrets
# Use Docker secrets for production # docker secret create api_key - docker run -d \ --name myapp \ --secret api_key \ -e API_KEY_FILE=/run/secrets/api_key \ myapp:latest # Inside container, read secret: API_KEY=$(cat /run/secrets/api_key)

Note: Docker secrets are encrypted and injected at runtime, never exposed in images.

Do's and Don'ts

✓ Do This

  • Use environment variables for all secrets
  • Rotate keys regularly (30-90 days)
  • Implement key expiration dates
  • Use separate keys for dev and production
  • Enable API key logging and monitoring
  • Use HTTPS for all API communications
  • Audit access logs regularly

✗ Don't Do This

  • Hardcode API keys in source code
  • Share keys via email or chat
  • Use the same key for multiple services
  • Commit .env files to version control
  • Display full keys in logs or error messages
  • Store keys in plain text files
  • Ignore suspicious API activity

Secret Management Tools & Services

HashiCorp Vault

Enterprise secret management with encryption, audit logging, and fine-grained access control.

Self-Hosted Enterprise

AWS Secrets Manager

AWS service for storing, encrypting, and rotating secrets with automatic lifecycle management.

Cloud AWS

Azure Key Vault

Microsoft's cloud solution for managing cryptographic keys and secrets with compliance certifications.

Cloud Azure

1Password Secrets

Developer-friendly secrets management with team collaboration and zero-knowledge encryption.

Cloud Managed

Doppler

Secrets management platform designed for development teams with real-time secret syncing.

Cloud Developer

python-dotenv

Lightweight Python library for loading environment variables from .env files during development.

Local Python

Frequently Asked Questions

An API key is a token used for programmatic access to services, while a password is for human authentication. API keys are typically longer, don't expire automatically, and grant access to specific resources. Passwords are shorter and intended for human-readable authentication. Both should be protected equally.

Industry best practice recommends rotating API keys every 30-90 days. However, you should rotate immediately if you suspect compromise. For critical infrastructure, consider more frequent rotation. Some organizations use automated key rotation every 30 days as a security baseline.

Yes, environment variables are safe for production when properly configured. They're loaded at runtime and not stored in code. However, for maximum security in enterprise environments, use dedicated secret management services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault which provide encryption, audit logging, and access controls.

Act immediately: 1) Revoke the exposed key immediately, 2) Review logs for unauthorized access, 3) Generate a new key, 4) Update all systems using the old key, 5) Monitor for suspicious activity, 6) If user data was accessed, follow your incident response protocol and notify users if required by law.

It's not recommended. Use separate API keys for each application or service. This follows the principle of least privilege—if one application is compromised, only that service is affected. Additionally, you can grant each key only the permissions needed for its specific application.

Implement custom logging filters that redact sensitive data. Mask API keys in logs by showing only the first and last few characters (e.g., "sk-****...****"). Use log levels appropriately—never log secrets at debug level. Most modern logging frameworks support redaction filters for this purpose.

Ready to Secure Your API Keys?

Start implementing these best practices today and protect your applications from unauthorized access.