The OpenAI Node client in Next.js cannot find OPENAI_API_KEY
The OPENAI_API_KEY environment variable is missing or emptyShort answer
The OpenAI client reads process.env.OPENAI_API_KEY when you create it. In Next.js that value is empty if the .env file sits in the wrong folder, if the code runs in the browser where server variables do not exist, or if the host never received the variable. Move the file, keep the client on the server, set it on the host.
Fix it fast
1Find out which cause you have
Print whether the variable exists, inside the same server code that builds the client. Never print the key itself.
// app/api/chat/route.ts console.log("key present:", Boolean(process.env.OPENAI_API_KEY));2Match what you see, then jump to its fix
- 1
key present: false in local developmentThe .env file is in the wrong folder or has the wrong nameFix - 2
The error appears in the browser console, or a client component imports the clientThe client is created in code that runs in the browserFix - 3
key present: false only on the hosted siteWorks locally, fails after deployFix
- 1
What does the error look like?
The OPENAI_API_KEY environment variable is missing or emptyeither provide it, or instantiate the OpenAI client with an apiKey option
Cause 1 of 3
The .env file is in the wrong folder or has the wrong name
1Check
Next.js loads .env files from the project root. With a src folder it still reads them from the parent, not from src.
ls -a | grep '^\.env'
ls src 2>/dev/null | grep '^\.env'2Fix
Put the key in .env.local in the project root, one line, no quotes needed, then restart next dev.
# .env.local (project root)
OPENAI_API_KEY=sk-your-key3Verify
Restart the dev server and call the route again; the log line prints true.
npm run devConfirmed by nextjs.org
Cause 2 of 3
The client is created in code that runs in the browser
1Check
Variables without the NEXT_PUBLIC_ prefix exist only on the server. The OpenAI SDK also disables browser use by default to avoid exposing the key.
grep -rn "new OpenAI" app src 2>/dev/null2Fix
Create the client in a route handler or server action, and have the browser call that route. Do not prefix the key with NEXT_PUBLIC_, which would put it in the JavaScript sent to users.
// app/api/chat/route.ts (server only)
import OpenAI from "openai";
const client = new OpenAI(); // reads OPENAI_API_KEY
export async function POST(req: Request) {
const { prompt } = await req.json();
const r = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
});
return Response.json(r.choices[0].message);
}3Verify
The browser calls /api/chat and gets JSON back.
curl -s -X POST localhost:3000/api/chat -H 'content-type: application/json' -d '{"prompt":"hi"}'Confirmed by nextjs.org
Cause 3 of 3
Works locally, fails after deploy
1Check
Your .env.local is ignored by git, so the host never receives it. Look at the host's environment variable settings.
git check-ignore -v .env.local2Fix
Add OPENAI_API_KEY in the hosting dashboard (or the container's environment) for the right environment and redeploy. Read it at request time on the server, inside the handler.
docker run -e OPENAI_API_KEY=sk-your-key my-next-app3Verify
Redeploy and call the route on the live URL.
curl -s -X POST https://example.com/api/chat -H 'content-type: application/json' -d '{"prompt":"hi"}'Confirmed by nextjs.org
How do I stop it coming back?
- Commit a .env.example with the variable name and no value so every environment knows it is needed.
- Keep every OpenAI call in route handlers or server actions.
- Pass the key to the client explicitly with the apiKey option if you want the failure to name your own variable.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
AI
The OpenAI client says the API key is missing
Missing credentials. Please pass an `api_key`
OpenAI() looks for an api_key argument first and then the OPENAI_API_KEY environment variable.
3 causes, each with a fixAI
The model's reply breaks JSON.parse
SyntaxError: Unterminated string in JSON at position 1874
JSON.parse rejects model output for a few repeatable reasons: the JSON sits inside markdown fences or next to a sentence, the reply stopped at the token limit mid-object, a stream was parsed before it ended, or the model refused.
5 causes, each with a fixAI
The OpenAI API answers 429: out of credit, or just too fast?
"type": "insufficient_quota"
A 429 from the OpenAI API means one of two unrelated things.
5 causes, each with a fixAI
OpenAI API 400: image_url is only supported by certain models
BadRequestError: 400 Invalid content type. image_url is only supported by certain models.
The request carried an image part, but the model you named cannot take image input.
2 causes, each with a fixAI
Azure OpenAI says the API deployment for this resource does not exist
The API deployment for this resource does not exist
Azure OpenAI does not take a model name in the model field.
2 causes, each with a fixAI
Azure OpenAI fails with an SSL certificate verification error
httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED]
The client checks the endpoint's certificate against its CA bundle, which is certifi by default.
2 causes, each with a fix