An API key is a credential — anyone who has it can spend your money and access your account. Yet keys are routinely committed to repositories, pasted into chat tools, and shared across projects. A few simple habits prevent almost all of the damage.
Never Hardcode Keys
The most common leak is a key committed to source control. Keep keys in environment variables or a secrets manager, never in your code. Add your env files to .gitignore from day one, and scan your history if you suspect a key was ever committed.
Use Separate Keys for Separate Purposes
One key for everything means one leak compromises everything. Instead, create distinct keys per environment and per service:
- A development key for local work
- A separate key for staging
- Dedicated keys for each production service
If one leaks, you revoke just that key without taking down everything else.
Set Spending Limits
Treat every key as if it could be exposed tomorrow. Per-key spending limits cap the blast radius: even if a key leaks, the damage is bounded. Set limits that match each key's expected workload, not your total budget.
Rotate Regularly
Rotate keys on a schedule and immediately whenever someone with access leaves or a leak is suspected. Rotation is painless when keys are stored centrally and referenced by name rather than copied around.
Restrict Access on the Client Side
Never put a raw API key in frontend code, mobile apps, or anything a user can inspect. Route requests through your own backend so the key stays server-side, and apply your own auth and rate limits in front of it.
Monitor Usage
Watch for unusual spikes, requests from unexpected locations, or models you do not normally use. A clear usage view per key turns a slow, expensive leak into something you catch within hours instead of at the end of the month.
A Simple Checklist
- Keys in environment variables or a secrets manager, never in code
- Separate keys per environment and service
- Spending limits on every key
- Scheduled rotation and instant revocation when needed
- No keys in client-side code
- Active usage monitoring and alerts
Good key hygiene is mostly about defaults. Set these up once, and the most common — and most expensive — mistakes simply stop happening.
