The error:
401 Unauthorized — Incorrect API key provided
Your first instinct is to regenerate the key. Don't — yet. Nine times out of ten the key itself is fine. The app just never saw it.
Why it happens
- The variable name in your
.envdoesn't match what the code looks for —OPENAI_API_KEYvsNEXT_PUBLIC_OPENAI_API_KEYis a classic. - You edited
.envbut never restarted the dev server. Env files load once, at startup. - The
.envfile is in the wrong folder. It belongs in the project root.
The fix, in order
- Open
.envand compare the variable name character for character with the name in your code. - Restart the dev server after any
.envchange. - Confirm the key is active on the provider's dashboard — and never paste a real key into a public repo or a chat.
Paste this to your AI instead of the key
"I'm getting a 401 from the API. Walk me through checking that my environment variable is named exactly what the code expects and loaded at server start. Don't ask me to share the key itself."
That last line matters — never paste a real key into an AI chat either.
This is pattern #2 from the Debug Clinic in Last20 Academy — a finish school for people learning AI and vibe coding, where the next lesson stays locked until you ship.
Top comments (0)