Getting the “401 Unauthorized” error on Claude AI? Don’t panic. Here is the complete step-by-step guide to fix it immediately and get back to work.
If you are currently trying to use Anthropic’s Claude AI terminal tool or connect your favorite third-party app via the API and suddenly encounter a roadblock, you are certainly not alone. Many developers and users report seeing the specific, frustrating messages below:
JSON
API Error: 401 {"type":"error","error":{"type":"authentication_error", "message":"Invalid authentication credentials"}}
Or simply:
JSON
{"type": "error", "error": {"type": "authentication_error", "message": "invalid x-api-key"}}
This specific Claude 401 error often strikes without warning. It can appear even when your internet connection is perfectly stable and other developer tools are running without a hitch. Whether you are prompting Claude 3.5 Sonnet, running complex logic through Claude Opus, or firing rapid queries to Haiku, the error halts everything because authentication happens before the server even looks at your requested model.
While it completely disrupts your coding workflow, the good news is that this issue is entirely fixable. Furthermore, it is strictly an access and credentials issue—it rarely means you have broken your actual application logic or code syntax.

In this comprehensive guide, we will walk you through exactly what this error means, why the Claude Code CLI or API fails to authenticate, and the specific steps you must take to fix it quickly.
What Does “401 Unauthorized” Mean in Claude?
To better understand the problem, we must first define what the error actually signals.
An HTTP Status 401 message means that the server is explicitly rejecting your request because it does not recognize or accept the security credentials you provided. Think of it like a bouncer at a door; the venue is open, but your digital ID card is being rejected. According to Anthropic’s official API documentation, a 401 specifically translates to an authentication_error.
Depending on your specific environment, this authentication failure usually points to one of two triggers:
- An Expired OAuth Session: Your local terminal tool’s secure token has expired or desynced.
- An Invalid API Configuration: Your application code or UI client is passing a miscopied, mismatched, or misplaced API key.
Because this error surfaces differently depending on whether you are using the terminal-based Claude Code CLI or an application/UI client (like Cursor or Cherry Studio), we have broken the solutions down by environment to get you back up and running fast.
Why This Error Happens
Based on real usage patterns and technical analysis, this error usually stems from one or more of the specific reasons below.
1. The Claude Code CLI “Login Loop”
If you are using Anthropic’s official terminal tool (claude-code), your local machine caches an OAuth token. When this token expires or corrupted, the CLI gets stuck in a deadlock. The system instructs you to run /login or /logout, but because the underlying cache is broken, those very recovery commands fail and throw a 401 error right back at you.
2. Base URL and Proxy Mismatch
For API users, a 401 frequently happens when mixing platforms. If you copy an official API key from Anthropic (which starts with sk-ant-) but point your application’s base_url to a third-party high-availability proxy endpoint (such as api.claudeapi.com), the authentication will fail. The key and the endpoint must always match. Custom API gateways often look for a specific Authorization: Bearer or x-api-key header, and mixing them up leads directly to an authentication block.
3. Hidden Whitespace in Environment Variables
Copy-pasting an API key from a web dashboard can easily capture an invisible trailing space or newline character. When your code passes this key to the backend, the extra character invalidates the string, triggering an instant invalid x-api-key response.
4. Windows PowerShell Syntax Malfunctions
Developers moving between operating systems often mistakenly use Linux terminal syntax like export ANTHROPIC_API_KEY="..." inside Windows PowerShell. This fails silently without storing the variable properly, leaving your system to send empty credentials to the API.
5. Suspended, Revoked, or Deprecated API Keys
If you accidentally pushed your .env file to a public GitHub repository, Anthropic’s automated security scanners may have immediately revoked your compromised key. Alternatively, if your organization administrator recently rotated team keys or disabled your workspace access, your current key will instantly return a 401.
6. Stale Cache from Tools like Dotenv or Direnv
If you are using Node.js or Python environments with package managers like dotenv or shell plugins like direnv, an old project configuration might be overriding your global variables. The application might be loading a stale, previously deleted key without you realizing it.
Quick Checks Before You Try Fix
Before you dive deep into manual file deletions or rewriting code, quickly run through this diagnostic checklist to narrow down the cause and save time:
- For CLI Users: Does running
/statusthrow the same error as running a prompt? - For API Users: Does your API key string explicitly start with the correct characters designated by your provider (e.g.,
sk-ant-)? - For UI Client Users: If you test a raw
curlrequest in the terminal using the exact same key, does it still fail? - For Enterprise Teams: Is your key assigned to an organization workspace that has reached its spending limit or disabled your user profile? Check the Anthropic admin console to verify your status.
- For Mac Users: Did you recently migrate to a new machine? Apple’s Keychain migration sometimes breaks stored OAuth tokens, requiring a manual reset.
If you can isolate whether the problem is isolated to your terminal app or your overall API key, you can jump straight to the correct step below.
How to Fix Claude Error 401: Step-by-Step Guide
To resolve this efficiently, identify your environment and follow the structured steps below. We strongly recommend that you do not skip ahead, as the simpler fixes often work best.
Environment A: If You Are Using the Claude Code CLI
When the built-in /login loop blocks your recovery, you must manually nuke the local credential cache.
Step 1: Delete Local Auth Files
Bypass the CLI entirely and clear the cached state directly from your operating system’s storage location.
- Linux / WSL2 / Windows: Open your terminal and run:
rm -f ~/.claude/.credentials.json
*Note for Windows users:* In some versions, the authentication file might also be found at `$env:USERPROFILE\.config\claude-code\auth.json`. If the first command doesn't work, clear this directory as well.
* **macOS:** macOS securely stores these credentials in the **system Keychain**. You must clear both the Keychain entry and the local JSON file:
```bash
security delete-generic-password -s "claude-code" 2>/dev/null
rm -f ~/.claude/.credentials.json
Step 2: Sign In Again
With the stuck auth state completely wiped, restart the tool to trigger a clean web authentication flow:
Bash
claude
If the session does not automatically prompt you to log in, type /login to link your account smoothly.
Step 3: Verify the Connection
Run the status command inside your active interactive session to confirm the deadlock is broken:
Bash
/status
If you see your verified account info and subscription details, you are good to go.
Step 4: Fallback to Direct API Key Auth
If the web-based OAuth continues to give you trouble, you can bypass it entirely in terminal sessions by exporting your API key directly as an environment variable:
Bash
export ANTHROPIC_API_KEY="sk-ant-api03-xxxxx"
Pro Tip: If you are returning to OAuth later, remember to use unset ANTHROPIC_API_KEY to prevent this manual variable from overriding your future CLI logins.
Environment B: If You Are Using the API or Third-Party Clients
If you are seeing a red alert banner in Cherry Studio, a toast notification in Cursor, or an anthropic.AuthenticationError traceback in your Python/Node.js applications, apply these steps:
Step 1: Align Your Key and Base URL
Double-check your client configurations. If your script or UI points to an alternative endpoint like [https://api.claudeapi.com](https://api.claudeapi.com), ensure you are using a key generated from that specific dashboard—not the official Anthropic console, and vice versa.
Example of a correct, aligned Python SDK configuration:
Python
import anthropic
client = anthropic.Anthropic(
api_key="sk-YOUR-ACTUAL-KEY",
base_url="https://api.claudeapi.com" # Ensure key and URL are from the same provider
)
Step 2: Strip Invisible Spaces
If you suspect hidden formatting is breaking your key, run this diagnostic command in a Linux or Mac terminal to audit your environment variable:
Bash
echo $ANTHROPIC_API_KEY | cat -A
Look closely for any trailing spaces or odd characters before the end-of-line flag ($). If present, manually type or carefully re-paste the key string into your environment configuration without double-clicking. On macOS, you can safely pipe a newly copied key directly to your environment using: export ANTHROPIC_API_KEY="$(pbpaste | tr -d '\r\n')".
Step 3: Fix Windows PowerShell Syntax
If you are operating on a Windows machine, replace any invalid export syntax with the proper native PowerShell environmental mapping:
PowerShell
$env:ANTHROPIC_API_KEY="sk-YOUR-CLAUDE-KEY"
Note: After running this, make sure to restart your terminal or IDE (like VS Code) so it registers the new environment variable layout.
Step 4: Check for Trailing Slashes in UI Apps
If your API connection test works perfectly via a terminal curl command but repeatedly fails inside software like Cherry Studio, inspect the end of your URL string. Many third-party clients will reject the connection if there is a trailing slash. Change [https://api.claudeapi.com/](https://api.claudeapi.com/) to [https://api.claudeapi.com](https://api.claudeapi.com) and hit re-test.
Step 5: Test Raw Connectivity with cURL
If everything seems correct but the 401 error persists in your code, bypass your application entirely and test your exact key against the raw Anthropic server using curl:
Bash
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-3-haiku-20240307", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}]}'
If this succeeds, your API key is perfectly valid, and the issue lies in your app’s specific request formatting or proxy routing.
Beyond 401: Other Common Claude Errors at a Glance
Once your authentication is cleanly sorted, it helps to know how to identify other status codes if your pipeline encounters separate friction down the line. The API follows a predictable HTTP error code format:
| Status Code | Error Type | Most Common Cause | Quick Fix |
| 400 | Bad Request | Typo in model ID string (e.g., claude-opus-4). | Update to a valid 2026 model tag like claude-sonnet-4-6 or claude-opus-4-6. |
| 403 | Forbidden | Your API key lacks permission for the resource. | Check your organization policies and billing tiers. |
| 404 | Model Not Found | Selected model does not exist on your current endpoint. | Cross-reference the permitted model catalog inside your developer account. |
| 413 | Request Too Large | Context window exceeded. | Reduce prompt length or image resolution. |
| 429 | Too Many Requests | Token or request speed limits exceeded. | Implement Exponential Backoff Retry loops or upgrade your account tier. |
| 500 | API Error | Internal failure on Anthropic’s end. | Wait and try again; the issue is upstream. |
| 529 | Service Overloaded | Upstream server traffic spikes at Anthropic. | Wait 30 seconds and retry, or use multi-node routing. |
How to Prevent This Error in the Future
While you cannot control server-side adjustments, you can drastically reduce your odds of running into an unexpected 401 error again by implementing clean local habits and maintaining good “browser hygiene”:
- Keep your tools updated: Run
npm install -g @anthropic-ai/claude-code@latestregularly, as auth-flow patches and improvements ship frequently. - Sanitize environment workflows: Always store production keys securely in localized
.envfiles rather than hardcoding or relying on global system environment variables that can get corrupted. - Keep a backup key ready: For terminal operations, keep a separate, valid API key generated and stored safely so you can switch instantly if web-based OAuth nodes experience a hiccup.
- Manage team access cleanly: If working in an organization workspace, explicitly delete revoked keys rather than just disabling them to avoid local cache confusion later.
- Avoid complex login transitions: If you use Claude.ai via browser, explicit logging out is better than leaving tabs idle indefinitely, which can cause session corruption.
FAQs
Why does Claude keep telling me my credentials are invalid when I just copied them?
This almost always traces back to an endpoint mismatch. If your API key originates from one management platform and your app’s base_url target points to a proxy or relay platform, the server will flag the credential string as invalid.
How long does a Claude Code OAuth token stay active?
Session tokens expire over time or lose validity after long idle periods. If you leave your development workspace inactive for several days, the token may expire naturally, requiring a quick deletion of your ~/.claude/.credentials.json file to log back in cleanly.
Can a 401 error mean my Claude account has been banned?
No. An account restriction or ban typically triggers a distinct, explicit 403 Forbidden error policy message. A 401 simply means the data sent failed the baseline cryptographic handshake check.
Is Claude blocked in some countries, and can VPNs cause this error?
Yes, access varies by region. Security services and certain VPN routing can trigger request failures or block your OAuth login flow entirely if the IP address has a bad reputation or mimics a proxy mismatch, leading to unexpected auth errors. Temporarily disabling your VPN can clarify if this is the cause.
What is the difference between “invalid x-api-key” and “OAuth token expired”?
They are both 401 errors but occur in different flows. invalid x-api-key is generated by the developer API when a hardcoded API key is rejected. OAuth token expired happens exclusively in authenticated tools like the Claude Code CLI or the Claude.ai web app when your temporary login session times out.
Related Claude Error Guides
If you are dealing with other issues across the Claude ecosystem, check out our dedicated troubleshooting resources:
- How to Fix “This Isn’t Working Right Now” Error in Claude AI
- How to Fix “There Was an Error Logging You In” in Claude AI
- How to Fix Claude Overloaded Error: Complete Guide
- How to Fix API Error 500 (Internal Server Error) in Claude Code
- How to Fix Claude Conversation Not Found Error
- How to Fix Claude Code Process Exited With Code 1 Error
What to Do If Nothing Works
If you have cleared your credential files, validated your proxy paths, scrubbed your trailing whitespaces, and the 401 error persists across multiple networks, check the Official Anthropic Status Page.
During intense server strains or backend routing updates, authentication gateways can occasionally experience localized dropouts. If an outage is underway, continuous rapid re-attempts won’t speed up recovery and may trigger an added 429 rate limit, making the experience more frustrating. We recommend you step away for 15 minutes, allow the infrastructure to stabilize, and try running your scripts again once conditions return to normal. In the majority of cases, these broader outages resolve without any action required on your end, allowing you to get back to creating with Claude AI seamlessly.
Visit Our Post Page: Blog Page
