I am building a relatively complex distributed Node system. Let's say there are two processes (node apps), A and B. They are defined in separate projects.
In addition, there are a couple of custom made node modules, being used in both A and B. Let's call them M and N. In addition, M is using N.
How should I correctly handle environment vars?
I guess I should define .env for both main processes (A and B), handle all ENV vars from there and simply pass the needed env vars from there, down to M and N. This way, M and N (and other internal modules) will receive their own ENV vars passed as parameters on creation.
Is this approach correct?
Having modules getting direct access to process.env
is not a good idea, and modules having their own .env
file is an even worse idea.
.env
files should not be added to source control (ie git) because they change with the environment (dev
, prod
, pre-prod
) and sometimes contains sensitive information (like AWS secret keys). So that would require you to paste a .env
file each time you install your node_modules
making your deployment process more complex.
The .env
file loaded inside your module could merge in unexpected ways with the .env
of your root app (remember there is only one process.env
).
Imagine a case where your module would need to behave differently in two parts of your application. How would you override the data loaded via the .env
file only in one place?
So in my opinion, your guess is correct: don't put .env
in node_modules
.
// This is better...
nModule.someMethod(process.env.PARAM1, process.env.PARAM2);
// ...than this
process.env.PARAM1 = '';
process.env.PARAM2 = '';
nModule.someMethod();
I feel strongly that environment variables are reserved for, well, the environment. This to me implies a few things:
process.env
.process.env
is really a question of how you start your programs A and B. I personally prefer systemd services for that which have excellent support for defining the runtime environment. The dotenv package seems more like a crutch, but it's fine from the program's perspective.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With