A simple trick for your dotenv files
Victor Ocnarescu

Victor Ocnarescu @victorocna

About: 11+ years of experience tangled in the world wide web.

Location:
Europe
Joined:
Sep 29, 2018

A simple trick for your dotenv files

Publish Date: Mar 4 '23
0 1

I'm sure most of you know and use dotenv files. They are great for storing app configs: everything that is likely to vary between deploys

MY_APP_KEY=supersecret
Enter fullscreen mode Exit fullscreen mode

These app configs are stored in a convenient key/value pair in a dotenv file. But what may come as a surprise to you is that every value is a string

DAYS_UNTIL_DATA_DELETION=60
AWS_DISABLE=true
Enter fullscreen mode Exit fullscreen mode

Both are in fact strings. Later on, when you will want to check if AWS is disabled, you will have to write this code (which I have seen over and over again in many projects)

if (process.env.AWS_DISABLE === "true") { ... } // what???
Enter fullscreen mode Exit fullscreen mode

That is just silly! When faced with boolean values I always write them with yes/no instead of true/false.

Furthermore, I quote every value in the dotenv files to make sure that every developer that reads the file knows the values are strings.

Here is the result:

MY_APP_KEY="supersecret"
DAYS_UNTIL_DATA_DELETION="60"
AWS_DISABLE="yes"
Enter fullscreen mode Exit fullscreen mode

Hope you enjoyed reading the article as much as I enjoyed writing it. And please do not store your boolean config values as strings. Give the yes/no option a try.

Photo by Tekton on Unsplash

Comments 1 total

  • tshammer
    tshammerOct 24, 2024

    What I do is define an array of false-ish strings then use a ternary operator to convert the .env variable value to a boolean

    const falsey = [ "false", "no", "0", "disabled", "disable" ]
    dotenv.config()
    const DEBUG=process.env.DEBUG ? (falsey.includes(process.env.DEBUG) ? false:true) : false

    Nice and concise with few lines of code.

Add comment