Environment variables for API keys

Published 2026-10-14 · Updated 2026-10-19

Every API client in this ecosystem reads keys from the environment. Get the mechanics right once and you stop thinking about it.

The basics

export OPENAI_API_KEY="sk-proj-..."
python app.py

The variable lives for the shell session only. Close the terminal, it’s gone. To persist it, add the export line to ~/.zshrc or ~/.bashrc.

.env files for projects

In a project directory, a .env file is the standard:

OPENAI_API_KEY=sk-proj-...
OPENROUTER_API_KEY=sk-or-v1-...

Load it with python-dotenv in Python or dotenv in Node. Then, and this is the part people forget, add .env to .gitignore before the first commit. Git history doesn’t forget.

The rules that actually matter

  1. Never hardcode. Not even in a private repo, not even “temporarily.” Scrapers index public code continuously and keys committed to GitHub get revoked within hours, the providers scan for their own formats.
  2. Quote carefully. Most keys tolerate plain quoting, but JWT-format keys and anything with +, / or = in it can trip up unquoted shell assignments or naive .env parsers. Single or double quotes, and check echo ${#VAR} for the right length.
  3. One name per provider. OPENAI_API_KEY, ANTHROPIC_API_KEY, XAI_API_KEY, DEEPSEEK_API_KEY, the conventional names are what SDKs and tools auto-detect. Inventing MY_OPENAI_KEY just means extra plumbing.
  4. Server-side only. A key in browser JavaScript is public the moment you ship. If a web app needs AI, put the call behind your own endpoint.
  5. Distinguish shells from CI. In GitHub Actions and friends, use the platform’s secret store, not a committed .env. The var name stays the same; the storage changes.

Checking what’s set

env | grep -i api_key

Prints every key var in the current shell, useful when a tool insists it “can’t find” a key you exported in a different terminal.