Claude API Environment Variables Setup Guide
Setting up environment variables for the Claude API means storing your API key and related config (base URL, model name, timeouts) outside your source code, then loading them at runtime through your shell, a .env file, or your hosting platform's secrets manager. The goal is simple: your code never hardcodes a secret key, and the same codebase can run against different keys in development, staging, and production without changes.
This guide walks through the actual setup — naming conventions, .env files, loading libraries per language, and how to avoid the most common mistakes that leak keys or break deployments.
Why environment variables instead of hardcoding
Hardcoding an API key directly in a script is the fastest way to leak it. It ends up in git history, in logs, in error messages pasted into Slack, or in a public repo fork. Environment variables solve this because:
- The value lives outside the file tree, so it's not committed by accident.
- You can rotate a key without touching code — just update the variable and restart.
- Different environments (local, CI, staging, prod) can use different keys with zero code changes.
- Secrets managers (Vault, AWS Secrets Manager, platform dashboards) inject variables at deploy time instead of storing them in files at all.
Naming your variables
There's no strict standard, but a consistent naming pattern avoids confusion once you have multiple providers or multiple environments:
ANTHROPIC_API_KEY=sk-ant-...
ANTHROPIC_MODEL=claude-3-5-sonnet-20241022
ANTHROPIC_MAX_TOKENS=1024
If you're calling Claude through a proxy or gateway service instead of Anthropic directly, prefix accordingly so it's obvious at a glance which key goes where:
SUBTOAPI_KEY=sub_live_...
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1
Keeping provider-specific prefixes matters once a project touches more than one API — mixing up OPENAI_API_KEY and ANTHROPIC_API_KEY in a config file is a common source of silent failures.
Local development with a .env file
The most common setup is a .env file at the project root, loaded by a library, and excluded from git.
- Create the file:
touch .env
echo "ANTHROPIC_API_KEY=sk-ant-your-key-here" >> .env
- Add it to
.gitignoreimmediately, before you commit anything:
.env
.env.local
.env.*.local
- Load it in your code.
Node.js (using dotenv):
import 'dotenv/config';
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
throw new Error('Missing ANTHROPIC_API_KEY in environment');
}
Python (using python-dotenv):
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ["ANTHROPIC_API_KEY"]
Shell session (no library, quick testing):
export ANTHROPIC_API_KEY="sk-ant-your-key-here"
echo $ANTHROPIC_API_KEY
Exported shell variables only last for the current terminal session unless you add the export line to your ~/.bashrc, ~/.zshrc, or equivalent — which is fine for a shared dev machine but not ideal for a key you want scoped to one project.
Validating variables at startup
A script that fails with a cryptic 401 three functions deep is worse than one that fails immediately with a clear message. Add a validation step at the top of your entry point:
const required = ['ANTHROPIC_API_KEY'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required env var: ${key}`);
process.exit(1);
}
}
This catches missing or misnamed variables before any API call is attempted, which saves debugging time in both local dev and CI.
Setting variables in CI/CD
CI platforms don't read your .env file — you set secrets through the platform's own interface, and they're injected as environment variables during the build/test run.
- GitHub Actions: add the key under Settings → Secrets and variables → Actions, then reference it as
${{ secrets.ANTHROPIC_API_KEY }}in your workflow YAML. - GitLab CI: add it under Settings → CI/CD → Variables, optionally marked as "masked" so it never appears in logs.
- CircleCI: set it as a project environment variable in the project settings UI.
Never echo a secret variable in a build log step, even for debugging — most CI systems mask known secret values, but typos or string concatenation can still expose fragments.
Production deployment
In production, environment variables are usually injected by the hosting platform rather than read from a file:
- Vercel / Netlify: set variables in the project dashboard, scoped per environment (production, preview, development).
- Docker: pass variables with
-e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEYor through adocker-compose.ymlenvironment:block, keeping the actual value in an untracked.envfile read by Compose. - Kubernetes: store the key in a
Secretobject and mount it as an environment variable in the pod spec, rather than putting it in aConfigMap.
Managing keys across multiple apps or teams
Once you have more than one application calling Claude, or more than one person on the team, raw environment variables per machine get hard to track — who has which key, which ones are stale, which app is burning through usage. If you're running a product rather than a single script, routing calls through SubToAPI gives you application-scoped keys (sub_live_...) with per-key usage visibility and team seats, so you set one SUBTOAPI_KEY environment variable per app instead of distributing a shared root key. See the quickstart for the exact setup, or check pricing if you're evaluating it for a team.
FAQ
What should I name my Claude API key environment variable? ANTHROPIC_API_KEY is the conventional name if you're calling Anthropic directly, since most SDKs and examples default to reading that exact variable. If you're using a gateway or proxy service, use a prefix that matches the provider, such as SUBTOAPI_KEY, to avoid confusing it with other keys in the same project.
How do I stop my .env file from being committed to git? Add .env to your .gitignore file before your first commit. If it's already been committed, remove it from git tracking with git rm --cached .env, commit that change, and rotate the key immediately since it's already in your git history.
Can I use the same environment variable name across dev, staging, and production? Yes — the variable name stays the same (ANTHROPIC_API_KEY), but the value differs per environment. Most platforms let you scope values per environment in their dashboard, so the same code works everywhere without any conditional logic for which key to load.