Home > Net >  Why is the ternary operator defaulting to true
Why is the ternary operator defaulting to true

Time:08-03

I have the following bit of code:

const production = process.env.PRODUCTION
console.log(production)

const corsOptions = {
    origin: production ? 'https://myproductionurl' : 'http://localhost:3000',
    credentials: true
}

console.log(corsOptions)


app.use(cors(corsOptions))

When I run this code the first console.log is returning false as desired however the second console.log statement is returning the production URL as if the variable is true.

Not sure why this is if someone spots something then please let me know!

Furthermore, if I remove the ternary and URLs to test what's going on then i will get origin: false in the corsOptions which is stumping me even more!

CodePudding user response:

Environment variables are always strings, unless they aren't set in which case they will be undefined.

If it is logging false, then you have set it to the string "false" which is a truthy value.

You can test for that explicitly:

production !== 'false' ? 'https://myproductionurl' : 'http://localhost:3000',

… although you should probably write a test that is more robust than that such as:

const isProduction = () => {
    const env = process.env.PRODUCTION; 
    if (!env) return false;
    if (env === "false") return false;
    return true;
}

and then

isProduction() ? 'https://myproductionurl' : 'http://localhost:3000',

CodePudding user response:

Update your ternary logic

const env = process.env.PRODUCTION
console.log(env)

const corsOptions = {
    origin: env == "production" ? 'https://myproductionurl' : 'http://localhost:3000',
    credentials: true
}

console.log(corsOptions)


app.use(cors(corsOptions))

CodePudding user response:

Because all environment variables are strings. And string that is false does not have boolean value of false, therefore the ? just see string that contains some characters => therefore resolving it as true.

const production = 'false'
const productionBool = false
console.log(production)

const corsOptions = {
    origin: production ? 'https://myproductionurl' : 'http://localhost:3000',
    originBool: productionBool ? 'https://myproductionurl' : 'http://localhost:3000',
    credentials: true
}

console.log(corsOptions)

You can resolve it i.e. by (String(production).toLowerCase() === 'true')

  • Related