Protecting API keys in AI apps: 7 mistakes that blow up your bill overnight
TL;DR
Never put API keys in the frontend, the repo or screenshots. Keep keys on the server or in a secret manager, call models through your backend, set spend limits, separate keys per environment and rotate them. Key leaked → revoke first, investigate second.
7 common mistakes
| Mistake | Fix |
|---|---|
| Key in frontend / mobile app code | Call through a backend or serverless function |
Committing .env to GitHub | .gitignore + secret scanning / push protection |
| One key for every environment | Separate dev / staging / prod keys with clear names |
| No spend limit | Set limits and alerts in the Console |
| Pasting keys in chats, tickets, screenshots | Use a secret manager, share via a vault |
| Agents can read key files | Deny reading .env with permissions or hooks |
| Never rotating | Rotate regularly and whenever someone leaves |
Block agents from secrets (Claude Code)
// .claude/settings.json
{
"permissions": {
"deny": ["Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
}
}When a key leaks
- Revoke it in the Console immediately.
- Create a new key, update the secret manager.
- Review usage logs to assess damage.
- Purge it from git history (and treat the old key as gone forever).
References: Claude Code permissions · GitHub secret scanning