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.
The short version
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 # inside Claude Code: /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.
Subscription login vs API key: what actually differs
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.
Which variable to use: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN or apiKeyHelper
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.
- Console API key (
ANTHROPIC_API_KEY): Sent as the X-Api-Key header. Used instead of your subscription once set and approved. - Gateway or relay token (
ANTHROPIC_AUTH_TOKEN): Sent asAuthorization: Bearer. Anthropic says to use it if you were not told which kind your gateway expects. - Rotating credentials (
apiKeyHelper): A script that prints a key on demand, for short-lived tokens from a vault. - Endpoint (
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:
- Cloud provider credentials (
CLAUDE_CODE_USE_BEDROCK,CLAUDE_CODE_USE_VERTEXorCLAUDE_CODE_USE_FOUNDRYset) ANTHROPIC_AUTH_TOKENANTHROPIC_API_KEY- Output of the
apiKeyHelperscript -
CLAUDE_CODE_OAUTH_TOKEN(a long-lived subscription token fromclaude setup-token) - Anthropic profile and federation credentials
- Subscription OAuth login from
/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.
Configure it: three ways to set the key
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.
~/.claude/settings.json
{ "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.
Verify which credential is active
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.
- Expect an
API keyrow (orAuth tokenfor a gateway) when the key is in effect. - Run
env | grep ANTHROPICin the same shell to see what the process inherited. Tools like direnv can load a stale key from a project.envfile. - To switch back to a subscription, run
unset ANTHROPIC_API_KEY, remove it from your profile, and relaunch. - To clear a saved login before using a gateway token, type
/logout; Anthropic recommends it to avoid conflicts between a login and an external credential.
Persist the key on a Linux server
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:
- Create the settings file with the key, as in Option 2 above.
- Lock it down:
chmod 600 ~/.claude/settings.json. - Run
claudeinsidetmux new -s workso a dropped SSH connection does not kill the task. - Check
/statusonce 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.
Keep the key safe
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.
- Where to store it: user-level
~/.claude/settings.jsonor.claude/settings.local.json(check that your.gitignorecovers the latter), never a committed file. - Limit blast radius: in the Console, use workspaces and set a workspace spend limit so a leaked or runaway key cannot spend without bound.
- Rotate: create a new key at the Console's API keys page, update the server, then revoke the old key. A revoked key shows up as an "Invalid API key" error, which is also how you notice a stale copy somewhere.
Claude Code API key not working: common errors
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.
Why official cloud sessions and Remote Control don't accept API keys
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.
Running it in the cloud with AlwaysAgent
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.
- Your keys stay on your server. AlwaysAgent does not proxy model calls or add a markup on tokens.
- Close your laptop and the task keeps running; check in from your phone.
- Use an Anthropic key, OpenRouter, a relay, or your own subscription login, per session.
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.
FAQ
How do I set up an API key for Claude Code?
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.
Will ANTHROPIC_API_KEY override my Claude subscription?
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.
Should I use ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN?
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.
Why is my Claude Code API key not working?
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.
How do I switch from an API key back to my subscription?
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.
Does Claude Code on the web or Remote Control support API keys?
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.
Is it safe to put the API key in settings.json?
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.
Can I keep my key out of config files entirely?
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.

