2020-08-12
|~2 min read
|229 words
This is all about how to get the variables from a .env into a node script using source
MY_VAR=MY_VALUEwith dotenv
require("dotenv").config()
console.log(process.env.MY_VAR) // MY_VALUEIf you don’t want to use dotenv, however, you can inject the values by seeding your terminal session with source.
For example, imagine a Yarn managed project.
You can pass the variables directly:
export MY_VAR=MY_VALUE && yarn startThese are two methods recommended by John Papa in his blog post, “Making Your NodeJS Work Everywhere With Environment Variables”
Another way to do it is to use source:
source .env && yarn startUpdate for folks on Windows, the equivalent to
sourceiscall, so the command would be:call .env && yarn start
This is a dependency-less approach that will read the .env file, however it does require a slight modification to the .env. Specifically, the variables need to be exported:
- MY_VAR=MY_VALUE
+ export MY_VAR=MY_VALUEThe added benefit of this approach is its variability. For example, you could add a script to package.json to accommodate different .env variables based on where you’re running it. This could take the form of:
scripts: {
"dev:local":"source .env-local && node index.js",
"dev:staging":"source .env-staging && node index.js"
}In this case index.js is the entry point for the application.
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!