How Do You Keep API Keys Secure and Prevent Leaks?
Store API keys in environment variables, never hard-code them in source files, and add secret files to .gitignore before your first commit. These three habits prevent the vast majority of API key leaks.
Keep API keys secure by storing them in environment variables or a dedicated secret manager — never hard-code them into your source code. Add any local secret files (like .env) to your .gitignore so they never reach a public repository. Combine this with key rotation, least-privilege permissions, and monitoring to prevent costly leaks.
Why API Key Leaks Happen and Why They Matter
An API key leak occurs when a secret key ends up somewhere publicly accessible — most commonly in a Git repository, a client-side JavaScript bundle, or a shared screenshot. Attackers actively scan GitHub, GitLab, and Bitbucket for exposed keys using automated bots. Once they find one, they can rack up charges on your cloud account, exfiltrate data, or abuse rate limits under your identity.
The root cause is almost always the same: a developer hard-codes a key into source code for convenience and then forgets to remove it before committing. Even if you delete the key in a later commit, Git history preserves it permanently. Services like AWS, Google Cloud, and Stripe have introduced automatic secret scanning to alert you, but prevention is far more effective than remediation. Understanding this risk is the first step toward building the habit of treating every API key like a password.
How to Store API Keys Safely With Environment Variables
The most reliable method for keeping keys out of code is environment variables. Here is a step-by-step workflow using a `.env` file and Python's `python-dotenv` package:
1. Create a `.env` file in your project root: ``` # .env OPENAI_API_KEY=sk-abc123yourSecretKeyHere ```
2. Add `.env` to `.gitignore` immediately: ``` # .gitignore .env ```
3. Load the key in your Python script: ```python import os from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY") if not api_key: raise ValueError("Missing OPENAI_API_KEY environment variable")
# Use api_key in your API calls ```
This pattern works across languages — Node.js has the `dotenv` npm package, and Ruby has `dotenv-rails`. The principle stays the same: the secret lives outside your code, and only your runtime reads it. For production deployments, inject environment variables through your hosting platform (Vercel, Heroku, AWS Lambda) rather than shipping a `.env` file.
Best Practices for Long-Term API Key Security
Environment variables solve the most common leak vector, but a mature security posture requires additional layers:
**Rotate keys regularly.** Most API providers let you generate a new key and deprecate the old one. Schedule rotation every 90 days or after any team member leaves.
**Apply least-privilege scopes.** If the API supports permission scoping (Google Cloud, AWS IAM), restrict the key to only the endpoints and resources it needs.
**Use a secret manager in production.** Tools like AWS Secrets Manager, HashiCorp Vault, or Doppler encrypt keys at rest, audit access, and simplify rotation. Example AWS CLI retrieval: ```bash aws secretsmanager get-secret-value --secret-id my-api-key --query SecretString --output text ```
**Enable alerts and monitoring.** GitHub's secret scanning, GitGuardian, and TruffleHog detect exposed secrets in commits. Enable these as pre-commit hooks or CI checks.
**Never expose keys in front-end code.** If your browser app needs API access, proxy requests through your back-end server so the key stays server-side.
These practices form a defense-in-depth strategy: even if one layer fails, the others limit the damage.
Key Takeaways
- Never hard-code API keys directly into source files — use environment variables or secret managers instead.
- Add .env and any secret files to .gitignore before your very first commit to the repository.
- Rotate API keys every 90 days and immediately after any suspected exposure or team change.
- Use secret scanning tools like GitGuardian or GitHub's built-in scanner as a safety net in your CI pipeline.
- Keep API keys on the server side only — never embed them in front-end JavaScript or mobile app bundles.
FAQ
Q: What should I do if I accidentally push an API key to GitHub?
A: Revoke or regenerate the key immediately through your API provider's dashboard — do not just delete the commit, because Git history retains it. Then use a tool like BFG Repo-Cleaner to scrub the secret from your repository history.
Q: Can I store API keys in a database instead of environment variables?
A: Yes, but encrypt them at rest and restrict database access tightly. A dedicated secret manager like AWS Secrets Manager or HashiCorp Vault is generally safer and provides audit logging out of the box.
Q: Is it safe to share API keys with teammates through Slack or email?
A: No — messaging platforms store message history and can be compromised. Use a secret manager with role-based access, or at minimum a tool like 1Password for Teams that encrypts shared secrets.
Conclusion
Securing API keys comes down to one core habit: separate secrets from code. Store keys in environment variables for development, use a secret manager for production, and enforce scanning in your CI pipeline. Start today by auditing your current repositories for any hard-coded keys and migrating them to environment variables — that single step eliminates the most common cause of API key leaks.