Secure API Key Storage for Production: A Practical Guide
Secure API key storage for production means keeping secrets out of your codebase, limiting who and what can read them, and making sure a leaked key does minimal damage before you can revoke it. In practice that boils down to four things: never commit keys to source control, inject them at runtime through environment variables or a secret manager, scope each key to the narrowest permissions it needs, and have a fast rotation path when something goes wrong.
If you're reading this because you just realized a key is sitting in a .env file inside a public repo, or because a security review flagged hardcoded credentials, the fix below applies whether you're protecting a database password, a payment provider secret, or an LLM API key like a sub_live_... token from SubToAPI. The principles are the same; only the tooling differs slightly by platform.
Where Keys Should Never Live
Before talking about the right way, it helps to be explicit about the wrong ways, because these show up constantly in production incidents:
- Hardcoded in source files — even "temporary" keys get committed and stay in git history forever, even after you delete the line.
- Committed
.envfiles —.envis meant to be local-only. Add it to.gitignoreon day one, not after a leak. - Client-side JavaScript or mobile app bundles — anything shipped to a browser or app binary can be extracted. API keys belong on the server, never in frontend code.
- Slack messages, tickets, or shared docs — convenient for a quick fix, terrible for audit trails and rotation.
- Build logs and CI output — many pipelines accidentally print environment variables during debugging steps.
If a key has ever touched any of these, treat it as compromised and rotate it, don't just hope no one noticed.
Environment Variables: The Baseline
For most applications, environment variables are the minimum acceptable standard. They keep secrets out of the codebase and let you set different values per environment (dev, staging, production) without code changes.
# .env (never committed)
SUBTOAPI_KEY=sub_live_xxxxxxxxxxxxxxxxxxxx
DATABASE_URL=postgres://...
// loaded via dotenv locally, or injected natively by the platform in production
const apiKey = process.env.SUBTOAPI_KEY;
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
messages: [{ role: "user", content: "Summarize this ticket" }]
})
});
Environment variables alone have limits: they're visible to anything running in the same process, they can leak through crash logs or error reporting tools, and most platforms store them in plaintext in their dashboard. That's fine for a side project, but production systems handling customer data or paid API usage usually need the next layer.
Secret Managers for Production Workloads
A dedicated secret manager (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault, or your cloud provider's equivalent) adds three things environment variables alone don't give you:
- Encryption at rest and in transit, with access controlled by IAM policies rather than whoever can read the deployment config.
- Audit logs of exactly which service or person accessed which secret and when.
- Programmatic rotation — secrets can be rotated without redeploying the application, as long as your app reads them at request time or on a short-lived cache rather than baking them in at boot.
A typical pattern: your app's deployment role has permission to fetch one specific secret, nothing else. The secret manager injects it into the runtime environment or the app fetches it on startup. No human ever needs to see the plaintext value in a dashboard.
# AWS CLI example, conceptually similar to GCP Secret Manager or Vault
aws secretsmanager get-secret-value --secret-id prod/subtoapi-key --query SecretString --output text
For small teams without the budget or need for a full secret manager, a platform-native equivalent (Vercel environment variables with team-scoped access, Fly.io secrets, Render environment groups) is a reasonable middle ground — better than raw .env files, not quite as strong as Vault.
Scope Keys to the Minimum They Need
Secure storage only solves half the problem. The other half is limiting what a key can do if it does leak. This is why platforms that let you issue separate API keys per application or per team member are worth using over a single shared credential.
With SubToAPI, each application gets its own sub_live_... key rather than everyone sharing one Claude credential. That means:
- A leaked key for your staging app doesn't expose production traffic.
- You can revoke one team member's or one service's access without rotating everyone else's key.
- Usage metadata per key makes it obvious which application is responsible for a spike or an anomaly, which is often the first sign a key has leaked.
Check the docs for how key scoping and usage metadata work, and docs/quickstart for setting up your first key correctly from the start rather than retrofitting security later.
Rotation Is Part of Storage, Not an Afterthought
A key storage strategy isn't complete without a rotation plan. Build for rotation before you need it:
- Keep secrets out of long-lived caches or compiled binaries so a new value takes effect without a full redeploy.
- Support two valid keys briefly during rotation (old and new) so you don't cause downtime mid-swap, if your provider allows it.
- Automate rotation on a schedule for high-value keys, and immediately for any key that touched a log file, screenshot, or support ticket.
- Document who can generate and revoke keys — rotation during an incident is not the time to figure out who has dashboard access.
Checklist for Production-Ready Key Storage
- [ ] No keys in source control, ever — check git history too, not just current files
- [ ]
.envfiles gitignored and never deployed as static files - [ ] Secrets injected via environment variables or a secret manager, never hardcoded
- [ ] Each application or environment has its own scoped key
- [ ] Logging and error reporting configured to redact secret values
- [ ] Rotation process documented and tested at least once
- [ ] Usage monitored per key so anomalies are visible early
Questions
Is storing an API key in an environment variable secure enough? For most small to mid-sized production apps, yes, as long as .env files are never committed, logs don't print environment variables, and the deployment platform restricts who can view them. For regulated or high-traffic systems, pair environment variables with a dedicated secret manager for audit logging and rotation.
What should I do if an API key was accidentally committed to git? Revoke or rotate the key immediately through the provider's dashboard — removing it from the latest commit is not enough since it remains in git history. Then scrub the history with a tool like git filter-repo if the repo is public, and audit logs for any unauthorized usage during the exposure window.
Should frontend applications ever hold API keys directly? No. Any key included in client-side JavaScript or a mobile app bundle can be extracted by anyone using the app. Route requests through your own backend, which holds the real key server-side, and have the frontend call your backend instead of the third-party API directly.