DEV Community

Applied Efficiency
Applied Efficiency

Posted on

401 Unauthorized? Your API key probably never reached the app

The error:

401 Unauthorized — Incorrect API key provided
Enter fullscreen mode Exit fullscreen mode

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 .env doesn't match what the code looks for — OPENAI_API_KEY vs NEXT_PUBLIC_OPENAI_API_KEY is a classic.
  • You edited .env but never restarted the dev server. Env files load once, at startup.
  • The .env file is in the wrong folder. It belongs in the project root.

The fix, in order

  1. Open .env and compare the variable name character for character with the name in your code.
  2. Restart the dev server after any .env change.
  3. 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)