Fix Claude Code Failed to Authenticate
The "failed to authenticate" error in Claude Code means your credentials are missing, expired, or misconfigured. This guide walks through every authentication method Claude Code supports and shows you exactly how to fix each failure mode.
The Problem
You launch Claude Code or run a command, and it immediately returns a "failed to authenticate" error. This blocks all AI-assisted work. The error can appear after system updates, token expiration, environment variable changes, or when switching between authentication methods.
Quick Solution
- Check which authentication method you are using:
claude config list - If using an API key, verify it is set correctly:
echo $ANTHROPIC_API_KEY - If the key is missing or empty, set it:
export ANTHROPIC_API_KEY="sk-ant-your-key-here" - If using OAuth (Claude Max subscription), re-authenticate:
claude auth login - Test the connection:
claude "hello"
How Authentication Works
Claude Code supports multiple authentication paths. The most common is the ANTHROPIC_API_KEY environment variable, which sends your key directly with each API request. When this variable is unset, empty, or contains an invalid key, authentication fails immediately.
OAuth-based authentication through claude auth login stores tokens in ~/.claude/. These tokens expire periodically and must be refreshed.
For enterprise setups using Amazon Bedrock or Google Vertex AI, authentication flows through AWS IAM or GCP service accounts respectively.
Common Issues
Token expired after sleep or restart. OAuth tokens have a limited lifetime. Run claude auth login again. To prevent this, add export ANTHROPIC_API_KEY=... to your shell profile (~/.zshrc or ~/.bashrc) so it persists across sessions.
Wrong API key format. Anthropic API keys start with sk-ant-. If your key does not match this format, you may be using a key from a different provider.
Environment variable overridden by dotenv. If your project uses .env files, an empty ANTHROPIC_API_KEY= line will override your shell export. Check all .env files in your project hierarchy.
Best Practices
- Store your API key in your shell profile (
~/.zshrcor~/.bashrc) so it survives terminal restarts. - Never commit API keys to version control. Use
.env.localfiles that are listed in.gitignore. - Use separate keys for development and production to isolate rate limits and track usage independently.
- Set up a pre-commit hook that scans for accidentally committed secrets using tools like
gitleaks. - For team environments, use OAuth rather than shared API keys so each developer has their own authentication context.
Paste your error into our Error Diagnostic for an instant fix.
Master Claude Code
Get lifetime access to all ClaudHQ tools, advanced workflows, and production-grade templates.
Get Lifetime AccessWritten by the ClaudHQ team ยท Expert Claude Code guides and tools