1

I am in production environment on a vps that has linux. I have a file where I try to set my environment variables. my variables are in a file called environment.js.

the content of my file is like this:

process.env.NODE_ENV = "prod";
console.log(process.env.NODE_ENV);
process.env.SEED = "seed";
console.log(process.env.SEED);
process.env.SEED_PORTAL = "seed_bee"
console.log(process.env.SEED_PORTAL);
process.env.HOST = "http://3.86.232.97";

then I run

node environment.js

and I would expect the values to persist, but these variables are not global, they appear as undefined where I try to use them in other projects where I use nodejs

why?

yavg
  • 2,761
  • 7
  • 45
  • 115

3 Answers3

2

When you set environment variables manually in node they only persist to that instance of node, since you're setting them in memory and not on the disk. If you're looking to share them across processes, one way is to use dotenv as Iggnaxios pointed out, in all of the applications, and have the same variables in each application's .env file, or have them all use the same .env file.

Node will also pull environment variables from your operating system. See How to permanently export a variable in Linux? on how to set environment variables in Linux

Benjamin Vogler
  • 336
  • 3
  • 5
-2

to work with environment variables you must install the dotenv library

Iggnaxios
  • 155
  • 2
  • 5
-2

I created a single-purpose CLI tool that does what you want in 1 line if you put your key/value pairs in a YAML file. See npm package & GitHub

Install:

npm install -g yaml-env-cli

Now you can run:

export `yec my_env_file.yaml` && node index.js

Anything after && is the script / command you want to run. Under the hood, the yec CLI simply reads any .yaml file you give it and outputs it as a string, formatted for the export command to work.

Boris Yakubchik
  • 3,861
  • 3
  • 34
  • 41