← Blog

Claude API Environment Variable Setup Guide

2026-10-22 · 5 min read · SubToAPI Team

Setting up environment variables for the Claude API means storing your API key and related config (model name, base URL, 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 reads process.env.ANTHROPIC_API_KEY (or the equivalent in your language) instead of a hardcoded string, so the key never ends up in Git history, client-side bundles, or logs.

This guide walks through the actual setup — naming conventions, .env files, Docker, CI/CD, and framework-specific gotchas — so you can get a working, secure configuration in a few minutes rather than guessing which variable name your SDK expects.

Choosing variable names

There's no single enforced standard, but conventions matter for readability and for avoiding collisions with other services. Common patterns:

ANTHROPIC_API_KEY=sk-ant-...
CLAUDE_API_KEY=sk-ant-...
CLAUDE_MODEL=claude-sonnet-4-5
CLAUDE_MAX_TOKENS=4096
CLAUDE_BASE_URL=https://api.anthropic.com

If you're using the official Anthropic SDK, it looks for ANTHROPIC_API_KEY by default — stick with that name unless you have a reason not to. If you're routing through a proxy or gateway service (like SubToAPI), you'll typically use a separate variable so you can swap providers without renaming things across your codebase:

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

Keep provider-specific prefixes consistent across your team. If one developer uses CLAUDE_KEY and another uses CLAUDE_API_KEY, you'll get silent failures that look like authentication errors but are actually just typos in variable names.

Local development with .env files

The standard approach for local dev is a .env file loaded by a library like dotenv (Node), python-dotenv (Python), or direnv (shell-level).

# .env
ANTHROPIC_API_KEY=sk-ant-your-key-here
CLAUDE_MODEL=claude-sonnet-4-5
import 'dotenv/config';

const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
  throw new Error('ANTHROPIC_API_KEY is not set. Check your .env file.');
}

Two things to get right immediately:

  1. Add .env to .gitignore before you commit anything. Do this as the very first step in a new project, not after you've already pushed a key.
  2. Commit a .env.example with placeholder values so teammates know which variables exist without seeing real secrets:
# .env.example
ANTHROPIC_API_KEY=
CLAUDE_MODEL=claude-sonnet-4-5

Validating variables at startup

Don't let a missing or malformed key fail deep inside a request handler. Validate at boot:

function requireEnv(name) {
  const value = process.env[name];
  if (!value) {
    console.error(`Missing required environment variable: ${name}`);
    process.exit(1);
  }
  return value;
}

const apiKey = requireEnv('ANTHROPIC_API_KEY');

This turns a confusing 401 error three requests into your app's lifecycle into an immediate, readable failure at startup — much easier to debug in CI or on a fresh server.

Docker and containerized environments

Never bake API keys into a Docker image. Pass them at runtime instead:

docker run -e ANTHROPIC_API_KEY=$ANTHROPIC_API_KEY my-app

Or with docker-compose.yml:

services:
  app:
    build: .
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
    env_file:
      - .env

Make sure .env is in .dockerignore as well as .gitignore — it's easy to forget the second file and accidentally copy secrets into an image layer during COPY . ..

CI/CD pipelines

In GitHub Actions, store the key as a repository or environment secret, then reference it in the workflow:

- name: Run tests
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: npm test

Avoid printing environment variables in CI logs (echo $ANTHROPIC_API_KEY or verbose debug flags that dump the full environment) — most CI providers mask known secret values automatically, but custom scripts that reconstruct strings from fragments can bypass that masking.

Production deployment platforms

Most hosting platforms (Vercel, Railway, Render, Fly.io, AWS Elastic Beanstalk) have a dashboard section for environment variables. Set them there rather than in a committed config file, and separate variables by environment (development, staging, production) so a staging key never accidentally serves production traffic.

If multiple services or team members need access to the same Claude API key, consider centralizing key management rather than copying the raw key into every service's config. A platform like SubToAPI issues scoped sub_live_... application keys from a single underlying Claude subscription, so you can rotate or revoke access per-service without touching a shared secret. You set SUBTOAPI_KEY and SUBTOAPI_BASE_URL once per service, and usage metadata is tracked per key in the dashboard — useful when you have five microservices and don't want five copies of the same root credential floating around. See the quickstart for the exact variables it expects.

A minimal working example

Putting it together with the official SDK:

import 'dotenv/config';
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

const response = await client.messages.create({
  model: process.env.CLAUDE_MODEL || 'claude-sonnet-4-5',
  max_tokens: Number(process.env.CLAUDE_MAX_TOKENS) || 1024,
  messages: [{ role: 'user', content: 'Say hello in one sentence.' }],
});

console.log(response.content[0].text);

Using environment variables for CLAUDE_MODEL and CLAUDE_MAX_TOKENS as well as the key means you can change models or token limits per environment without redeploying code — just update the variable and restart the process.

Common mistakes to avoid

Questions

Do I need different environment variables for different Claude models? No — a single ANTHROPIC_API_KEY works across models. Use a separate variable like CLAUDE_MODEL to specify which model string to pass in requests, so you can switch models by changing one value.

Can I use the same API key variable in multiple apps? Technically yes, but it's not recommended. Separate keys per app or environment make it easier to track usage and revoke access without affecting unrelated services. See /docs for key management options.

What's the fastest way to test if my environment variable is set correctly? Run a one-line check before your app logic: node -e "console.log(!!process.env.ANTHROPIC_API_KEY)" or echo $ANTHROPIC_API_KEY | cut -c1-8 to confirm it's loaded without printing the full secret.

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 →