Search code examples
node.jsdotenv

process.env variables not the same value as in .env config


In a recent nodejs project, I had a very strange occurrence: I set the HOSTNAME variable in my .env file, and by the time it got included in the .js file, the HOSTNAME value was different from the one in .env. Why?

--

Situation

.env

HOSTNAME=foo.bar.com

server.js

require('dotenv').config();
console.log("Hostname: ", process.env.HOSTNAME);

console output

Hostname: foo

Expected console output

Hostname: foo.bar.com

--

Debugging

  • Nodejs application is installed on a windows server 2008, where the machine's DNS entry is foo.bar.com. From the intranet, the machine is even reachable as "http://foo" (for whatever reason).
  • No other nodejs application runs on that server
  • Problem only occurs with HOSTNAME, no other variable name (at least not as far as I could find)
  • works perfectly fine if HOSTNAME=localhost and I run the application from the server browser
  • works perfectly fine if I rename HOSTNAME to _HOSTNAME (and replace all occurrences of HOSTNAME in my code)
  • works perfectly fine if I run the code on my local machine and just have a .hosts entry "127.0.0.1 foo.bar.com"

I have fixed the issue by renaming to _HOSTNAME, but I would like to know WHY this happened, and if there are other .env variable names that might be affected by this strange occurrence


Solution

  • dotenv npm library skips the variables which already set in the host environment.You can find the more information about overriding existing system variables in official documentation.

    https://github.com/motdotla/dotenv#what-happens-to-environment-variables-that-were-already-set