The symptom

You set API_KEY in .env. Your code reads it and gets undefined, empty, or the literal string undefined.

The usual causes

Nothing is loading the file. .env is a convention, not a language feature. Something must read it — a library you call at startup, or your framework doing it for you. If nothing does, the file is just a text file.

It's loaded too late. The load call must run before any code that reads the variable, including imports at the top of other files that execute on import.

Wrong name. Case matters. API_KEY and api_key are different variables.

Quoting or spaces. KEY = value with spaces around the equals, or quotes that end up as part of the value.

Browser code. Environment variables are a server concept. Frontend build tools only expose variables with a specific prefix — NEXT_PUBLIC_, VITE_ — and anything they expose is public to everyone.

Not set on the host. Your .env is gitignored, correctly, and therefore never deployed. Production variables go in the host's settings.

The fix

env-debug.txt
My env var <NAME> is undefined at runtime. Stack: <stack>.
Here's how I load and read it: <paste both>

Check, in order:
- Is anything actually loading the .env file, and does that run before
  the read?
- Is the file in the directory the app runs from?
- Is the name and syntax exactly right?
- Is this code running in the browser, where env vars don't exist
  unless the build tool exposes them?

Then show me a one-line startup check that fails loudly if a required
variable is missing.

Add the startup check

The best fix is not needing to debug this again. Check every required variable when the app starts, and exit with a clear message naming what's missing. A crash at boot saying "API_KEY not set" beats a mysterious failure an hour later.

Never log the value to debug this — log whether it's set and how long it is. That answers the question without putting your key in a log file.