OpenAI API 401: Incorrect API key provided
401 Incorrect API key provided: sk-proj-****. You can find your API key at https://platform.openai.com/account/api-keys.In one sentence: OpenAI rejected the key your app sent: it's missing, wrong, revoked, or not being loaded.
What it means
A 401 means "not authenticated." OpenAI received your request but the API key in it isn't valid.
Note that running out of credit is a different error (429 insufficient_quota), so a 401 is about the key itself.
Common causes
- The env variable holding the key isn't loaded, so an empty or `undefined` key is sent.
- The key was copied with a missing character, extra space, or quotes.
- The key was revoked or deleted (OpenAI also auto-revokes keys it detects leaked publicly, e.g. pushed to GitHub).
- The key belongs to a different project/organization than the one you're specifying.
How to fix it
- Create a fresh key at platform.openai.com/api-keys and paste it carefully into `OPENAI_API_KEY`.
- Restart the dev server, and add the key to your host's environment variables, then redeploy.
- Call OpenAI only from server code. Never expose the key in the browser or with a `NEXT_PUBLIC_` prefix.
- If the key was ever committed to git, revoke it and make a new one.
Example
// app/api/chat/route.ts (server only)
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
if (!process.env.OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");Prompt to paste into your AI tool
OpenAI returns 401 Incorrect API key. Make sure the key is read from OPENAI_API_KEY on the server only, fail with a clear message if it's missing, and never send it to the browser.Still stuck?
Paste your exact error and code. Get a plain-English explanation free, or the full fix for $5.
Related errors
- TypeError: Cannot read properties of undefined
- CORS error: blocked by CORS policy
- Hydration failed: server HTML didn't match the client (Next.js)
- Module not found: Can't resolve '...'
Weekly: the errors breaking vibe-coded apps and how to fix them. Free.
No spam. Unsubscribe anytime.