What's the Best Way to Store API Keys?

API keys leak most often through public Git repositories or hardcoded source files. The fix is straightforward: store keys in environment variables, add .env to your .gitignore, and rotate any key you suspect has been exposed.

What's the Best Way to Store API Keys?
Quick Answer
Never hardcode API keys directly in your source code. Store them in environment variables or a secrets manager, exclude them from version control using a .gitignore file, and rotate any key you suspect has been compromised. These three habits eliminate the vast majority of real-world API key leaks.

Why API Keys Leak (And Why It's Costly)

API keys are credentials — whoever holds one can make requests billed to your account or access your data. The most common leak vector is a public GitHub repository where a developer accidentally committed a key directly in the code, a config file, or even a comment. GitHub scans for common key patterns and will alert you, but damage can happen within seconds of a push since automated bots continuously scrape new commits.

A leaked OpenAI API key, for example, can result in thousands of dollars in charges before you notice. AWS has documented cases where exposed keys led to $50,000+ bills overnight from crypto-mining bots. Beyond cost, a leaked key can expose your users' data or let attackers abuse services under your identity. The good news: almost every leak is preventable with a small set of disciplined habits applied before you write a single line of production code.

How to Store API Keys Safely Using Environment Variables

The standard practice is to load API keys from environment variables at runtime instead of writing the value in your code. Here is how to do it in Python using a .env file and the python-dotenv library:

1. Install the library: pip install python-dotenv 2. Create a .env file in your project root: OPENAI_API_KEY=sk-your-real-key-here 3. Add .env to your .gitignore file so it is never committed: echo '.env' >> .gitignore 4. Load the key in your script:

import os from dotenv import load_dotenv import openai

load_dotenv() client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

Now your key lives only on your local machine or server, never in your repository. On production servers (Heroku, Vercel, AWS), set environment variables through the platform's dashboard or CLI — for example: heroku config:set OPENAI_API_KEY=sk-your-key. The code reads from the environment the same way in both places.

Advanced Best Practices: Rotation, Scoping, and Secret Scanning

Environment variables are the baseline. These additional practices harden your setup further:

**Least privilege:** Most APIs let you restrict what a key can do. An OpenAI key used only for read operations does not need write access. On AWS, attach an IAM policy that grants only the exact permissions your app needs.

**Rotate keys regularly:** Treat API keys like passwords. Rotate them every 90 days or immediately after any suspected exposure. Most providers let you generate a new key and delete the old one in under a minute.

**Use a secrets manager for production:** Tools like AWS Secrets Manager, HashiCorp Vault, or Doppler store encrypted secrets centrally. Your app fetches the key at runtime via an authenticated API call — no flat files involved.

**Enable secret scanning:** GitHub Advanced Security and tools like GitGuardian or truffleHog automatically scan your commits and history for exposed credentials. Enable these before your first push.

**Never log keys:** Ensure your logging setup does not capture request headers or environment variables. A key printed in a log file is as exposed as one in source code.

Key Takeaways

  • Never write an API key directly in source code — use environment variables loaded at runtime instead.
  • Always add your .env file to .gitignore before your first commit to prevent accidental exposure.
  • Rotate any API key immediately if you suspect it has been seen by an unauthorized party.
  • Use platform-native secret managers (AWS Secrets Manager, Vercel env vars) for production deployments.
  • Enable automated secret scanning tools like GitGuardian to catch leaks before they reach a public repository.

FAQ

Q: What should I do if I accidentally push an API key to GitHub?
A: Revoke the key immediately from the provider's dashboard — assume it has already been scraped. Then remove it from your Git history using git filter-repo or BFG Repo Cleaner, and generate a fresh key to replace it.

Q: Is it safe to store API keys in a .env file on a server?
A: A .env file on a server is safer than hardcoding, but a secrets manager is better for production because it centralizes access control and audit logging. If you use a .env file on a server, restrict its file permissions to the app user only: chmod 600 .env.

Q: Can I use the same API key for development and production?
A: Avoid it — use separate keys for each environment so you can revoke a compromised dev key without disrupting production. Separate keys also make it easier to track usage and set different permission scopes per environment.

Conclusion

Keeping API keys secure comes down to three non-negotiable habits: store them in environment variables, keep them out of version control, and rotate them when anything seems off. The single most impactful next step you can take right now is to open your current project, check that your .gitignore includes .env, and move any hardcoded key into an environment variable before your next commit.

  • 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.
  • What Are API Keys and How Do You Use Them in 2026?
    API keys let your application prove its identity when calling an external service. This guide walks you from zero knowledge to advanced best practices — with real code examples, security tips, and FAQs — so you can integrate any API confidently in 2026.
  • How Do API Keys Authenticate Your Requests?
    An API key is a unique string of characters that acts as a password for your application when it communicates with an external service. It tells the API who is making the request and whether they are allowed to do so. Without a valid key, the API simply refuses the request.