.env variables not loading? (And how to fix it)

Chetan YadavChetan Yadav
2 min read

I’m learning backend development, and today I faced a frustrating error.

Here’s my project’s folder structure:

root_directory
├── .vscode
├── node_modules
├── src
│   ├── db
│   │   └── index.js
│   ├── models 
│   ├── app.js
│   ├── constants.js
│   └── index.js
├── .env
├── .gitignore
├── .prettierignore
├── .prettierrc
├── package-lock.json
└── package.json

When I ran my project, I saw an error. I took help from ChatGPT and found that my .env variables were not actually loading.

As you can see in the code snippet below, we get undefined when trying to print the MongoDB URI. I checked my .env variables and found that they were correct. Then I checked the path of the .env file (relative to index.js) and thought it was also correct.

After checking a few things, I changed the path and suddenly, my project started working. But I didn’t know the exact reason, because the path was not relative to the index.js and was still working fine.

Then I asked ChatGPT about this, and it explained it clearly, but before that, GPT also suggested checking the path relative to the index.js (entry file).

What ChatGPT explained:

dotenv.config() doesn't care where the JS file is.
It only looks relative to the folder where you run the command (
node src/index.js).

“dotenv.config({ path }) is relative to the current working directory (CWD), not the file’s location."

Analogy:

Think of dotenv.config({ path: "./.env" }) like asking:

“Hey Node, where are we standing right now?”

Node replies: “We’re standing in /root_directory, because you ran node src/index.js from here.”

So ./.env means:
➡ Look for .env file in the /root_directory folder.

❌ Wrong Path Example - relative to index.js

import { DB_NAME } from "./constants.js";
import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";

dotenv.config({
  path: "../.env",
});

console.log(process.env.MONGODB_URI); // Undefined
const app = express();

✅ Correct Path Example - relative to the working directory

import { DB_NAME } from "./constants.js";
import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";

dotenv.config({
  path: "./.env",
});

console.log(process.env.MONGODB_URI); // mongodb+srv:.........
const app = express();

I hope this was useful to you! Thanks for reading.

Since I’m still a newbie in my backend journey, please forgive any small mistakes 😊

🧡 Drop a comment if you liked it or have suggestions and consider following me!

📱 Follow me on Twitter/X → Chetany0724

10
Subscribe to my newsletter

Read articles from Chetan Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chetan Yadav
Chetan Yadav