Claude API Key Environment Variable Setup Guide
Setting up your Claude API key as an environment variable means storing the secret outside your source code, in a place your operating system or runtime can expose to your application at launch. This keeps the key out of git history, out of logs, and out of reach of anyone browsing your repository on GitHub.
The short answer: you export a variable like ANTHROPIC_API_KEY (or SUBTOAPI_KEY if you're using a proxy service) in your shell profile, a .env file, or your hosting platform's secrets manager, then read it in code with process.env.ANTHROPIC_API_KEY or os.environ["ANTHROPIC_API_KEY"]. The exact mechanics differ slightly by OS and deployment target, which is what the rest of this guide covers.
Why environment variables instead of hardcoding
Hardcoding an API key directly in a script works for a five-minute test, but it breaks down fast:
- Accidental commits. A key pasted into
app.jsends up in git history forever, even if you delete it later. - No per-environment separation. You need different keys (or at least different limits) for local dev, staging, and production.
- Rotation pain. If a key leaks, you want to revoke it and swap in a new one without editing and redeploying code.
Environment variables solve all three. The key lives in the environment, not the codebase, and swapping it is a config change, not a code change.
macOS and Linux: shell profile setup
For a key you'll use across every terminal session, add an export line to your shell's startup file.
# bash users
echo 'export ANTHROPIC_API_KEY="your-key-here"' >> ~/.bashrc
source ~/.bashrc
# zsh users (default on modern macOS)
echo 'export ANTHROPIC_API_KEY="your-key-here"' >> ~/.zshrc
source ~/.zshrc
Verify it loaded correctly:
echo $ANTHROPIC_API_KEY
If you're only working in one terminal session and don't want the variable to persist, just run the export command directly without writing it to a file.
Windows setup (PowerShell and CMD)
PowerShell, for the current session only:
$env:ANTHROPIC_API_KEY = "your-key-here"
To persist it across sessions on Windows, use setx:
setx ANTHROPIC_API_KEY "your-key-here"
Note that setx changes won't apply to a terminal window that's already open — close and reopen it first.
Project-level setup with .env files
For project-specific keys, a .env file loaded by a library like dotenv is the standard approach in Node.js and Python projects.
# .env
ANTHROPIC_API_KEY=your-key-here
Node.js:
require('dotenv').config();
const apiKey = process.env.ANTHROPIC_API_KEY;
Python:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.environ.get("ANTHROPIC_API_KEY")
Critical step: add .env to your .gitignore before you commit anything. This is the single most common way API keys leak onto GitHub.
echo ".env" >> .gitignore
Reading the variable in your code
Once the variable is set, reading it is a one-liner in most languages:
// Node.js
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
throw new Error("Missing ANTHROPIC_API_KEY environment variable");
}
# Python
import os
api_key = os.environ.get("ANTHROPIC_API_KEY")
if not api_key:
raise RuntimeError("Missing ANTHROPIC_API_KEY environment variable")
Always add a check that fails loudly if the variable is missing. A silent None or empty string passed into an HTTP header produces a confusing 401 error rather than a clear "you forgot to set the key" message.
Docker and containerized environments
In Docker, pass environment variables at runtime rather than baking them into the image:
docker run -e ANTHROPIC_API_KEY="your-key-here" my-app
Or reference an .env file in docker-compose.yml:
services:
app:
build: .
env_file:
- .env
Never use ENV ANTHROPIC_API_KEY=your-key-here inside a Dockerfile — that bakes the secret into the image layer, and anyone who pulls the image can extract it.
CI/CD and hosting platforms
Every major CI/CD and hosting platform has a secrets interface for exactly this purpose:
- GitHub Actions: repository Settings → Secrets and variables → Actions, referenced as
${{ secrets.ANTHROPIC_API_KEY }}. - Vercel / Netlify: project settings → Environment Variables, scoped per deployment environment.
- Railway / Render / Fly.io: a dedicated secrets or variables tab in the service dashboard.
The pattern is the same everywhere: set the value once in the platform's UI or CLI, reference it by name in your build or runtime config, and never print it in build logs.
If you're routing requests through a proxy like SubToAPI
Some teams don't call the Claude API directly — they route through a gateway for team seat management, usage tracking, or centralized key rotation. SubToAPI issues its own sub_live_... keys that map to your underlying Claude access, so the environment variable setup is identical, just with a different variable name and endpoint:
export SUBTOAPI_KEY="sub_live_xxxxxxxxxxxx"
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello" }]
})
});
This is useful if multiple developers or services need access without sharing one raw API key — you issue separate sub_live_ keys per app or teammate and revoke individually. See the quickstart and messages docs for full request examples, or check pricing if you're evaluating plans.
Common mistakes to avoid
- Committing
.envfiles before adding them to.gitignore. - Putting quotes incorrectly around the key in shell exports (usually harmless, but inconsistent quoting causes confusing bugs on Windows).
- Setting the variable in one terminal tab and testing in another where it was never exported.
- Logging
process.envor full request headers in production, which exposes the key in log aggregators.
Questions
Do I need to restart my terminal after setting an environment variable? For variables added to a shell profile like .bashrc or .zshrc, yes — either restart the terminal or run source ~/.bashrc to reload it in the current session.
Can I use the same environment variable name for multiple API providers? Technically yes, but it's risky. Use distinct names like ANTHROPIC_API_KEY and SUBTOAPI_KEY so you never accidentally send the wrong key to the wrong service.
What's the safest way to share a key with a teammate? Don't share the raw key over chat or email. Use a secrets manager, a password manager's secure sharing feature, or issue each teammate their own scoped key through a platform like SubToAPI so access can be revoked individually.