Search code examples
npmenvironment-variableschaidotenv

environmental variable not being read (NPM)


So I have a project running with nodejs, and an env file using multiple variables. For some reason one of these does not seem to be working though.

Here the code should be printing out the port and namespace/ip of that the env file should have specified

      `==> API is running on port ${process.env.API_PORT}`,
      '\n',
      `==> Send requests to http://${process.env.API_HOST}:${process.env.API_PORT}`

But for some reason it is only finding the host, as this is what the console actually outputs

 ==> API is running on port undefined
 ==> Send requests to http://127.0.0.1:undefined

Here is the .env file entries for these two variables

API_PORT=8080

API_HOST=127.0.0.1

The only guidance I have found so far was that I had to include require('dotenv').config(); but this did not resolve anything either.

What could be blocking the API_PORT variable?

UPDATE: So it seems when I host the server using npm, it works, but when I try to run code coverage over it using chai is when this error pops up (still npm run test).


Solution

  • Fast solution at the moment in your package.json

    Put your envs in your scripts

    "scripts": {
        "dev": "API_PORT=8080 API_HOST=127.0.0.1 node index.js",
        "test": "your script here"
     },
    

    npm run dev should work fine.