javascriptnode.jsenvironment-variablesnodemon

Nodemon Not Loading .env Variables in Node.js 20.9.0 (undefined)


There's a built-in .env files support starting from Node.js v20.6.0 (no need for dotenv) But 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.

I tried to configure package.json from "scripts": {"dev": "nodemon index.js"}, to "scripts": {"dev": "nodemon --exec 'node --env-file=.env index.js'"} but it was still undefined.


Solution

  • 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.

    "dev": "nodemon --exec node --env-file=.env index.js"
    

    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 it

    {
        "execMap": {
          "js": "node --env-file=.env"
        }
    }
    

    now you can keep the same "dev": "nodemon index.js" of package.json untouched.