TroubleshootingBeginner

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.

8 minBeginner

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.

VS Code - explorer
Explorer
.env
package.json
index.js
src/
.env
1OPENAI_API_KEY=sk-proj-real-key-here
2# no quotes, no spaces around the equals sign
The .env file sits next to package.json at the project root.

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.

index.js
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.

zsh - check
$node index.js
key loaded: false
Fix: remove the quotes in .env, then rerun
$node index.js
key loaded: true
$

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.

Never commit .env
Add .env to .gitignore before your first commit. A committed key gets scanned and revoked within minutes by automated bots.

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

Tags
#env vars#dotenv#api keys#configuration