Managing API Keys Securely
API keys belong in environment variables or secret managers โ never in code, repos, or prompts. If one leaks, only one thing matters: revoke immediately.
Why this matters
An API key is like a credit card: whoever has it can send requests on your bill. Public repos are automatically scanned for such keys โ by attackers and by protection systems alike.
Rule 1: never in code, repo, or prompt
Keys do not belong in source code, in the git repo, or in chat prompts. The standard local approach: a .env file holding the key โ plus a .gitignore entry so it is never committed. Anthropic explicitly recommends exactly this pattern.
Rule 2: environment variables and secret managers
Locally, your program reads the key from an environment variable. In production, Anthropic recommends encrypted secret storage (the cloud providers' secret managers) instead of dotenv files.
Rule 3: rotate and restrict
Rotate keys on a regular schedule (Anthropic gives every 90 days as an example), use separate keys for development, testing, and production, and give each key only the minimum rights it needs โ the least-privilege principle from the OWASP guide.
If a key leaks
Revoke and replace immediately. Deleting the commit is not enough: GitHub makes clear that a leaked secret must first be revoked or rotated โ the git history may long since have been cloned or cached.
EXAMPLE
Instead of `apiKey = "sk-ant-..."` in code: put the key in .env (.env is listed in .gitignore), read `process.env.ANTHROPIC_API_KEY` in code โ and use your cloud provider's secret manager in production.
๐ ๏ธ EXERCISE โ TRY IT YOURSELF
Set up the .env pattern in a practice project and verify that no key can end up in the repo.
- Create a .env with a dummy variable (NO real key) and add .env to .gitignore.
- Create a .env.example with the variable names but no values, and commit only that.
- Check with `git status` that .env does not appear as a new file โ and read the value in code via the environment variable.
โ SELF-CHECK
- โ Does .env show up in `git status`? (If yes: check the .gitignore entry)
- โ Is there a key as a plaintext string anywhere in your code or in a prompt?
- โ Do you know where you could revoke your real key immediately (the provider's console/dashboard)?
QUICK QUIZ
Your API key accidentally ended up in a public repo. What is the correct first step?
SOURCES
- Anthropic Help Center: API Key Best Practices โ support.claude.com
- OWASP Cheat Sheet: Secrets Management โ cheatsheetseries.owasp.org
- GitHub Docs: Removing sensitive data from a repository โ docs.github.com