Search code examples
node.jsenvironment-variablesdotenv

Why should we use environmental variables in node.js?


While I can understand the benefit of using a .env file, what are the pros and cons (if any) of using them versus placing the values directly in the code? I've see many guides that explain how to use them, but never why should we use them. Are they considered a best practice? Should every production project use them?

# File: .env
DB_HOST=localhost
DB_USER=rootz
DB_PASS=s1mpl3

# File: random_db.js
const db = require('db')
db.connect({
    host: process.env.DB_HOST,
    username: process.env.DB_USER,
    password: process.env.DB_PASS
})

Solution

  • It is best practice not to include database configuration information directly in the code. Keeping these items in environment variables instead has the following benefits:

    • It allows you to use different databases for different instances of the program. For example, to have a development and production instance of the same application
    • It allows you to protect the database credentials. Putting these credentials in the source code might be an option for closed-source highly guarded code, but it's much easier to protect them if they are somewhere else
    • It allows you to change the database configuration without changing the code. Perhaps you've decided to host your database somewhere else. It's nice to be able to do this without rebuilding the application

    I'm sure there are other reasons that I am not thinking of right now, but these alone are enough to convince most people.