node: sourcing environment variables

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

.env
MY_VAR=MY_VALUE

with dotenv

require("dotenv").config()

console.log(process.env.MY_VAR) // MY_VALUE

If 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 start

These 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 start

Update for folks on Windows, the equivalent to source is call, 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:

.env
- MY_VAR=MY_VALUE
+ export MY_VAR=MY_VALUE

The 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:

package.json
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.


Related Posts
  • Olo: Unable To Register Device / Expo 500 Errors On Backend
  • testing-library-printing-large-dom-trees


  • 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!