Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access variable from .env file in JS

When I try to console.log DOG, I got Undefined to console.
I installed npm install dotenv.

dotenv version: 16.3.1
node version: v18.16.0

index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

require('dotenv').config();

console.log(process.env.DOG)

.env

DOG=16

My structure is:

  • examples
    • index.js
  • node_modules
  • .env
  • package.json
  • package-lock.json

So, env file is not in the same folder as index.js, it is one folder outside.

I also tried in index.js:

require('dotenv').config(); 
const dog = process.env.DOG
console.log(dog)

but nothing. Although, nothing should change in this way.

It is like, index.js cannot read from .env or cannot find it.

>Solution :

The default behavior is to look for .env in the process’s working directory.

If your working directory is the directory where .env is and you run node examples/index.js, it should work.

If your working directory is examples/ and you run node index.js, it won’t work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading