cd /news/ai-tools/claude-code-api-key-setup-from-first… · home › topics › ai-tools › article
[ARTICLE · art-182223] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=· neutral

Claude Code API key setup: from first login to a cloud server

A developer guide details how to configure Claude Code with an Anthropic API key, showing that setting the ANTHROPIC_API_KEY environment variable (or placing it under env in ~/.claude/settings.json) switches billing from a Pro or Max subscription to per-token charges against the key's Console organization. The writeup explains credential precedence—an approved API key overrides a saved subscription login—and notes that API-key sessions do not support Anthropic's official cloud sessions or Remote Control. It also distinguishes ANTHROPIC_API_KEY (X-Api-Key header) from ANTHROPIC_AUTH_TOKEN (Authorization: Bearer) for gateways, and recommends sticking to one configuration method to avoid 401 errors.

recommendation

Use an API key when you need automation, shared billing or a hard spend cap, but keep one configuration method since API-key sessions lose official cloud sessions and Remote Control.

more in playbook: Controlling LLM cost
by read10 min views8 publishedDec 5, 2026

Originally published at alwaysagent.app. The original is kept up to date.

Setting an API key in Claude Code takes one environment variable, but the details decide whether you get billed per token, which credential wins, and whether Anthropic's own cloud features still work. Here is the full picture, with copy-paste config.

To use an API key with Claude Code, export ANTHROPIC_API_KEY (or put it under env in ~/.claude/settings.json), start claude, approve the key when asked, and confirm with /status. Requests are then billed per token to the account that owns the key, not drawn from a Pro or Max subscription.

bash

export ANTHROPIC_API_KEY="<your-api-key>"
claude
/status

Everything below explains what that does, how to make it permanent on a server, and what to check when it stops working. All behavior described here comes from Anthropic's Claude Code documentation; where a detail changes between versions, check the docs for your version.

A subscription login draws on your plan's usage limits, while an API key bills every token to the Console organization that owns it. Anthropic's cost documentation says Claude Code "charges by API token consumption" for API users, and that subscribers have usage included in their plan.

Subscription login (/login) API key
Billing Included in Pro, Max, Team or Enterprise plan limits Per token, billed to the key's Console organization
Limits Plan usage windows API rate limits and any spend limit you set on the workspace
Where to see spend Plan usage in /usage Cost page in the Claude Console
Official cloud sessions Supported Not supported
Remote Control Supported Not supported

A subscription suits one person working interactively. An API key suits automation, shared billing, or a hard spend cap. Check Anthropic's pricing page for current plan numbers.

Use ANTHROPIC_API_KEY for a key from the Claude Console, and ANTHROPIC_AUTH_TOKEN when a gateway or relay expects a bearer token. The only practical difference is the HTTP header.

ANTHROPIC_API_KEY): Sent as the X-Api-Key header. Used instead of your subscription once set and approved.ANTHROPIC_AUTH_TOKEN): Sent as Authorization: Bearer. Anthropic says to use it if you were not told which kind your gateway expects.apiKeyHelper): A script that prints a key on demand, for short-lived tokens from a vault.ANTHROPIC_BASE_URL): Where requests go. Leave it unset for Anthropic's own API. Putting a credential in the wrong variable is a classic cause of 401 errors, because the header is wrong. For a gateway, see the OpenRouter guide for a worked example.

Credential precedence

When several credentials exist, Claude Code picks one in a fixed order, and an API key beats a saved subscription login. Per Anthropic's authentication docs, the order is:

CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX or CLAUDE_CODE_USE_FOUNDRY set)CLAUDE_CODE_OAUTH_TOKEN (a long-lived subscription token from claude setup-token)/login Two consequences matter in practice. First, if you are logged in to a subscription and also have ANTHROPIC_API_KEY set, Claude Code uses the key once you approve it. Second, your saved login is not deleted; it just sits unused while a higher-ranked credential is present.

In interactive mode Claude Code asks once whether to use the key and remembers your answer. You can change it later with the "Use custom API key" toggle in /config, which only appears while the variable is set. In non-interactive mode (claude -p) the key is always used when present, with no prompt.

Pick one method and stick with it, because mixing shell exports and settings files makes it hard to tell which value is live.

Option 1: shell environment variable

The simplest option is a shell export. It applies to every claude started from that shell.

~/.bashrc or ~/.zshrc

export ANTHROPIC_API_KEY="<your-api-key>"

Reload with source ~/.bashrc. The weakness is that non-interactive launches (cron, systemd, some SSH commands) may not read your interactive profile, so the variable can be missing exactly where you need it.

Option 2: settings.json env block

Put the key under env in your user settings so it applies however claude is launched. Anthropic's docs say Claude Code reads these directly from the file.

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_API_KEY": "<your-api-key>"
  }
}

For a gateway or relay, set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN in the same block instead. Do not set the same variable in both a shell export and the env block; the docs and some vendor pages disagree on which one wins in edge cases, so one source of truth is safer.

Option 3: apiKeyHelper

Use apiKeyHelper when the key rotates or lives in a secret manager. Point it at a script that prints the key.

{
  "apiKeyHelper": "/usr/local/bin/print-anthropic-key"
}

The script must print only the key to stdout, as a single printable token, and exit with code 0. A banner or log line in the output breaks it. If it takes more than 10 seconds, Claude Code shows a slow-helper notice. Note that /login will not help while a helper is set, because the helper's output outranks a saved login.

Run /status inside Claude Code; it shows the credential source in use and, if a login and a key both exist, marks the one that is not being used. When you set a custom base URL, it also shows the Anthropic base URL line.

API key row (or Auth token for a gateway) when the key is in effect.env | grep ANTHROPIC in the same shell to see what the process inherited. Tools like direnv can load a stale key from a project .env file.unset ANTHROPIC_API_KEY, remove it from your profile, and relaunch./logout; Anthropic recommends it to avoid conflicts between a login and an external credential. On a server, store the key in a file only your user can read, and start sessions inside tmux so they survive disconnects. A reliable pattern:

chmod 600 ~/.claude/settings.json. claude inside tmux new -s work so a dropped SSH connection does not kill the task./status once after every change to the config. Claude Code itself stores a saved login on Linux in ~/.claude/.credentials.json with mode 0600, and the same permissions are a good default for anything you write yourself. If you run several accounts, give each its own directory with CLAUDE_CONFIG_DIR.

For unattended jobs, remember that in -p mode the key is used without a prompt, and a --bare run does not read the subscription token, so authenticate those with the API key or an apiKeyHelper.

Treat an API key like a password: keep it out of git, scope it, cap its spend, and rotate it when in doubt. Anthropic's own warning is specific: do not put the credential in a project's .claude/settings.json, because that file is committed and shared with everyone who clones the repository.

.claude/settings.local.json (check that your .gitignore covers the latter), never a committed file. Most failures come down to a stale or higher-priority credential, a key in the wrong variable, or a wrong base URL. Work through these in order.

Authentication conflict or "my old login keeps winning"

If you see a warning about conflicting credentials, you have both a login and an environment credential. Run /status to see which is active, then either unset the variable or run /logout and log in again. If an old ANTHROPIC_API_KEY is set in ~/.bashrc, ~/.zshrc or ~/.profile, remove it from there too, or it comes back in every new shell.

"Invalid API key"

The API rejected the key, or Claude Code blocked it before sending. Check for typos, trailing whitespace or line breaks in the value, confirm the key has not been revoked in the Console, and look for a stale key loaded from a .env file. If the key comes from apiKeyHelper, run the script by hand and confirm it prints a valid key.

401 "Invalid authentication credentials"

The credential's format was recognized but the account or organization behind it was rejected. If /status shows an API key row, that key overrides your login: rotate it or unset it. Behind a gateway, the text after "401" is the gateway's own message, so fix the credential the gateway expects, and check you used ANTHROPIC_AUTH_TOKEN versus ANTHROPIC_API_KEY as the provider specifies.

403 "Request not allowed"

A 403 usually means a permissions or network problem rather than a bad key. Anthropic lists three common causes: an inactive subscription, a Console account without the "Claude Code" or "Developer" role, and a corporate proxy interfering with requests. A proxy or filter blocking the host, or Claude Code being unavailable in your region, can also produce it.

"This organization has been disabled"

An old ANTHROPIC_API_KEY from a previous employer or project is overriding a working subscription. Unset it, remove it from your shell profile, relaunch, and confirm with /status.

Base URL and proxy mistakes

ANTHROPIC_BASE_URL changes where requests go, not which model answers them. Set it only when you actually use a gateway, with the exact URL the provider documents. A wrong path, an extra /v1, or a leftover value from an old experiment shows up as connection errors, 404s or auth failures. Set only the base URL without a credential variable and Claude Code keeps using your saved login. Slow gateways may also need a larger API_TIMEOUT_MS.

"Your apiKeyHelper script is failing"

The helper exited with an error, timed out, or printed something other than the key. Run it directly, make it print one token and nothing else, and check the apiKeyHelper row in /status for the last error.

Anthropic's cloud sessions and Remote Control both require a claude.ai subscription login. Per the docs, Remote Control states "API keys are not supported", and it is also unavailable while ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, an apiKeyHelper or a non-Anthropic ANTHROPIC_BASE_URL is active. Cloud sessions "always use your subscription credentials": setting an API key in the cloud environment does not override them, and gateway variables set there are not applied.

So the choice is real. If you want per-token billing, a company gateway, or OpenRouter, the CLI works with all of them, but you run it somewhere you control. Remote Control also needs your own machine to stay on with the claude process running. The comparison is covered in detail in Claude Code on the web vs. Remote Control vs. your own server.

AlwaysAgent hands you a dedicated US Linux server with Claude Code and Codex preinstalled and a browser workspace on top. You paste your key, base URL or relay in settings and start a session; the config lives on your own server.

AlwaysAgent is independent and not affiliated with Anthropic. The same security rules above apply on any box, ours included: one key per purpose, a spend limit in the Console, and rotation when you are unsure.

Export ANTHROPIC_API_KEY in your shell or add it under env in ~/.claude/settings.json, run claude, approve the key when prompted, and confirm with /status. Requests are then billed per token to the key's Console organization.

Yes. Per Anthropic's docs, once the key is set and you approve it, it is used instead of your Pro, Max, Team or Enterprise login, even if you are logged in. Unset it and relaunch to go back to your subscription.

Use ANTHROPIC_API_KEY for a key from the Claude Console. Use ANTHROPIC_AUTH_TOKEN for gateways and relays that expect a bearer token, and use it when you are not sure which one the provider wants.

Usual causes are a stale key in your shell profile or a .env file, a revoked key, a credential in the wrong variable, a wrong ANTHROPIC_BASE_URL, or an old login conflicting. Run /status and env | grep ANTHROPIC, then unset or fix the offending value.

Run unset ANTHROPIC_API_KEY, delete it from ~/.bashrc, ~/.zshrc or ~/.profile and from settings.json, relaunch claude, and check /status. Run /login if no saved login remains.

No. Anthropic's docs say cloud sessions use subscription credentials only, and Remote Control states API keys are not supported. To pay per token, run the CLI on a server you control.

Yes in your user-level ~/.claude/settings.json with chmod 600, but never in a project's committed .claude/settings.json. Add a Console spend limit and rotate the key if it may have leaked.

Yes. Set apiKeyHelper to a script that fetches the key from a secret manager and prints only the key to stdout. It outranks a saved login, so /login will not override it while it is set.

── more in #ai-tools 4 stories · sorted by recency
── more on @anthropic 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/claude-code-api-key-…] indexed:0 read:10min 2026-12-05 · —