API keys and secrets are the passwords your app uses to talk to everyone else: the database, the email provider, the payment processor, the AI model. Store them where only the server process can read them, and treat any copy that reached a browser, a chat log, or a git commit as already exposed. Builders without a security team leak keys in ordinary ways. A .env file gets committed. A framework prefix sends the value to the client. A screenshot of the dashboard ends up in the README. The fix is a storage rule you follow every time, plus a rotation habit for the day the rule slips.
This guide shows the split between frontend and backend, how environment variables should work, how to search git history, and how to rotate with a short deploy. Pair it with the security checklist before launch so a key in the client bundle blocks launch until you move it and rotate it.
Where an API key is allowed to live
An API key belongs in a secret store the server reads at runtime: the host environment, a managed secret manager, or a CI variable marked secret. Source code, browser bundles, public images, and chat transcripts are the wrong places. If a stranger who can load your site can also load the key, treat that copy as public.
The OWASP Secrets Management Cheat Sheet describes the same boundary. For a small app, use the table below.
| Location | Acceptable for a server secret? | What to do instead |
|---|---|---|
| Host environment or secret manager | Yes | Reference the name in code, inject the value at deploy |
| CI secret used only on the runner | Yes, for build and deploy tasks | Scope it to the environment that needs it |
.env committed to git |
No | Keep .env gitignored, commit .env.example with blank values |
NEXT_PUBLIC_, VITE_, or other client prefixes |
No | Call your server, let the server hold the key |
| Hardcoded string in a source file | No | Move to the environment and rotate |
| Chat transcript or ticket | No | Rotate, then share a name, not the value |
| Frontend bundle or mobile binary | No | Those clients are in the user's hands |
A publishable key is a different object. Some providers issue a client key that is meant to be public and is restricted by domain, bundle id, or allowed APIs. Read the provider's docs before you ship it. A secret key and a publishable key in the same .env file get mixed up constantly. Name them so the next edit is obvious: STRIPE_SECRET_KEY on the server, STRIPE_PUBLISHABLE_KEY in the client, and never the reverse.
Keep secrets out of the places builders actually leak them
Most leaks happen during ordinary work: a commit, a client bundle, a pasted token, a Docker layer. Close those doors before you worry about a targeted break-in. The checks below match the places indie apps actually lose a key.
Frontend versus backend
The browser is a hostile place to keep a secret. Anyone can open devtools, read the bundle, and replay the request. If the email API is called from a click handler, move that call to a route on your server. The button talks to you. You talk to the provider. The same rule covers serverless functions and background workers: they count as backend. A React component does not.
Mobile apps are the same story. A key compiled into the binary can be extracted. Put privileged calls behind your API and authenticate the user, which is the model in how to protect API endpoints.
Environment files and git
Commit .env.example with the variable names and empty values. Add .env, .env.local, and provider credential files to .gitignore before the first commit. Paste production values into the host dashboard, and keep a separate set for local development. A live key in a laptop .env that later gets committed is a leak.
Before you push, run git status and look at the diff. A 40-character token in a green line is the moment to stop. Search the tree on a schedule:
git log -p --all -S 'sk_live' -- .
git grep -n -E 'AKIA[0-9A-Z]{16}|BEGIN PRIVATE KEY|sk_live|ghp_'
Adapt the patterns to the providers you use. History search matters because deleting the file in a new commit leaves the blob reachable. If the repository was public, even for an afternoon, assume the key was copied.
Coding agents and logs
Pasting a live key into a chat so the agent "can test the call" puts the secret in a transcript you do not fully control. Give the agent the variable name and a local .env that stays on your machine. Scrub keys from application logs, error trackers, and analytics. A stack trace that prints process.env is a dump of the secret store. Log the variable name and whether it was present, not the value.
Images, forks, and build output
A Docker image built with ENV STRIPE_SECRET_KEY=... carries the value in a layer. Pass secrets at runtime. A fork of a public repo inherits commits, so a key pushed once is in every fork that copied that history. Inspect one production bundle and search for your key prefix after each deploy that touches environment configuration.
Scan, then rotate, in that order
Revoke a leaked key before you clean the git history. A search you never run is how the value sits in an old commit while the dashboard still looks calm. Work the list below in order, and stop to rotate as soon as a live value appears.
- Inventory every secret: database URL, auth provider, payments, email, SMS, AI provider, object storage, webhook signing secrets.
- Mark each one server-only or intentionally public. Move anything misplaced.
- Search the working tree, the git history, the CI logs, and one production bundle.
- Turn on the host's secret scanning if you have it. GitHub secret scanning and similar tools catch known prefixes on push. They do not replace a search of old history.
- If you find a live value anywhere public, revoke it in the provider before you clean the repo.
- Issue a new key, put it in the secret store, and redeploy.
- Confirm the app works, then delete the old key so a stray copy cannot keep calling.
- Rotate first. Rewrite git history only when you understand the cost of a force-push, and remember that forks may still hold the old commits.
If the database password leaked, rotate it and check connection logs for unfamiliar clients. If a cloud key leaked, review recent resources for anything you did not create. Those steps overlap with what to do if your app gets hacked. Treat every new scaffold as untrusted until you have read the env example and the client code. Sample files and generated components are a common place for a working key to hide.
A key that survived in the bundle
A founder moved billing server-side, deleted the secret from the component, and deployed. Payments worked. A week later a stranger created charges because the old JavaScript file was still cached on the CDN, and the key had not been rotated. The source tree was clean. The secret was not.
The durable sequence is rotate, deploy the server-only call, purge the old assets, and watch the provider's log for use of the retired key. Deleting the line from source leaves the cached bundle and the old credential working. Rotate again when someone with production access leaves, when a laptop goes missing, or when a private repository becomes public.
FAQ
Are environment variables actually safe?
Environment variables are safe enough for a small app when the host injects them into the server process, the repository ignores local env files, and logs never print the values. The same names become public when a framework exposes them to the browser, or when CI prints the environment on failure. Judge safety by who can read the process.
What if I already committed a key and made the repo private?
Make the repo private if it is still public, then rotate the key immediately. Private visibility limits future clones. Clones, forks, caches, and search indexes may already hold the public commit. The provider's revoke button is the urgent control. Clean history later if the team can tolerate a rewritten branch.
How do I share a secret with a collaborator?
Share it through the host or a password manager, scoped to that person. Remove access when they stop working on the project, and rotate keys they could see if you cannot tell what they copied.
Should client apps have any key at all?
Only keys the provider designed to be public, restricted by domain or app id. Anything that spends money, reads other users' data, or signs webhooks stays on your server. If the documentation says "secret" or "private," it stays off the client.
What to do next
List your providers and point each secret at the server environment. Search git history and one production bundle for live prefixes. Rotate anything that shows up, redeploy, and confirm the old key fails.
StaySecure checks the repository for API keys and secrets and explains what to rotate. Run that scan before you announce the app, and again when generated code touches the client.