Troubleshooting · Claude Code
Claude Code API Error 401 authentication_error — Fix
Claude Code prints API Error: 401 authentication_error when no valid key reaches the endpoint it is talking to. The environment-variable rules that cause it and the fix.
What you see
API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid or missing API key."}}Why it happens
- ANTHROPIC_BASE_URL is not set in the shell that launched claude, so the key goes to api.anthropic.com, which has never seen it. That server answers invalid x-api-key.
- The variable is set in a different shell than the one that launched claude — an export in one terminal does not exist in another, and GUI launchers do not read your shell profile.
- ANTHROPIC_AUTH_TOKEN is empty, truncated or holds a key from another provider. This endpoint accepts the key in x-api-key or Authorization: Bearer; a 401 means that no key it received is valid.
- The key was revoked, or expired if it was issued with an expiry date.
How to fix it
- Set ANTHROPIC_BASE_URL and ANTHROPIC_AUTH_TOKEN together, and unset ANTHROPIC_API_KEY so a stale key from another provider cannot get in the way.
- Verify inside the same shell that runs claude: print the first characters of the variable right before launching.
- Confirm the key is active in your dashboard, then test it with curl against https://router.apitoken.sale/v1/models.
Working environment for this gateway
export ANTHROPIC_BASE_URL="https://router.apitoken.sale"
export ANTHROPIC_AUTH_TOKEN="sk-pool-•••"
export ANTHROPIC_MODEL="openai/gpt-6.1-terra" # or a google/gemini-* model
export ANTHROPIC_DEFAULT_HAIKU_MODEL="openai/gpt-6-luna" # background tasks
unset ANTHROPIC_API_KEY # keep one credential
claudeRelated searches
API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}claude code 401 custom ANTHROPIC_BASE_URLclaude code invalid api key
FAQ
Why does Claude Code return 401 right after I set a custom ANTHROPIC_BASE_URL?+
Usually the variables did not reach the shell that runs claude, or the key belongs to a different endpoint than the base URL points at. Check the environment in that shell and match key to endpoint.
Is ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN the right variable?+
ANTHROPIC_API_KEY becomes the x-api-key header; ANTHROPIC_AUTH_TOKEN becomes Authorization: Bearer. This endpoint accepts both, but ANTHROPIC_AUTH_TOKEN is the documented choice. Keep only one of them set.
The same key works in curl but not in Claude Code — why?+
The shell that runs claude has different environment state: a competing variable, a stale value, or no value at all. Check the environment in that exact shell.