components icon indicating copy to clipboard operation
components copied to clipboard

All variables in dotenv file are converted to string type

Open yugasun opened this issue 3 years ago • 5 comments

I found serverless cli using dotenv to parse .env file, but dotenv will convert all variables to string, if I config number type in .env for example PORT=3306, then my mysql connection will throw port unknow error.

Ralative issue: https://github.com/motdotla/dotenv/issues/51

Maybe we can do like dotenv-parse-variables to keep type of variables in .env.

yugasun avatar Sep 03 '20 11:09 yugasun

@yugasun by design env variables can only be strings, you cannot set at CLI level a number value, it's also only strings that you can store at process.env in Node.js (if you try to assign number, it'll be coerced to string).

Also recommended (and imo the only valid) use of dotenv is to at begin of program initialization transport all env vars from .env to process.env, and after that read them only from process.env (technically weather we're relying on dotenv or not, should be transparent to our app logic. It's the process.env that should be treated as the only source of truth)

In light of above, real fix for that issue, is to coerce PORT value to number before passing it to mysql connection constructor.

medikoo avatar Sep 03 '20 11:09 medikoo

Yeah, we can not append number type to process.env, maybe we can append all variables in .env as a JSON object, then we can parse ${env:xx} from this json object?

yugasun avatar Sep 03 '20 11:09 yugasun

Yes, technically you can store stringified JSON as env var, and then resolve it when needed.

I'm not sure exactly what problem we're trying to solve (?) Where is this mysql connection setup which raises issues?

medikoo avatar Sep 03 '20 12:09 medikoo

@medikoo It's just an example, the key point is user want to keep the type of variables in .env config.

yugasun avatar Sep 03 '20 12:09 yugasun

@medikoo It's just an example, the key point is user want to keep the type of variables in .env config.

Ok, then the only way is serialization to string and unserialization.

medikoo avatar Sep 03 '20 12:09 medikoo