← Blog

Claude API Environment Variable Configuration Tips

2026-11-05 · 5 min read · SubToAPI Team

If you're searching for how to configure environment variables for the Claude API, you're probably trying to solve one of two problems: keep your API key out of source control, or get the same key working reliably across local development, CI, and production without hardcoding secrets. Both problems have the same root fix — store credentials in environment variables, load them consistently, and never let them touch your repo.

This guide covers the practical setup: naming conventions, .env file handling, loading libraries, per-environment configuration, and common mistakes that leak keys or break deployments.

Why environment variables matter for API keys

Hardcoding an API key directly in your source code is the single most common way keys end up in public GitHub repos, screenshots, or Slack messages. Environment variables solve this by keeping secrets outside the codebase:

This applies whether you're calling Anthropic's API directly or using a gateway like SubToAPI that issues its own sub_live_... application keys on top of your Claude access.

Naming conventions that avoid confusion

Pick one naming scheme and stick to it across every environment:

ANTHROPIC_API_KEY=sk-ant-...
CLAUDE_MODEL=claude-sonnet-4-5
CLAUDE_MAX_TOKENS=4096

If you're calling multiple services, prefix clearly instead of using generic names like API_KEY or TOKEN — these collide easily in larger codebases or when a teammate copies a .env.example from another project.

SUBTOAPI_KEY=sub_live_...
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1

Keep the prefix consistent in code, CI config, and your hosting dashboard. A mismatched variable name (CLAUDE_KEY in code vs. CLAUDE_API_KEY in your platform's secret settings) is one of the most common causes of "works locally, fails in production" bugs.

Local development with .env files

For local work, a .env file loaded by a library like dotenv keeps things simple:

# .env
ANTHROPIC_API_KEY=sk-ant-xxxxxxxx
SUBTOAPI_KEY=sub_live_xxxxxxxx
require('dotenv').config();

const apiKey = process.env.SUBTOAPI_KEY;

Two rules that prevent almost every leak incident:

  1. Add .env to .gitignore immediately, before you add the first secret — not after.
  2. Commit a .env.example with placeholder values so teammates know what variables are required without ever seeing real keys.
# .env.example
ANTHROPIC_API_KEY=
SUBTOAPI_KEY=
SUBTOAPI_BASE_URL=https://api.subtoapi.app/v1

Separating environments: dev, staging, production

A frequent mistake is reusing the same API key across dev, staging, and production. If one environment is compromised — a leaked log, a misconfigured debug endpoint — every environment is affected. Instead:

With SubToAPI specifically, you can create multiple application keys from the same dashboard, assign them per project or environment, and track usage separately — so a staging key behaving unexpectedly doesn't drain your production quota. Key creation and scoping are covered in the quickstart.

Loading variables in CI/CD

CI pipelines need the same variables without a .env file ever existing on disk. Most CI platforms (GitHub Actions, GitLab CI, CircleCI) provide an encrypted secrets store — use it instead of inlining values in YAML:

# GitHub Actions example
env:
  SUBTOAPI_KEY: ${{ secrets.SUBTOAPI_KEY }}
  ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

Avoid printing environment variables in build logs for debugging — even a partial console.log(process.env) can expose full secrets in log history that's harder to purge than you'd expect.

Configuring variables in production hosting

Every major platform (Vercel, Railway, Render, Fly.io, AWS) has a secrets/environment panel in its dashboard. The pattern is the same everywhere:

  1. Set the variable name and value in the platform UI or CLI, never in a config file committed to git.
  2. Scope variables per deployment environment if the platform supports it (production vs. preview).
  3. Restart or redeploy after changing a variable — most platforms don't hot-reload them into running processes.
const response = await fetch(`${process.env.SUBTOAPI_BASE_URL}/messages`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.SUBTOAPI_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'claude-sonnet-4-5',
    max_tokens: 1024,
    messages: [{ role: 'user', content: 'Hello' }],
  }),
});

Validating variables at startup

Instead of discovering a missing key when the first API call fails in production, validate required variables when your app boots:

const required = ['SUBTOAPI_KEY', 'SUBTOAPI_BASE_URL'];
const missing = required.filter((name) => !process.env[name]);

if (missing.length > 0) {
  throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}

This turns a silent runtime failure into a loud, immediate one — far easier to debug than a 401 error buried in logs hours after deployment.

Where a gateway simplifies things

If you're managing Claude access across a team — multiple developers, multiple projects, multiple environments — raw API key management gets messy fast: who has access, which key is burning through quota, which environment is using which model. SubToAPI centralizes this into one dashboard: generate scoped sub_live_... keys per project, see usage metadata per key, and manage team seats without passing raw credentials around in Slack. See pricing for plan details or start with a free trial at signup.

questions

Should I ever put an API key directly in client-side JavaScript? No. Environment variables only protect secrets on the server. Any variable bundled into client-side code (even via a build tool) is visible in the browser. Keep API calls server-side or proxy them through your backend.

What's the difference between .env and .env.local? .env is often committed as a shared template or shared defaults, while .env.local (ignored by git in most frameworks like Next.js) holds personal, machine-specific overrides. Never put real secrets in a file meant to be committed.

How do I rotate a leaked Claude API key safely? Revoke the compromised key immediately in your provider's dashboard, generate a new one, update it in every environment (local, CI, production secrets), and redeploy. Check logs for any unexpected usage during the exposure window before considering the incident closed.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →