2020-08-13
|~1 min read
|185 words
In learning about different approaches to loading environment variables in Node projects, I came across an option for Node that can require dependencies from the command line.
For example, one common way to load environment variables within a Node project is to use dotenv like so:
Define your variables within a .env file:
MY_VAR=TESTLoad the environment variables with dontenv’s config method as quickly as possible, e.g., in the entry point to the app:
require(dotenv).config()
console.log(process.env.MY_VAR)Assuming dotenv is installed when we run this project:
node index.jsWe’ll print to the console:
SUCCESSBut this is only because “as early as possible” in our application, we called the config method.
It turns out we can preload this configuration (using the -r --require CLI option for Node) and eliminate the line:
- require(dotenv).config()
console.log(process.env.MY_VAR)node --require dotenv/config index.jsAnd we will still see our environment variables are loaded successfully:
SUCCESSPretty nifty! Particularly if you don’t want dotenv to be a production dependency where environment variables are managed by some external service.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!