How to Fix an API Key That Loads as Undefined
Solve the classic 'undefined API key' bug by loading your .env file correctly in Node and Python.
Your key is right but the app still says it is undefined. This is one of the most common AI setup bugs and it has nothing to do with the provider. The environment variable is simply not reaching your code, usually because the .env file is in the wrong place, loaded too late, or named incorrectly.
- A project using dotenv (Node) or python-dotenv
- A .env file with your key
- A terminal to run quick checks
Step 1: Confirm the file name and location
The file must be named exactly .env with the leading dot, and it must sit in the directory where you run the process, not a subfolder. A file called env.txt or one in src/ while you run from the root will not be found.
Step 2: Load dotenv before you read the variable
In Node, you must call dotenv config before any code reads process.env. If you import a module that reads the key at the top of the file before config runs, the value is undefined. Load it first, ideally at the very top of your entry file.
import "dotenv/config"; // must be the first import
import OpenAI from "openai";
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
console.log("key loaded:", Boolean(process.env.OPENAI_API_KEY));Step 3: Check for quotes and spaces
A key wrapped in quotes or with spaces around the equals sign can load with the quotes included or not load at all. Keep each line as KEY=value with no spaces and no surrounding quotes.
Step 4: Verify nothing else overrides it
A shell variable, a Docker env, or a deploy platform secret can override or shadow the .env value. Print the final resolved value once at startup to be sure the process sees what you expect.
Result
Once dotenv loads first and the file has clean KEY=value lines at the root, the startup log prints key loaded: true and the API call succeeds. In a frequent variant, a developer imported the OpenAI client in a separate module that ran before dotenv config, so moving the import dotenv/config line to the top of the entry file fixed it.
Watch related tutorials
1:42:18
28:14
41:09
9:47
8:23
52:31