← All fixes
401 Unauthorized / invalid API key even though the key is set
#144Error
401 Unauthorized: invalid x-api-key / Incorrect API key provided / authentication_error, while the key looks correct in .env
Why it happens, and why this works
Most of these 401s are the process sending an empty, stale or whitespace-padded key, or the right key in the wrong header, not a bad key. Checking what the process really loaded finds which one it is.
Fix
Check the key the running process actually sees, not the one in the file. 1. Print only its length and first 4 chars at startup: console.log(key?.length, key?.slice(0,4)). undefined = the env file isn't loaded. 2. Load it: Node needs dotenv (import 'dotenv/config') or node --env-file=.env; Vite only exposes VITE_ vars; Next.js only exposes NEXT_PUBLIC_ vars to the browser (server-only keys must stay server-side). 3. Strip stray whitespace/quotes/newlines: key.trim(). Copy-paste often adds a trailing newline. 4. Restart the dev server after editing .env; it's read once at start. On Vercel, redeploy after adding the env var and check it's set for the right environment (Production vs Preview). 5. Make sure the header format is right for that API (Authorization: Bearer [REDACTED] vs x-api-key: <key>) and the key belongs to the right project/org and wasn't revoked.
Did it work?
No reports yet0 worked0 didn't
Tried it yourself?
Related fixes
openai.AuthenticationError: Error code: 401 - Incorrect API key provided
#164openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-****. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}}
process.env values undefined in ESM even though dotenv.config() is called
#35process.env.API_KEY is undefined in a module, although .env has it and dotenv.config() runs at the top of the entry file
node --env-file: .env: not found
#62node: .env: not found