🤖 AI Tools
· 4 min read

How to Secure Your AI API Keys — A Developer's Guide


A leaked API key can cost you thousands in minutes. Bots scan every public GitHub commit for patterns matching API keys and exploit them within 30 seconds on average. Here’s how to protect yours.

The threat

AI API keys are especially valuable to attackers because:

  • Claude Opus costs $15/M input + $75/M output tokens. A stolen key running batch requests can rack up $1,000+ in hours.
  • OpenAI keys have default spending limits, but many developers raise them.
  • OpenRouter keys access 200+ models. One key, unlimited damage.

Rule 1: Never put keys in code

# WRONG - key in source code
client = Anthropic(api_key="sk-ant-abc123...")

# RIGHT - key from environment
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

This seems obvious, but it’s the #1 cause of key leaks. Even if you “plan to remove it later,” you’ll forget. Git history is forever.

Rule 2: Use .gitignore

# .gitignore
.env
.env.local
.env.production
*.key
*.pem

Add this before your first commit. If you’ve already committed a .env file, the key is in git history even after you delete the file. Rotate the key immediately.

Rule 3: Use a password manager for storage

Don’t store API keys in:

  • ❌ Text files on your desktop
  • ❌ Slack messages
  • ❌ Email drafts
  • ❌ Browser bookmarks
  • ❌ Notion pages (unless encrypted)

Store them in:

  • 1Password — best for developers (SSH agent, op run)
  • NordPass — included with NordVPN Plus plan
  • ✅ Bitwarden — free, self-hostable

1Password developer workflow

# Instead of .env files with plaintext keys:
# Create a template that references 1Password items
cat > .env.tpl << 'EOF'
ANTHROPIC_API_KEY=op://Development/Claude/credential
OPENAI_API_KEY=op://Development/OpenAI/credential
OPENROUTER_API_KEY=op://Development/OpenRouter/credential
DATABASE_URL=op://Development/Postgres/connection-string
EOF

# Run your app with secrets injected at runtime
op run --env-file=.env.tpl -- python main.py

Keys never touch disk. They’re decrypted in memory, used, and discarded.

See our password managers guide for the full comparison.

Rule 4: Set spending limits

Every AI provider lets you set spending limits. Do it immediately after creating a key:

ProviderWhere to set limit
AnthropicConsole > Billing > Usage limits
OpenAISettings > Billing > Usage limits
OpenRouterSettings > Credits (prepaid, can’t overspend)
DeepSeekConsole > Billing > Budget

Set limits at 2x your expected monthly usage. If you normally spend $50/month, set the limit at $100. This caps damage from a leaked key.

Rule 5: Use scoped keys

Create separate API keys for each environment and application:

claude-key-dev-myapp      → Development, $20 limit
claude-key-staging-myapp  → Staging, $50 limit  
claude-key-prod-myapp     → Production, $200 limit

If your dev key leaks, production is unaffected. If one app’s key leaks, other apps keep working.

Rule 6: Rotate keys quarterly

Set a calendar reminder every 3 months:

  1. Generate new key in provider dashboard
  2. Update in password manager
  3. Deploy to staging, verify it works
  4. Deploy to production
  5. Revoke old key

With 1Password op run, rotation is a password manager update — no code changes needed.

Rule 7: Secure CI/CD

Never put keys in CI/CD config files. Use your platform’s secret management:

# GitHub Actions
- name: Deploy
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: python deploy.py
# GitLab CI
variables:
  ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY  # Set in GitLab CI/CD settings

For Railway and Cloudways, set secrets in the dashboard. They’re encrypted at rest and injected at runtime.

Rule 8: Monitor for leaks

GitHub secret scanning

GitHub automatically scans public repos for known API key patterns and alerts you. Enable it in Settings > Code security > Secret scanning.

Google Alerts

Set up a Google Alert for your API key prefix (first 8 characters). If it appears anywhere public, you’ll know.

Provider notifications

Most AI providers email you when unusual usage is detected. Make sure your billing email is monitored.

What to do if a key leaks

  1. Revoke immediately — don’t wait, don’t investigate first. Revoke the key now.
  2. Check usage — review the provider’s usage dashboard for unauthorized requests
  3. Rotate all related keys — if one key leaked, assume others in the same .env file did too
  4. Audit git history — use git log --all -p | grep "sk-ant" to find where it was committed
  5. Add to .gitignore — prevent it from happening again
  6. Set spending limits — if you hadn’t already

Use a VPN on public WiFi

API keys in transit are encrypted via HTTPS, but DNS queries and connection metadata are not. On public WiFi, use a VPN to encrypt all traffic:

  • NordVPN — dedicated IP for consistent access
  • Proton VPN — Swiss privacy for sensitive work
  • Surfshark — unlimited devices for teams

Related: Best Password Managers for Developers · AI Security Checklist · Best VPNs for Developers · MCP Security Checklist · AI App Deployment Checklist