Tim Hardy
Tim Hardy

Reputation: 1737

NodeJs and Dotenv - Running nodemon does not find .env file in src folder

I've got a pretty standard Nodejs setup using dotenv with my server.js file sitting in an src folder, a .env file sitting right next to it, along with a bin/www.js file. Ever since I started using dotenv, running all of the following no longer work...

nodemon (from the root of my repo)
npm start
nodemon src/server
nodemon src
etc

All fail and none of my environment variables get loaded properly. I have to go to the actual src folder and run "nodemon server.js" at that exact location. This poses problems for some of the build environments I used to use and some of my previous cloud setups like heroku. I thought having the .env file in the same folder as my server.js file would always work, but it does not.

Can anyone tell me why dotenv fails to find the .env file and load the environment variables depending on where I launch nodemon from, even though nodemon finds the server.js file just fine?

I basically would like to be able to launch nodemon from my repository's root folder and still have dotenv work. Also, I tried moving the .env folder into the root directory, and I still have problems.

Upvotes: 0

Views: 3814

Answers (1)

f4b1n0u
f4b1n0u

Reputation: 11

I had the same issue, I found a way to fix it, but it is not clean at all.

I noticed that

node --require dotenv/config --require babel-register ./bin/www

and

node ./bin/www --require dotenv/config --require babel-register

does not behave the same way, probably because the --require is for node not for

./bin/www

so I end up using

nodemon({
  script: '--require',
  cwd: './dist',
  tasks: [
    'dist',
  ],
  args: [
    'dotenv/config',
    '--require',
    'babel-register',
    './bin/www', // YEAH it's weird but 
  ],
  watch: [
    './src',
  ],
});

Yeah I know, it's ugly, but it works, if you have a better way to do that, just let me know :)

Upvotes: 1

Related Questions