Troubleshooting · Claude Code
Claude Code API Error 401 invalid x-api-key — Fix
Claude Code prints API Error: 401 invalid x-api-key when the key does not reach 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 x-api-key"}}Why it happens
- ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN are both set — both headers go out and the request is rejected. An empty string still counts as set. This is the most common cause when a custom base URL is involved.
- 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_BASE_URL points at one provider while the key was issued by another. A valid key sent to the wrong endpoint is still a 401.
- The key was revoked, or expired if it was issued with an expiry date.
How to fix it
- Pick one variable and unset the other: for this gateway, use ANTHROPIC_AUTH_TOKEN with ANTHROPIC_BASE_URL and make sure ANTHROPIC_API_KEY is not also exported.
- 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 and that the base URL matches the key's issuer.
Working environment for this gateway
export ANTHROPIC_BASE_URL="https://api.apitoken.sale"
export ANTHROPIC_AUTH_TOKEN="sk-pool-•••"
unset ANTHROPIC_API_KEY # must not be set at the same time
claudeRelated searches
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 both ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN are set at once, or the key belongs to a different endpoint than the base URL points at. Unset one variable 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. Use exactly one. With this gateway, ANTHROPIC_AUTH_TOKEN is the documented choice.
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.