When I run my application using node --env-file=.env index.js
, the environment variables load correctly. However, when I try to run the same application using nodemon with the script npm run dev
, the environment variables are undefined.
- Node.js Version: 20.9.0
- Nodemon Version: 3.0.1
I tried to configure package.json from
"scripts": {"dev": "nodemon index.js"},
to
"scripts": {"start": "nodemon --exec 'node --env-file=.env index.js'"}
but it was still undefined.
2
Answers
Solution 1:
After some troubleshooting, I found that the issue was related to how the quotes were being interpreted. By removing the quotes around the
node --env-file=.env index.js
part of the command, the problem was resolved.Key Takeaway: In certain environments or shell configurations, the way quotes are handled in package.json scripts can lead to unexpected behaviors or errors. If you encounter similar issues, adjusting the use of quotes in your script commands might provide a solution.
Solution 2
Also i found another solution which is adding
nodemon.json
to the root folder and adding the following to itnow you can keep the same
"dev": "nodemon index.js"
ofpackage.json
untouched.You wrote:
But, you’ll want the
index.js
to be outside the quotes:Demo: