Node: Native support for loading environment variables

Created on 19 Nov 2017  路  10Comments  路  Source: nodejs/node

Node based apps are working great with environment variables.
It is simple to modify the dynamic values based on the app purpose.
But when it comes to development environment I find it is coming short.

For example, for test and production environments,
my configuration file can be the same,
and read the variables from the automated building tool environment (gitlab-runner, travis ...).

But for the development phase, running on the local machine of the developers,
we want the developers to easily modify the values (like port, dbUrl ...).

dotenv is a great try, but you have to install it as a dependency,
though it's actually a devDependency.
I don't want to have something like this in my production app:

if (process.env.NODE_ENV != PRODUCTION)
    dotenv.config();

And while you could argue that I can remove the if statement,
my application still depends on the library.

I think it could be great if the platform (node) could have load the environment variables (like docker does).

And so my package.json would look something like this:

"start": "node build/index.js",
"start:dev": "node --env-file=env-vars.json build/index.js"

Developers now can easily commit and modify the env-vars.json,
and the environments are still provide great agility.

What do you guys think?

feature request process

Most helpful comment

-1 IMO this is best left to userland.

All 10 comments

-1 IMO this is best left to userland.

@itaied246 How would this work? Would npm start consult the NODE_ENV environment variable and choose between the start and start:dev tasks?

@Trott he's talking about --env-file=env-vars.json

@Trott he's talking about --env-file=env-vars.json

Oh, I see, adding that as a CLI flag. Got it.

I feel like this solves the problem

@devsnek you are right, that'll do it.
But I still think that executing the environment with a file is necessary.
You didn't provide any reason to not implement it, so why do you suggest alternatives?

Another thing came up to my mind is that exporting the env vars does change your desktop environment,
as opposed to dotenv and my suggestion.

It's possible to use dotenv without polluting your production code. You can for example use Node's preload feature:

// env.js
require('dotenv').config();

and have in your package.json:

"start:dev": "node -r ./env.js build/index.js

It's not much more complicated than your suggestion and allows to do any kind of customization (like setting the env from a JSON file).

I also think this is best left to userland.

You are right, this is much more elegant solution.
For now I think I'll use this, though I my opinion it could be awesome to enable more advanced options for running in the platform.

I agree with @targos as well. I'll close this out given the general sentiment to defer to userland.

Was this page helpful?
0 / 5 - 0 ratings