Claude API Environment Variable Configuration Guide
Claude API Environment Variable Configuration
Configuring environment variables for the Claude API means storing your API key and related settings (base URL, model name, timeout, max tokens) outside your source code, so your app can read them at runtime without hardcoding secrets. The standard approach is a .env file for local development, process environment variables for CI/CD, and a secrets manager or platform-native secret store for production.
This matters because Claude API keys are long-lived credentials with direct billing and data-access implications. Hardcoding them in source files risks leaking them through version control, logs, or client-side bundles. Below is a practical setup that works whether you're calling Anthropic's API directly or using a gateway like SubToAPI that issues its own sub_live_... keys.
Basic Environment Variable Setup
The minimum you need is one variable holding your API key. Convention matters here — most SDKs and examples look for a specific name, so stick with it unless you have a reason not to.
# .env
ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxx
If you're routing requests through SubToAPI instead of calling Anthropic directly, the pattern is identical, just with a different key prefix and base URL:
# .env
SUBTOAPI_KEY=sub_live_xxxxxxxxxxxxxxxx
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1
Load these with dotenv in Node.js:
require("dotenv").config();
const apiKey = process.env.SUBTOAPI_KEY;
const baseUrl = process.env.SUBTOAPI_BASE_URL || "https://api.subtoapi.app/v1";
if (!apiKey) {
throw new Error("Missing SUBTOAPI_KEY environment variable");
}
In Python, use python-dotenv:
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ["SUBTOAPI_KEY"]
The fail-fast check (throw/raise on missing key) is worth adding everywhere. A missing environment variable should crash your app at startup, not three requests into production traffic.
Recommended Variable Set
Beyond the API key itself, it's useful to externalize a few more values so you can change behavior per environment without redeploying code:
SUBTOAPI_KEY=sub_live_xxxxxxxxxxxxxxxx
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1
CLAUDE_MODEL=claude-sonnet-4-5
CLAUDE_MAX_TOKENS=1024
CLAUDE_TIMEOUT_MS=30000
NODE_ENV=production
This separates "what model and limits does staging use" from "what model and limits does production use" — a common need when you want to test a cheaper or newer model before rolling it out.
const config = {
apiKey: process.env.SUBTOAPI_KEY,
baseUrl: process.env.SUBTOAPI_BASE_URL || "https://api.subtoapi.app/v1",
model: process.env.CLAUDE_MODEL || "claude-sonnet-4-5",
maxTokens: parseInt(process.env.CLAUDE_MAX_TOKENS || "1024", 10),
timeoutMs: parseInt(process.env.CLAUDE_TIMEOUT_MS || "30000", 10),
};
async function callClaude(prompt) {
const res = await fetch(`${config.baseUrl}/messages`, {
method: "POST",
headers: {
"Authorization": `Bearer ${config.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: config.model,
max_tokens: config.maxTokens,
messages: [{ role: "user", content: prompt }],
}),
});
return res.json();
}
Keep .env out of version control. Add it to .gitignore and commit a .env.example with placeholder values instead, so teammates know which variables are required without exposing real credentials.
# .env.example
SUBTOAPI_KEY=
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1
CLAUDE_MODEL=claude-sonnet-4-5
CLAUDE_MAX_TOKENS=1024
Environment-Specific Configuration
Most teams run at least three environments — local, staging, and production — and each should have its own key and settings rather than sharing one across all of them.
- Local development:
.envfile, loaded bydotenv, never committed. - CI/CD: environment variables set in your pipeline's secret store (GitHub Actions secrets, GitLab CI variables, etc.), injected at build or test time.
- Production: environment variables set directly on the hosting platform (Vercel, Render, AWS, Docker) or pulled from a secrets manager at container startup.
In GitHub Actions, for example:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
env:
SUBTOAPI_KEY: ${{ secrets.SUBTOAPI_KEY }}
run: npm test
Using separate keys per environment also lets you track usage independently. If you're on SubToAPI's Team or Scale plan, issuing one key per environment (and optionally per service) makes usage metadata in the dashboard actually mean something — you can see which environment is driving cost rather than one undifferentiated number.
Common Mistakes to Avoid
Mixing variable names across files. If one module reads ANTHROPIC_API_KEY and another reads CLAUDE_API_KEY, you'll get confusing "works locally, fails in prod" bugs. Pick one name and use it everywhere, or centralize config in a single module that all other code imports from.
Committing .env by accident. Run git status before your first commit on a new project and confirm .env isn't staged. If it's already in history, rotate the key immediately — removing it from a later commit doesn't remove it from git history.
Not validating at startup. Catching a missing or malformed environment variable at request time, inside a try/catch that logs and moves on, hides real configuration problems. Validate once when the process boots.
Exposing keys to client-side code. Environment variables prefixed for frontend frameworks (like NEXT_PUBLIC_ or VITE_) get bundled into client JavaScript and are visible to anyone who opens dev tools. API keys should only ever live in server-side environment variables.
Hardcoding fallback values with real keys. process.env.API_KEY || "sk-ant-actual-key" defeats the purpose of using environment variables at all. Fallbacks should be for non-secret values like model names or timeouts, never for the key itself.
If you want to skip building this scaffolding yourself, SubToAPI gives you a single sub_live_... key per environment, dashboard-level usage tracking, and a stable Messages and Streaming API that behaves the same whether you're hitting it from a local .env file or a production container. Setup takes about five minutes — see the quickstart or sign up for a free trial.
FAQ
What environment variable name should I use for the Claude API key? There's no single mandated name from Anthropic, but ANTHROPIC_API_KEY is the common convention for direct API access. If you're using a gateway like SubToAPI, use SUBTOAPI_KEY and keep it consistent across all your code and config files.
Should I store the API key in the same .env file as other secrets? Yes, that's normal practice — one .env per environment holding all secrets for that environment. Just make sure the file is gitignored and that production secrets are injected via your hosting platform rather than committed anywhere.
How do I rotate a Claude API key without downtime? Generate a new key, add it as a new environment variable (or update your secrets manager), deploy, confirm the new key works, then revoke the old one. Services like SubToAPI that support multiple keys per account make this easier since you can run both briefly during cutover.