skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. You wrote:

    nodemon --exec 'node --env-file=.env index.js'
    

    But, you’ll want the index.js to be outside the quotes:

    » npx nodemon --exec 'node --env-file=.env' index.js
    

    Demo:

    » cat .env
    ENVIRONMENT_NAME=local
    
    » cat index.js
    console.log(process.env.ENVIRONMENT_NAME);
    
    » npx nodemon --exec 'node --env-file=.env' index.js
    [nodemon] 3.0.1
    [nodemon] to restart at any time, enter `rs`
    [nodemon] watching path(s): *.*
    [nodemon] watching extensions: js,mjs,cjs,json
    [nodemon] starting `node --env-file=.env index.js`
    local
    [nodemon] clean exit - waiting for changes before restart
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search