Storing API Keys for AI Apps Securely
An API key unlocks models and balance. Treat it as a credential with financial risk: the secret lives server-side, never in browsers or repos — anything client-side is extracted in minutes.
Short answer
A key is money: server-side only, never in browsers or repos. One key per environment with a spend limit from day one.
Where keys live
Server environment variables or a secret manager — never client JavaScript, mobile bundles, query strings or git history. Browser calls go to your backend route, which adds the key and calls the API. Check CI artifacts, docker history and HTTP-client exception texts too: secrets leak there most often.
Name keys by purpose and date, keep environments split from day one: prod, test, bot, experiments. Quarterly review of dangling keys: ex-contractor keys are the classic silent hole.
- server env or secret manager only
- browser goes via your backend route
- names by purpose and date
- quarterly dangling-key review
Limits and rotation
A spend limit per key is the emergency brake: exhausted means failed requests, not an empty balance. Rotate on personnel changes: issue new, verify, revoke old. Keep the old key briefly for rollback, then revoke.
On suspected leak revoke and reissue immediately — a found bot key is spent within hours since bots are searchable. Then find the leak path before issuing the replacement, or history repeats.
- spend limit per key before traffic
- rotate on changes: new, verify, revoke
- suspected leak — revoke first
- find the path before reissuing
What to log
Log statuses and request IDs, never keys or contents. Masking catches the obvious and misses scans and screenshots — attachments go by metadata (name/size/hash) only. Full keys must not appear even partially: prefixes help restore them too.
Separate prod, test and experiment spending by key: with split keys the bill explains itself, and incidents stay contained to one direction.
- statuses and IDs, never keys or contents
- attachments by metadata only
- split spending by key
Sources and related pages
Next step
Russian version: все статьи на русском.