Warm tip: This article is reproduced from serverfault.com, please click

String comparison not working in Javascript when comparing an environment variable with a constant

发布于 2018-11-20 13:53:57

We have a simple React application, created with CRA 1.x.

We installed dotenv to use environment variables on the project and our variables are included on the .env and .env.development files like this:

.env

REACT_APP_LOGGER=LOGGER

.env.development

REACT_APP_LOGGER=NO_LOGGER

Then in the code we have this logic:

if(process.env.REACT_APP_LOGGER === "LOGGER") {
    // do something
}

On local builds with webpack 4 in development mode the if is true, and on production mode is false.

But on azure, in both cases is false

process.env.REACT_APP_LOGGER === "LOGGER" // false

We have checked the value of process.env.REACT_APP_LOGGER and it is "LOGGER" type of string but the code is returning weird values:

console.log(process.env.REACT_APP_LOGGER)
console.log(process.env.REACT_APP_LOGGER === "LOGGER")
console.log(process.env.REACT_APP_LOGGER == "LOGGER")
console.log(typeof process.env.REACT_APP_LOGGER)

This is the output generated by the previous code:

LOGGER
false
false
string

Is there something I´m doing wrong? The weird part is that we have other string comparisons like this one and they are comparing correctly.

process.env.NODE_ENV === "production" // true 

EDIT: When we look at the transpiled code we see the following:

console.log("LOGGER"),
console.log(!1),
console.log(!1),
console.log(f("LOGGER"));

So I guess that means the comparison is done during build time (and as this is a constant it makes sense).

Questioner
Miguel Angel
Viewed
0
Miguel Angel 2019-01-31 05:00:09

The solution was pass both to stringify, like this:

JSON.stringify(process.env.REACT_APP_LOGGER) === JSON.stringify("LOGGER")

In this way, we could cast both variables in the same string format, both have the same length and both have the same value, but environment variables injected by Azure Process are not the same.