Leaked API keys are one of the most common, and most expensive, security mistakes in software. Automated scanners watch public repositories continuously, and a cloud or AI key pushed to a public repo can be abused within minutes, running up large bills or exposing data.
Where keys leak
- Committed to Git (including in old commits, after you "deleted" them)
- Shipped in front-end JavaScript or mobile app bundles
- Pasted into tickets, chat, screenshots and screen recordings
- Printed in logs and error trackers
- Left in public Postman collections, notebooks or Docker images
Ten rules
- Never put secret keys in client-side code. Anything shipped to a browser or app can be extracted. Call the API from a backend or serverless function instead.
- Use environment variables or a secrets manager (for example Cloudflare secrets, AWS Secrets Manager, Doppler or 1Password), never hard-coded strings.
- Add secret scanning. Enable push protection on your Git host and run a pre-commit scanner such as gitleaks.
- Scope every key to the minimum permissions, resources and environments it needs. Use read-only keys where possible.
- Separate keys per environment (dev, staging, production) and per service, so a leak is contained and easy to trace.
- Restrict usage by IP, referrer, app bundle ID or allowed APIs when the provider supports it.
- Set budgets and alerts on usage and spend. A billing alert is often the first sign of a leak.
- Rotate regularly, and immediately after anyone with access leaves or a laptop is lost.
- Redact logs. Mask headers such as
AuthorizationandX-Api-Keybefore logging. - Have a leak runbook: revoke the key, issue a new one, deploy, review usage logs for abuse, and purge the secret from Git history.
Publishable vs secret keys
Some services issue two kinds of key. Publishable keys are designed to appear in front-end code and can only do safe things (for example create a payment form). Secret keys can do anything and must stay on the server. Read the docs carefully, because only the provider decides which is which.
Prefer short-lived credentials
Where possible, swap long-lived static keys for OAuth tokens or short-lived credentials issued per session or workload. They expire on their own, which limits the damage from any leak. For user-facing apps, a JWT from your own auth system plus a backend proxy is the standard pattern. Inspect tokens with our JWT Decoder.