Fix error 401 "Incorrect API key provided" / "invalid x-api-key"
openai.AuthenticationError: Error code: 401 - Incorrect API key provided: sk-proj-****abcd
- anthropic.AuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}}
- openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable
- You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth
- 400 API key not valid. Please pass a valid API key. (API_KEY_INVALID)
The API does not recognize the key it received: it is missing, mistyped, revoked or sent in the wrong header. Check that the environment variable holds the right key, test it with curl and regenerate it if needed. Never put an API key in front-end code.
What this error means
Every request to an LLM API must prove who it is. OpenAI expects the key in Authorization: Bearer, Anthropic in the x-api-key header, Gemini in x-goog-api-key. The server compares the key with the active keys of your organization or project. If it matches none, it returns HTTP 401 (invalid_api_key at OpenAI, authentication_error at Anthropic; Gemini returns a 400 API_KEY_INVALID). When no key is found at all, the SDKs fail before the call with a message asking you to set OPENAI_API_KEY or ANTHROPIC_API_KEY. The error is not about permissions (403) or quota (429): the key itself is rejected.
Common causes
- Key copied wrong: a missing character, a space, a trailing newline or quotes included in the
.envfile. - Environment variable not loaded:
.envnever read, terminal not restarted aftersetxon Windows, or production server missing the variable. - Old key takes precedence: a variable already exported in the shell wins, because
python-dotenvdoes not override existing variables by default. - Key revoked or project deleted: key rotation, key disabled after a detected leak, archived project or workspace.
- Wrong provider or wrong header: an OpenAI key sent to Anthropic, or an Anthropic key sent as
Authorization: Bearerinstead ofx-api-key.
Step-by-step fix
-
Check the variable without printing the key
Check the length and prefix (
sk-proj-for OpenAI,sk-ant-for Anthropic) without printing the full key in a terminal or shared logs.# macOS / Linux (bash, zsh) echo "${#OPENAI_API_KEY} ${OPENAI_API_KEY:0:8}" # Windows (PowerShell) $env:OPENAI_API_KEY.Length $env:OPENAI_API_KEY.Substring(0, 8) -
Test the key directly with curl
A simple call to the models list isolates the problem: if
curlalso returns 401, the key is at fault, not your code.# OpenAI curl -s https://api.openai.com/v1/models \ -H "Authorization: Bearer $OPENAI_API_KEY" | head -c 300 # Anthropic curl -s https://api.anthropic.com/v1/models \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" | head -c 300 # Gemini curl -s https://generativelanguage.googleapis.com/v1beta/models \ -H "x-goog-api-key: $GEMINI_API_KEY" | head -c 300 -
Store the key in an unversioned .env file
One line per key, with no quotes or spaces around
=. Add.envto.gitignorebefore the first commit.# .env OPENAI_API_KEY=sk-proj-your-key ANTHROPIC_API_KEY=sk-ant-your-key -
Load the .env and remove stale values
In Python,
load_dotenv()reads the file but does not replace a variable already set in the shell: remove the old one withunset(or passoverride=Truein development). In Node.js 20.6+,--env-fileloads the file with no dependency.# Python from dotenv import load_dotenv from openai import OpenAI load_dotenv() # reads .env client = OpenAI() # picks up OPENAI_API_KEY from the environment # shell: drop a stale exported key # unset OPENAI_API_KEY # Node.js 20.6+ # node --env-file=.env server.js -
Regenerate the key if revoked or leaked
Create a new key in the provider’s console (OpenAI Platform, Anthropic Console, Google AI Studio), update it everywhere (local, CI, hosting), then revoke the old one. If the key was published on GitHub or in a JavaScript bundle, treat it as compromised.
-
Call the API from the server, never from the browser
A key placed in front-end code (React, Vue, a mobile app) is visible to any visitor. Instead, expose a route on your back end that reads the key from the environment and calls the API on the client’s behalf.
// server.js - run with: node --env-file=.env server.js import express from "express"; import Anthropic from "@anthropic-ai/sdk"; const app = express(); app.use(express.json()); const client = new Anthropic(); // reads ANTHROPIC_API_KEY app.post("/api/chat", async (req, res) => { const msg = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 1024, messages: [{ role: "user", content: String(req.body.message ?? "") }], }); const text = msg.content .filter((b) => b.type === "text") .map((b) => b.text) .join(""); res.json({ text }); }); app.listen(3000);
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Keep keys only in environment variables or a secrets manager, never in the repository or in client code.
- Turn on a secret scanner (GitHub secret scanning, gitleaks) to block commits that contain a key.
- Use one key per project and per environment, so you can revoke one without breaking everything.
Frequently asked questions
My key worked yesterday, why a 401 today?
It was probably revoked: manual rotation, deleted project or automatic disabling after a public leak was detected. Check its status in the console and create a new one.
Can I put my OpenAI key in a VITE_ or NEXT_PUBLIC_ variable?
No. Those prefixes inject the value into the JavaScript sent to the browser, so the key becomes public. Call the API from a server route.
What is the difference between a 401 and a 403 error?
401 means the key is missing or invalid. 403 means the key is valid but has no access to the requested resource (model, project or region).
Useful tools for this error
More AI & LLMs errors
- Fix error 429 "Rate limit reached" on OpenAI, Claude and Gemini APIs
- Fix "maximum context length" and "prompt is too long" (context_length_exceeded)
- Fix "CUDA out of memory" in PyTorch
- Fix "Torch not compiled with CUDA enabled" and torch.cuda.is_available() returning False
- Fix "could not connect to ollama" and connection refused on port 11434
- Fix "JSONDecodeError: Expecting value" when parsing an LLM response
- Fix "You are trying to access a gated repo" (401) on Hugging Face