How to Store API Keys Securely: Env Vars, .env, Team Secrets

Blog / Developer tools

How to Store API Keys Securely: Env Vars, .env, Team Secrets

How should you store an API key? The basic rule: keys never go into code, never into a Git repository, and never into chats or screenshots. For local development, keep them in environment variables or in a .env file that .gitignore excludes. For teams, use a secrets manager, and add one key per person plus spend limits so that even a leak has a bounded cost.

Below, the advice is organized as local, repository, team, and after-the-fact, with steps you can follow directly.

Why shouldn't an API key live in your code?

A key is just a string that lets whoever holds it spend your money. Once it is in your code, it travels wherever the code goes: Git history, CI logs, coworkers' laptops, screenshots, and forum questions. Even if you delete the line later, the old commits still contain it.

Common ways keys leak:

  • Pushing a file containing a key to a public repository, even if it was public for only a few minutes.
  • Calling a model API directly from front-end code (web pages, mini programs). The key ships with the page and anyone can see it in the browser.
  • Showing the full key in an error screenshot, a screen recording, or terminal output.
  • Baking .env into a Docker image, then pushing that image to a public registry.

So the working assumption is this: if a key has ever appeared somewhere it shouldn't have, treat it as leaked and revoke and recreate it.

How do you store keys for local development?

Option 1: environment variables

Most official SDKs read a conventional environment variable name by default (check each vendor's official docs for the exact name). To set one temporarily in your shell:

export OPENAI_API_KEY="sk-xxxx"

To make it permanent, you can put it in ~/.zshrc or ~/.bashrc, but watch the file permissions and don't sync those files to a public dotfiles repository.

Your code should only read the variable, never contain the plaintext:

import os
api_key = os.environ["OPENAI_API_KEY"]  # fails loudly if unset, which beats silently using an empty value

Option 2: a .env file plus .gitignore

When you have many projects and many variables, a .env file is more convenient. The key is to ignore it first, then create it:

echo ".env" >> .gitignore
echo ".env.*" >> .gitignore
echo "!.env.example" >> .gitignore
touch .env && chmod 600 .env

Then commit a .env.example with no real values, so teammates know which variables they need:

OPENAI_API_KEY=
ANTHROPIC_API_KEY=

If .env has already been committed, adding it to .gitignore does nothing. Remove it from the index first:

git rm --cached .env

Then revoke that key immediately, because it is still in the history.

How do you stop keys at commit time?

Relying on people to remember is unreliable, so add a machine check at the commit step. The simplest option is to write your own .git/hooks/pre-commit that scans the staged changes for anything that looks like a key:

#!/bin/sh
# Example: match the common long strings starting with sk-; adjust the pattern to the key format you actually use
if git diff --cached -U0 | grep -E '^\+.*(sk-[A-Za-z0-9_-]{20,})'; then
  echo "Staged changes appear to contain an API key. Commit aborted."
  exit 1
fi

Don't forget chmod +x .git/hooks/pre-commit. This pattern is crude and only catches the most common format.

A more complete approach is to use an existing scanner such as gitleaks. You can wire it in through the pre-commit framework and also run it in CI to scan the full history. For installation and configuration, follow the tool's official documentation, and set rev to the current release. Also consider turning on the secret scanning that platforms like GitHub provide; check the platform docs for what is available.

How should a team manage keys?

The worst practice on a team is pasting a key into a group chat or sharing a single one. Improve in this order:

  1. One key per person, or one key per project. When something goes wrong you can tell who or which service was responsible, and revoking one key doesn't affect anyone else.
  2. Set spend limits. Configure a spending cap and usage alerts in the provider's dashboard (see the official docs for where the menu is). A cap turns "leaked and run up to the moon" into "loses at most the cap."
  3. Least privilege. If the provider lets you create keys per project or per permission, grant only the scope that is needed.
  4. Store centrally. Use your cloud provider's secrets manager, Vault, or the Secrets feature of your CI platform, and inject the values as environment variables at runtime instead of copying .env files around.
  5. Rotate regularly. Rotate when people change roles and whenever you suspect a leak. Before you swap, confirm which services still use the old key.

We cover these in more detail elsewhere on the site: How to manage API keys on a team: one key per person, budget splits, and rotation and How to use OpenAI project API keys: per-project permissions and limits. For setting limits, see How to set a spending limit and usage alerts for the OpenAI API.

Checklist

CheckDone?
No plaintext keys in code or config files
.env is in .gitignore; the repo contains only .env.example
No key in front-end code that calls a model API directly
Pre-commit scanning or CI scanning is set up
Each person or project has its own key
Every key has a spend cap or usage alert
You know the leak procedure: revoke first, then check usage

What if a key leaks?

The order is: revoke first, then check usage, and last clean up the history and trace the source. Don't start by rewriting Git history; during those few minutes the key is still valid. For the steps, see OpenAI API key leaked: revoke it now, check usage, and prevent a repeat. Other providers follow a similar process; check each vendor's official docs for where to revoke.

If you replaced a key and still get a 401, don't assume the service is down right away. First check the variable name spelling, stray spaces or newlines, and whether you reopened the terminal. If you suspect a server-side problem, check the current status of each service at /en/down.

Using several model providers, and the keys keep piling up

Connecting to multiple providers means multiple keys, multiple dashboards, and multiple quotas to manage. One approach is an aggregation gateway that brings several providers' models under a single key, so there are fewer things to store and rotate.

AGI Plan is one such service: a multi-provider LLM aggregation gateway sold as a monthly subscription, paid in RMB with no overseas credit card needed. Tools like Claude Code and Codex only need a single endpoint URL changed. The service states clearly that it is not an officially authorized channel and that some models are available only outside China; see https://agiplan.dev/models for specifics. AGI Plan is a commercial partner of cdnping, and we disclose that relationship here. Whether or not you use a gateway, everything above applies equally: a gateway key also belongs in an environment variable, should have a cap, and should be one per person. For how to connect, see https://agiplan.dev/startup.

Next steps

  1. Run git log -p | grep -E 'sk-[A-Za-z0-9_-]{20,}' in your project now to see whether any key slipped into the history. Revoke any you find.
  2. Add .env to .gitignore and add a .env.example.
  3. Set a spend cap on every key.
  4. Install commit-time scanning.
  5. To go further on checking usage, read How to track API usage yourself: calculate daily spend from response headers and logs.

Related articles

Keep reading