How to Fix dotenv Not Loading Environment Variables in Node.js
In this tutorial, you'll learn about How to Fix dotenv Not Loading Environment Variables in Node.js. We cover key concepts, practical examples, and best practices.
The Problem
Your Node.js app uses dotenv but process.env.MY_KEY returns undefined, often because require('dotenv').config() is called too late, the .env file is in the wrong location, or the file has incorrect formatting with spaces around = signs.
Quick Fix
Call config() at the Very Top of Your Entry File
node -e "
require('dotenv').config();
console.log(process.env.MY_VAR);
"
Move require('dotenv').config() to the very first line of your entry script, before any other module imports. If another module reads process.env before dotenv loads, those values will be undefined.
Specify the .env File Path Explicitly
node -e "
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '.env') });
console.log(process.env.MY_VAR);
"
By default dotenv looks for .env in process.cwd(). Pass an explicit path option when your .env file lives in a different directory than where you start the process.
Check the .env File Format
node -e "
const result = require('dotenv').config();
if (result.error) {
console.error('Config error:', result.error.message);
} else {
console.log('Parsed keys:', Object.keys(result.parsed));
}
"
# Parsed keys: ['MY_VAR', 'DB_URL']
dotenv.config() returns an object with .parsed and .error fields. Inspect .error to catch formatting issues like missing quotes around values with spaces or extraneous whitespace.
Use dotenv-safe or dotenv-expand
node -e "
require('dotenv-safe').config();
console.log('All required variables present');
"
dotenv-safe throws an error if any variable listed in .env.example is missing from .env, preventing silent failures in production where missing environment variables could cause crashes.
Check Node.js and npm Versions
node --version
# v18.17.0
npm --version
# 9.6.7
Verify your runtime versions before troubleshooting module resolution or compatibility issues. Outdated versions of Node.js or npm are a common source of mysterious errors. Use nvm to manage multiple Node versions side by side.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Load .env Files from Parent Directories
node -e "
const dotenv = require('dotenv');
const path = require('path');
let result = dotenv.config();
while (result.error && path.dirname(process.cwd()) !== process.cwd()) {
process.chdir('..');
result = dotenv.config();
}
console.log('Found .env in:', process.cwd());
"
For monorepos or nested project structures, walk up the directory tree to find the .env file. This is useful when your script is deeper in the project but the .env file is at the root.
Prevention
- Place
require('dotenv').config()at the very first line of your application entry point - Keep the
.envfile in the same directory as yourpackage.json - Never commit
.envto version control — add it to.gitignore - Use
dotenv-safewith a.env.examplefile to document required variables
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro