Best Practices for Storing API Keys Securely
If you're asking how to store API keys securely, the short answer is: never in source code, never in client-side JavaScript, and never in plaintext config files that get committed to version control. Keys belong in environment variables or a dedicated secret manager, loaded at runtime, scoped to the minimum permissions needed, and rotated on a schedule.
That's the summary. The rest of this article covers the practical details: where to put keys, how to load them safely, how to handle them in CI/CD, and what to do when a key leaks anyway — because eventually, one will.
Why API key storage matters
An API key is a credential, not a configuration value. If someone else gets your key, they can rack up usage charges, exfiltrate data, or impersonate your application. The risk isn't theoretical — leaked keys on public GitHub repos get scraped and abused within minutes, often by automated bots scanning commit history.
The goal of secure storage is to minimize the number of places a key exists in plaintext and the number of people or systems that can read it.
Core practices
1. Use environment variables, not hardcoded strings
This is the baseline. Never write a key directly into source code:
// Don't do this
const apiKey = "sub_live_abc123xyz";
Instead, read it from the environment:
const apiKey = process.env.SUBTOAPI_KEY;
if (!apiKey) {
throw new Error("Missing SUBTOAPI_KEY environment variable");
}
For local development, use a .env file loaded by a library like dotenv, and make sure .env is in .gitignore from day one — not added after the first commit.
2. Never commit secrets to version control
Even private repos aren't safe enough — contributors, forks, CI logs, and backup exports can expose history. If a key does get committed:
- Revoke and rotate it immediately. Removing the commit later doesn't help; the key is already compromised.
- Use
git-secretsor similar pre-commit hooks to scan for key patterns before they're pushed. - Treat
.env.examplefiles as documentation only — placeholder values, never real ones.
3. Use a secret manager for production
Environment variables are fine for small projects, but production systems benefit from a dedicated secret manager: AWS Secrets Manager, HashiCorp Vault, Google Secret Manager, or your platform's built-in equivalent (Vercel, Render, and Railway all have encrypted env var storage). These give you:
- Encryption at rest
- Access logging (who read the secret, when)
- Fine-grained IAM permissions
- Automatic rotation support
For most small-to-medium apps, a platform's built-in encrypted environment variables are sufficient. Vault or AWS Secrets Manager make more sense once you have multiple services, multiple environments, and a team that needs audited access.
4. Keep keys server-side only
API keys — including SubToAPI keys — should never be exposed in frontend JavaScript, mobile app bundles, or any code that ships to the client. Anything shipped to a browser is readable by anyone who opens dev tools.
If you need to call an API from a browser-based app, put a thin backend in between: the browser talks to your server, and your server holds the key and talks to the upstream API.
// server.js — the browser never sees this key
app.post("/api/chat", async (req, res) => {
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(req.body)
});
const data = await response.json();
res.json(data);
});
5. Scope keys to the minimum necessary access
If your provider supports multiple keys per account or per environment, use separate keys for development, staging, and production. If one leaks, you limit the blast radius and know exactly which environment to investigate. SubToAPI issues application keys in the sub_live_... format per project in the dashboard, so you can generate distinct keys for each app or environment rather than sharing one key across everything. See the quickstart guide for how key creation and request authentication work.
6. Rotate keys on a schedule and after any suspected exposure
Rotation isn't just a reaction to a leak — it should be routine. A reasonable policy:
- Rotate every 90 days for production keys
- Rotate immediately after any team member with access leaves
- Rotate immediately if a key appears in a log file, error report, or support ticket by mistake
Build rotation into your deployment process so it's not a manual, error-prone event. Update the secret in your manager or CI first, deploy, confirm the new key works, then revoke the old one.
7. Handle keys carefully in CI/CD
CI pipelines are a common leak vector because logs are often more visible than production systems realize. Use your CI provider's encrypted secrets feature (GitHub Actions secrets, GitLab CI/CD variables) rather than plaintext YAML. Mask secret values in log output, and avoid printing environment variables for debugging — env dumps in CI logs are a frequent accidental exposure point.
8. Avoid logging keys, even partially
It's tempting to log "using key: sub_live_ab12..." for debugging, but partial key fragments combined with other log data can still aid an attacker piecing together context. Strip or fully redact any credential before it touches a log line, error tracker, or monitoring dashboard.
What to do if a key leaks
- Revoke it immediately from your provider's dashboard.
- Issue a new key and update it everywhere it's used.
- Check usage logs for unexpected activity during the exposure window.
- Audit how it leaked — commit history, a shared Slack message, a public Postman collection — and fix the process, not just the symptom.
If you're managing Claude API access through SubToAPI, keys can be revoked and regenerated instantly from the dashboard, and usage metadata per key helps you spot anomalies quickly without digging through raw logs.
Summary checklist
- Store keys in environment variables or a secret manager, never in code
- Keep
.envfiles out of version control - Never expose keys in client-side code — proxy through a backend
- Use separate keys per environment and per project
- Rotate on a schedule, not just reactively
- Redact keys from all logs and error reports
- Revoke and rotate immediately on any suspected leak
questions
Is it safe to store API keys in a .env file? Yes, for local development, as long as .env is excluded from version control via .gitignore and never shared in plaintext over chat or email. For production, a secret manager or your platform's encrypted environment variables is a better fit.
Should I use the same API key across development and production? No. Use separate keys per environment so a leak in one doesn't compromise the other, and so you can tell from usage logs exactly which environment made a given request.
What's the fastest way to recover from a leaked API key? Revoke the key immediately, generate a new one, update every service that uses it, and review usage logs for unauthorized activity during the window the key was exposed.