Skip to content
Nilay Kabariya

Entry No.020·AI·Updated ·7 min read

Fix: The OPENAI_API_KEY environment variable is missing or empty

OpenAI's SDK or Codex CLI says your key is missing, though it's in .env. Every wording and its fix, plus the 401 you get when an old key wins.

What changed on Nov 8, 2026: Re-ran on openai 7.53.0 / 3.46.0 and Codex CLI 0.167.0: unchanged.

The error, verbatim

Jump to the fix ↓
OpenAIError: The OPENAI_API_KEY environment variable is missing or empty; either provide it,
or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

# the same error in newer versions of the SDK:
OpenAIError: Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`,
or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.

# Python, openai 3.x:
openai.OpenAIError: Missing credentials. Please pass an `api_key`, `workload_identity`, `admin_api_key`,
or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.

# OpenAI's Codex CLI, with a provider that reads the key from the environment:
ERROR: Missing environment variable: `OPENAI_API_KEY`.
✓ Reproduced on Windows 11 Pro; Ubuntu on GitHub Actions

The fix that worked

Load it before creating the client:

import 'dotenv/config';
Not it? Every cause, tested ↓

Tested on

openai (JS)
4.104.0, 7.23.0, 7.47.0, 7.53.0
openai (Python)
1.109.1, 3.19.2, 3.42.1, 3.46.0
dotenv / python-dotenv
18.0.3, 18.0.9 / 1.2.3, 1.2.4
Codex CLI
0.158.0, 0.166.0, 0.167.0
Runtime
Node 24.14.0, Python 3.14.5
OS
Windows 11 Pro; Ubuntu on GitHub Actions

✓ Last re-run on GitHub Actions · see the run · all repros

The key is in your .env file, and the SDK still says it’s missing. Almost always, that’s because nothing ever read the file. A .env file is just a text file: the SDK reads process.env (or os.environ), and something has to copy the file into it first.

If the key does load but OpenAI answers 401 Incorrect API key provided, an older key is probably winning over your .env: see that section.

Which wording you have

OpenAI has reworded this error, so what you see depends on the SDK version, and the Codex CLI has its own. They all mean the same thing:

SDK Message starts with
JavaScript 4.x The OPENAI_API_KEY environment variable is missing or empty
JavaScript 7.x Missing credentials. Please pass an apiKey…
Python 1.x The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable
Python 3.x Missing credentials. Please pass an api_key, workload_identity, admin_api_key…
Codex CLI Missing environment variable: OPENAI_API_KEY (it has its own section below)

The fix

Load the .env file before creating the client.

JavaScript, as the very first line of your entry file:

import 'dotenv/config';
import OpenAI from 'openai';

const client = new OpenAI();

Or skip the package entirely and let Node read the file (Node 20.6+):

node --env-file=.env app.mjs

Python, before the client is created:

from dotenv import load_dotenv
load_dotenv()

from openai import OpenAI
client = OpenAI()

When it still fails: you ran it from another folder

This is the version that survives the fix above. dotenv looks for .env in the folder you ran the command from, not the folder your script lives in. Run node src/app.mjs from one level up, or start it from an editor that uses a different working folder, and it finds nothing.

It doesn’t fail loudly, either. dotenv 18.0.3 printed one line, and the number is the clue:

◇ injected env (0) from .env

(0) means it found no .env where it looked. When the file is found you’ll see (1) or more. On dotenv 18.0.9, import 'dotenv/config' printed nothing, found or not, so with that import there’s no clue on a current install: the client just fails with “Missing credentials”. Calling dotenv.config() yourself still printed the line (◇ injected env (1) from .env in a November 2 run).

Point dotenv at the file next to the script instead of the current folder:

import dotenv from 'dotenv';
import { fileURLToPath } from 'node:url';

dotenv.config({ path: fileURLToPath(new URL('.env', import.meta.url)) });

In the Codex CLI: “Missing environment variable”

The Codex CLI prints a shorter version, and the cause is different:

ERROR: Missing environment variable: `OPENAI_API_KEY`.

It appears when Codex’s config.toml uses a model provider that takes its key from an environment variable, the kind of setup that config tools and Azure or gateway presets write:

model_provider = "openai-key"

[model_providers.openai-key]
name = "OpenAI with an API key"
base_url = "https://api.openai.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "responses"

The name in the message is whatever env_key says. With env_key = "AI_GATEWAY_API_KEY", the same run printed Missing environment variable: `AI_GATEWAY_API_KEY`. So read the name in your error, and set exactly that variable.

If Codex stops earlier, with Error loading config.toml, the file itself didn’t load: see Codex: Error loading config.toml, each message and its fix.

Set the variable in the terminal you start Codex from. In PowerShell:

$env:OPENAI_API_KEY = "sk-..."
codex

In bash or zsh:

export OPENAI_API_KEY="sk-..."
codex

Or put it in a .env file in Codex’s own folder, the one CODEX_HOME points to (.codex in your user folder unless you’ve moved it), not in your project:

OPENAI_API_KEY=sk-...

Without a custom provider, a missing key looks different: the default setup kept retrying with 401 Unauthorized and “Missing bearer or basic authentication in header”. That’s Codex with no sign-in and no key at all.

401 Incorrect API key provided: an old key beats your .env

Once the key loads, the request can still be rejected. You paste a fresh key into .env, and OpenAI still says it’s incorrect:

AuthenticationError: 401 Incorrect API key provided: sk-old-s*****************1111.
You can find your API key at https://platform.openai.com/account/api-keys.
code: invalid_api_key | type: invalid_request_error

# Python:
openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-old-s*****************1111. ...

Before you regenerate the key again, read the error closely, because it tells you exactly which key was sent.

OpenAI echoes the key it received: the first 8 characters and the last 4, with the middle masked. Compare those 12 characters with the key in your .env:

  • They don’t match → your code sent a different key than the one in .env. An older key set somewhere else is winning.
  • They match → the key itself is wrong: mistyped, revoked, or from a different organisation or project. Create a new one in the OpenAI dashboard.

If OPENAI_API_KEY is already set in your environment (from your system settings, your shell profile, or an old setx), loading .env does not replace it:

How .env is loaded Shell already has an old key Key actually sent
import 'dotenv/config' (JS) yes the old one
node --env-file=.env yes the old one
load_dotenv() (Python) yes the old one

In every case the request went out with the old key, and the 401 showed its first and last characters, not the new key’s. You can regenerate keys all day and paste each one into .env, and none of them is ever used.

Option 1: let .env win. Tell the loader to overwrite what’s already set.

// JavaScript
import dotenv from 'dotenv';
dotenv.config({ override: true });
# Python
from dotenv import load_dotenv
load_dotenv(override=True)

Option 2: remove the old key at its source, so there’s only one. Check whether one is set:

echo $env:OPENAI_API_KEY      # PowerShell
echo %OPENAI_API_KEY%         # Command Prompt
echo $OPENAI_API_KEY          # macOS / Linux

If it prints a key, find where it’s defined. On Windows that’s usually Start → “Edit the system environment variables” → Environment Variables; on macOS or Linux, your shell profile (~/.zshrc, ~/.bashrc). Delete it there, then open a new terminal and restart your editor, because running programs keep the environment they started with.

In browser code

Reading the key in browser code (a Vite or React app) fails differently: process doesn’t exist there at all, and the key should not be in the browser anyway. See ReferenceError: process is not defined in Vite.

How this was tested

A project with a .env holding a test key, run with the OpenAI SDK in JavaScript (4.104.0 and 7.23.0) and Python (1.109.1 and 3.19.2) on Windows 11. Each cause was produced on purpose: no loader at all, and loaders run from a different folder. Every message above is the SDK’s real output. No real API key was used; the test key was invented, and this error happens before any request is sent. The Codex CLI 0.158.0 runs used a separate, empty CODEX_HOME folder with the provider config shown above.

November 2, 2026: re-run on GitHub Actions ubuntu-latest with openai 7.47.0 (JavaScript, Node 24.22.1), openai 3.42.1 (Python 3.14.4), dotenv 18.0.9, python-dotenv 1.2.4 and Codex CLI 0.166.0. The error wordings and every fix above held. Two things changed: import 'dotenv/config' no longer printed its injected env line (a direct dotenv.config() call still did), and Codex with the invented key retried the connection instead of showing the 401. The script and output are public, and still use only an invented key.

The 401 section: the OpenAI SDK in JavaScript (7.23.0) and Python (3.19.2) on Windows 11, calling the real API with invented test keys: one in .env and a different one set in the shell. Each loader (dotenv, node --env-file, python-dotenv) was run with and without the override. No real key was used; every result is OpenAI’s actual 401 response, and the key characters shown are from the invented test keys. November 2, 2026: every row of the table was re-run on GitHub Actions ubuntu-latest with openai 7.47.0 (Node 24.22.1) and 3.42.1 (Python 3.14.4), dotenv 18.0.9 and python-dotenv 1.2.4, using two invented keys: an “old” one exported in the shell and a “new” one in .env. OpenAI rejected both, and each 401 showed which was sent: dotenv/config, --env-file and load_dotenv() all sent the old key (sk-old-k…1111), and override: true / override=True sent the new one (sk-new-k…2222). The script and output are public.

November 9, 2026: re-run with openai 7.53.0 (JavaScript) and 3.46.0 (Python), dotenv 18.0.9 and python-dotenv 1.2.4, and Codex CLI 0.167.0 (run 42515036571, run 42515031273): the same messages, the same loader behaviour (.env read only from the current folder, and an old shell variable winning unless you pass override).

— N.K., end of entry No.020

Useful? Pass it on:Post on XFollow @EmotionalMatter

Related entries

  1. No.088

    Responses.create() unexpected keyword argument: new names

    max_tokens, messages, response_format, seed: their names in OpenAI's Responses API, tested. Plus the 'proxies' TypeError from httpx 0.28.

    > TypeError: Responses.create() got an unexpected keyword argument 'max_tokens'

    AI6 min
  2. No.089

    module 'openai' has no attribute 'ChatCompletion', tested

    AttributeError: module 'openai' has no attribute 'ChatCompletion', or 'no longer supported in openai>=1.0.0'. Five SDK versions tested.

    > AttributeError: module 'openai' has no attribute 'ChatCompletion'

    AI4 min
  3. No.087

    Claude SDK: unexpected keyword argument temperature, betas

    Messages.create() got an unexpected keyword argument after an anthropic upgrade, plus what SDK 2.0 (October 21) breaks next. Python and TypeScript, tested.

    > TypeError: Messages.create() got an unexpected keyword argument 'temperature'

    AI5 min

tip: paste the exact error text