ThisCalculator

Everyday

Secure API Keys: Prevent Accidental Exposure

Updated · Standard formula, shown below

This guide walks you through practical steps to keep your API keys and secrets safe, covering storage, code hygiene, and response to leaks. You’ll learn how to prevent accidental exposure in code, logs, and public repositories, and what to do if a key does get out.

What You’ll Need

  • Access to the project’s code repository (Git, SVN, etc.)
  • Permissions to modify environment variables on your server or hosting platform
  • An account with the API provider (to rotate keys if needed)
  • A secret scanning tool (e.g., git-secrets, trufflehog, or GitHub’s built-in scanner)

Step-by-Step

  1. Use environment variables, not code. Store API keys in environment variables or a dedicated secrets manager (like AWS Secrets Manager, HashiCorp Vault, or a .env file that is not committed). Access them in code via process.env.API_KEY (Node.js), os.environ['API_KEY'] (Python), or similar. Never hardcode keys in source files.
  2. Add a .gitignore entry. If you use a .env file or any config file containing secrets, add it to .gitignore so it is never committed. Also ignore files like *.pem, *.key, and secrets.*.
  3. Rotate keys immediately if exposed. If you suspect a key has been leaked—even in a private repo—revoke it and generate a new one. Most providers allow you to rotate keys from their dashboard. Do this before removing the old key from code.
  4. Use a secret scanner. Run tools like git-secrets (for Git) or trufflehog to scan your entire history for accidental commits. Many platforms (GitHub, GitLab) have built-in secret scanning that alerts you when a known key pattern appears.
  5. Limit key permissions. Give each key the minimum permissions needed (e.g., read-only, specific IP ranges). If a key is exposed, the damage is limited. Use separate keys for different environments (dev, staging, prod).
  6. Set up automated scanning in CI/CD. Add a step in your build pipeline that runs a secret scanner on every commit. This catches leaks before they reach the remote repository.
  7. Use a secrets manager for production. For server-side apps, use a secrets manager to inject keys at runtime. This avoids storing keys in files altogether.
  8. Monitor logs and error reports. Check that your application logs do not print full keys. Configure logging to redact or mask secrets. Test by triggering an error that might include the key.
  9. Educate your team. Make sure every developer knows the policy: no keys in code, no screenshots with keys, no sharing keys in chat. Enforce via code review.

Common Mistakes

  • Committing a .env file because it was not ignored early.
  • Using the same key for multiple services or environments.
  • Sharing keys in team chat or email—these are often logged and searchable.
  • Assuming a private repo is safe—it can become public later or be accessed by former employees.
  • Not rotating keys after a suspected leak, hoping it was not seen.

Tips

  • Use a naming convention like API_KEY_ prefix to make scanning easier.
  • Store keys in a password manager for personal projects.
  • For serverless functions, use platform-specific secret storage (e.g., AWS Lambda environment variables).
  • Set up alerts for unusual API usage—that can be a sign of a stolen key.
  • Regularly audit your repositories with a scanner—not just once.

Troubleshooting

Key was committed in an old commit. Even if you remove it in a later commit, the key is still in history. Rotate the key, then use git filter-branch or BFG Repo-Cleaner to purge it from history. Push the cleaned history and force-push if necessary (coordinate with your team).

Secret scanner flags a false positive. Some strings look like keys but aren’t. If it’s a test key or a placeholder, you can add an allowlist entry in your scanner config. But first verify it’s not a real key.

Environment variable not loading in production. Check that your server restarted after setting the variable. Ensure the variable name matches exactly. For .env files, confirm the file exists and is not ignored.

Key works locally but not on CI. CI environments need their own secrets configured. Add the key to the CI platform’s secret store, not in the repo.

Accidentally shared a key in a public forum. Immediately rotate the key. Then check if any automated bots scraped it (they often do within minutes). Monitor your API usage for anomalies.

Frequently Asked Questions

Can I use a .env file in production?

It’s acceptable for small projects, but a secrets manager is more secure because it centralizes access and allows rotation without redeploying.

What is the difference between an API key and a secret?

An API key is often a unique identifier for your application, while a secret (like a client secret) is used for authentication. Both should be treated with the same level of protection.

How often should I rotate my API keys?

There’s no universal rule, but rotating every 90 days is a good practice. Rotate immediately if you suspect exposure or if a team member with access leaves.

Is it safe to store keys in a public repo if they are encrypted?

No. Encryption keys can be cracked, and the encryption key itself must be stored somewhere. Never put secrets in a public repo, even encrypted.

What should I do if I find a key in an old commit?

Rotate the key first. Then clean the history using git filter-repo or BFG. Finally, push the cleaned history and force-push if needed.

Can I use the same key for multiple projects?

You can, but it’s risky. If one project leaks, all are compromised. Use separate keys per project and per environment.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.