Search code examples
javascriptnode.jsdotenv

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

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.