← Blog/Security

API Key Management: How to Store, Rotate, and Protect Your Keys

API keys are the most commonly leaked credential in production systems. They end up in GitHub repos, log files, Slack messages, and browser history. Here's how to manage them so a single exposure doesn't become a breach.

·8 min read

Every week, thousands of API keys are accidentally committed to public repositories. GitHub's secret scanning catches millions of exposed credentials per year — and that's only the public repos. The private repo leaks, Slack paste jobs, and screenshot accidents never get counted. API key management isn't glamorous, but it's one of the highest-ROI security practices a small team can adopt.

Why API Keys Are So Frequently Exposed

The problem isn't that developers are careless — it's that the path of least resistance leads to insecurity. You need a Stripe key to test locally. You paste it into .env. You forget .env isn't in .gitignore. You commit. The key is now in git history forever, even after you delete the file.

Or you hardcode the key into a config file to debug a production issue quickly. Or you include it in a log statement to trace a request. Or you paste it into a Slack message to share with a teammate. Each of these is a vector. Each of them happens constantly.

The .env File Problem

.env files are the standard solution for keeping secrets out of code — and they work, when you remember to exclude them. The issue is human error at the worst possible time: when you're setting up a new project, moving fast, and not thinking about gitignore configuration.

Best practices for .env files:

  • Always include .env, .env.local, .env.production, and .env.*.local in .gitignore before your first commit
  • Commit a .env.example file with placeholder values — this documents required variables without exposing secrets
  • Run git rm --cached .env if a .env file was accidentally staged, and use BFG Repo Cleaner or git filter-branch to purge it from history
  • Use pre-commit hooks (like detect-secrets or git-secrets) to scan for secret patterns before allowing commits

Important: deleting a file from git does not remove it from history. If a key was ever committed, treat it as compromised. Rotate it immediately, even if the repo is private.

How to Store API Keys Securely

The right storage mechanism depends on your environment:

Local development

.env.local files, never committed. For team environments, a shared secrets manager (see below) is better than sharing .env files over Slack.

CI/CD pipelines

Use your CI provider's native secrets storage: GitHub Actions Secrets, GitLab CI Variables, CircleCI Environment Variables. Never hardcode keys in workflow files. Mask secret values in logs. Use short-lived tokens where possible.

Production environments

Platform environment variables (Vercel, Railway, Render, Fly.io) are acceptable for simple setups. For anything handling sensitive customer data or at significant scale, use a dedicated secrets manager:

  • AWS Secrets Manager / Parameter Store — IAM-controlled, rotation built in, audit trail. Standard choice for AWS deployments.
  • HashiCorp Vault — Self-hosted or HCP Vault. Extremely flexible, supports dynamic secrets. Higher operational complexity.
  • Doppler — Developer-friendly SaaS secrets manager. Simple sync to multiple environments. Good for small teams that want structure without Vault's complexity.
  • 1Password Secrets Automation — Good if your team already uses 1Password. Integrates with CI/CD and local dev.

Check if your API is leaking keys or sensitive data

Scantient scans your live API from the outside — catching exposed secrets, open endpoints, and misconfigured headers. Free, no signup.

Scan Your API Free →

API Key Rotation Policies

Rotation is the practice of replacing an existing API key with a new one on a defined schedule — or immediately after a suspected exposure. The goal is to limit the useful lifetime of any key that might be compromised without your knowledge.

Rotation cadence guidelines by key type:

  • Payment processor keys (Stripe, etc.): Rotate every 90 days. Immediately on any developer departure or team change.
  • Internal service-to-service keys: Every 30–90 days, or use short-lived tokens from an auth service instead of static keys.
  • Third-party SaaS integrations: Every 180 days. Maintain an inventory — rotate what you actually use, audit what you've forgotten about.
  • After any team member leaves: Rotate all keys that person had access to. No exceptions.

Rotation is only practical if your deployment supports it without downtime. This means keeping secrets in environment variables or a secrets manager — not hardcoded in application config that requires a rebuild to update.

Key Scoping and Least Privilege

Most API platforms let you create keys with limited permissions. A key for your analytics dashboard doesn't need write access to payment methods. A key for a webhook receiver doesn't need access to user data exports.

Scoping rules:

  • Create one key per integration, not one key for everything
  • Grant only the permissions each integration actually needs
  • Use IP allowlists where the API provider supports it
  • Use separate keys for development and production — never share them
  • Document what each key is for; undocumented keys get forgotten

The blast radius of a compromised key is limited by its scope. A leaked read-only analytics key is a nuisance. A leaked admin key with billing access is a crisis.

Exposure Detection

Detection is the safety net for when prevention fails. Several tools can help:

  • GitHub Secret Scanning: Automatically scans public repos and notifies API providers when their key patterns are detected. Many providers (Stripe, Twilio, AWS) are enrolled. Free for public repos; available on GitHub Advanced Security for private repos.
  • GitGuardian: Monitors both public GitHub activity and your own repos for secret patterns. Alerts in near-real-time. Accidental secret commits are one of the most common API security mistakes we see in startup codebases.
  • Trufflehog: Open-source tool for scanning git history for secrets. Run it on your repos periodically.
  • API provider alerts: Enable anomaly detection and unusual usage alerts from your API providers. Sudden spikes in usage from unexpected IPs are a key exposure signal.

What to Do When a Key Is Exposed

Speed matters. The window between exposure and exploitation can be minutes.

  1. Revoke the key immediately. Don't wait to understand the full scope — revoke first, investigate second.
  2. Issue a replacement key and update all systems that depend on it.
  3. Check usage logs for the compromised key. Look for unusual geographic locations, volumes, or endpoints accessed.
  4. Determine scope of exposure: Was the key in a public repo? A private one? A log file? Each has different blast radius implications.
  5. Purge from git history if it was committed. Use BFG Repo Cleaner:bfg --replace-text secrets.txt your-repo.git
  6. Post-mortem: How did this happen? Update your .gitignore, pre-commit hooks, and team practices to prevent recurrence.

API Key Management Checklist

  • .env files excluded from git before first commit
  • .env.example committed with placeholder values
  • ✅ Pre-commit hooks scanning for secret patterns
  • ✅ Production secrets in a secrets manager or platform env vars
  • ✅ One key per integration, least-privilege scopes applied
  • ✅ Separate keys for dev and production
  • ✅ Rotation schedule documented and enforced
  • ✅ GitHub Secret Scanning or GitGuardian monitoring active
  • ✅ Incident response plan for key exposure (revoke → replace → audit → purge)

For a broader look at the API security vulnerabilities that follow from poor key management, read the complete API security guide.

Scan Your API Free — 60 Seconds

External security scan catches exposed endpoints, misconfigured headers, and API key leakage. No signup. No SDK.