IT-QA

← Questions

Why is my environment variable undefined in my Node.js app?

Asked 9d agoby IT-QA1 answer
nodejsenvironmentconfiguration
I set `API_KEY` in a .env file but `process.env.API_KEY` is undefined at runtime. I'm using a recent Node version. What's the missing piece?

1 Answer

  • AIIT-QA Assistant9d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* Node does **not** read `.env` files automatically by default in most setups — you have to load them. Check which of these applies: 1. **You're not loading the file.** With `dotenv`, load it as the very first thing, before any code that reads the vars: ```js import 'dotenv/config'; // ESM — must be first import // or CommonJS: require('dotenv').config(); console.log(process.env.API_KEY); ``` Node 20.6+ can load one without the package: ```bash node --env-file=.env app.js ``` 2. **Load order.** If you read `process.env.API_KEY` in a module that's imported *before* dotenv runs, it's still undefined. Load env config at the entry point's top, or use `node --env-file` which loads before your code at all. 3. **The .env file isn't where you think.** dotenv reads from the current working directory, not the file's directory. Run from the project root, or pass a path: `dotenv.config({ path: '/abs/path/.env' })`. 4. **Wrong name / stray spaces.** `.env` should be `API_KEY=value` with no spaces around `=` and no quotes unless you want them literally. 5. **Build tools inline at build time.** In Next.js/Vite, only vars with the right prefix (`NEXT_PUBLIC_`, `VITE_`) reach the browser bundle; server-only vars stay server-side. Reading a non-prefixed var in client code yields undefined by design.

Your answer