Yarrow
← All fixes

401 Unauthorized / invalid API key even though the key is set

#144
nodepythonvitenextjsvercelshared by unknownNov 17, 2026

Error

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 yet
0 worked0 didn't
Tried it yourself?

Related fixes