简体   繁体   中英

How to specify env variables in node app?

It's a lot of references to dotenv library to use when you want to specify env variables. But why? I can just specify my var in a file like this:

var dev = {
    
}

var prod = {
    
}

var config = null;

if (process.env.NODE_ENV === 'production') {
    config = prod
} else {
    config = dev
}

exports.config = config

and assign my var in npm srcipts , like this:

"scripts": {
    "start": "NODE_ENV=dev node bin/dev",
    "production": "NODE_ENV=production node bin/production"
}

Is my way not secure? Why is dotenv way recommended? Why should I create .env files instead my config.js?

  • Environment variables is the commonly assumed way to configure the behaviour of a program, across all programming languages. It is also supported out-of-the box in most CI/CD tools, as well working really well with the command line.

  • In your example, you assume that the complete config of the prd environment will be stored in the config, including db password etc. It is not considered secure to store any secrets in source code.

  • The .env file is a common utility for bundling environment variables. It is really is easy to create a .gitignore file with this pattern that prevents it from ever being committed so that configuration stays local. Note that the consumer of the package doesn't have to use a .env file but could also have global/local environment vars where the script is ran. Development solid and not so prone to mistakes.

  • Syntax simplicity. instead of creating an ad-hoc source code file containing configuration, with more complex syntax than key=value and less common to understand.

@Nastro, I'll point a little and simple different approach.

Develop your application 100% agnostic of an environment. In other words, keep away *from versioning files within your code or lots of if assigning different values to globals, sessions attributes and etc.

Favor your environments with the due env vars and values. Usually, the most strategic or special environments will be protected against unwanted access(production, staging and etc), so your secret values will be unreachable.

A single db_password = process.env.DB_PASS will be reusable for any existing and future environment you or your team creates.

This is a simple, yet effective approach, but demands a minimal control over your environment and hosts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM