← Blog

Claude API Key Environment Variable Setup Guide

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

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:

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:

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

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.

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 →