Express: Unable to get cookie secure value from .env file

Created on 28 Aug 2020  路  3Comments  路  Source: expressjs/express

Hi,
I am trying to make my code work both in development and production, so I have a value in my .env file SECURE = false.
I am using this value in another location and it works fine, but when I use it as a value for the secure key in the cookie options, the cookie fails, I have to set it explicitly to false.
res.cookie('test', 'Bearer ' + token, { expires: new Date(Date.now() + 8760 * 3600000), secure: false, httpOnly: true, sameSite: 'Strict' });
I am trying to have it like this:
res.cookie('test', 'Bearer ' + token, { expires: new Date(Date.now() + 8760 * 3600000), secure: process.env.SECURE, httpOnly: true, sameSite: 'Strict' });
This same value process.env.SECURE works elsewhere in the code.

question

All 3 comments

I think that values from process.env are strings and parsing of secure in the cookie module used by express looks like this:

  if (opt.secure) {
    str += '; Secure';
  }

In such case any non-empty string fulfils this condition, so each of those options is equivalent:

  • secure: true
  • secure: "true",
  • secure: "1",
  • secure: 1,
  • secure: "false"

Proof:
eaxmples

Thank you, I understand now, it's strange since the same value was parsed as false with Nodemailer, I wonder if this is how it should be and if there is a reason behind it?

Hi @HafidAbnaou I'm glad you were able to get your answer.

As for your question regarding accepting a boolean in our APIs if you provide a string that is some kind of boolean command as it's contents: I cannot speak as to what decisions drive the Nodemailer API, but at least in our APIs we try to reduce the number of surprise by providing a type behavior that is in line with the actual JavaScript APIs that are part of the language.

As an example, Object.defineProperty takes a third argument that is an object with keys and value that are booleans, the most similar to the cookie options API in question here. That API has the same behavior as the API we are providing, resulting in a consistent experience between how JavaScript platform APIs work and our APIs. I hope that helps!

$ node
Welcome to Node.js v12.18.3.
Type ".help" for more information.
> o={}
{}
> Object.defineProperty(o,'foo',{configurable:'false'})
{}
> Object.getOwnPropertyDescriptor(o,'foo')
{
  value: undefined,
  writable: false,
  enumerable: false,
  configurable: true
}
Was this page helpful?
0 / 5 - 0 ratings