Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
AI and LLM integration

The OpenAI Node client in Next.js cannot find OPENAI_API_KEY

ErrorThe OPENAI_API_KEY environment variable is missing or empty

Short 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.

  • Applies to Next.js 15 and 16, openai Node.js SDK 4 and later, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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));
  2. 2Match what you see, then jump to its fix

    1. 1key present: false in local developmentThe .env file is in the wrong folder or has the wrong nameFix
    2. 2The error appears in the browser console, or a client component imports the clientThe client is created in code that runs in the browserFix
    3. 3key present: false only on the hosted siteWorks locally, fails after deployFix

What does the error look like?

  • The OPENAI_API_KEY environment variable is missing or empty
  • either 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-key

3Verify

Restart the dev server and call the route again; the log line prints true.

npm run dev

Confirmed by nextjs.org

Did this fix it?

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/null

2Fix

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

Did this fix it?

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.local

2Fix

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-app

3Verify

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

Did this fix it?

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 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 fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.