Should I call dotenv in every node JS file?

I want to work with environment variables. Unfortunately, I am an inexperienced developer and decided very late to implement such a solution in my project.

I’m trying to inject environment variables, located in .env file, to all JS files (not all of them using environment variables, but I thought it would be faster and easier). Currently, I’m using dotenv package but it is obviously working in one file at once.

Should I use dotenv the standard way? Maybe there’s a vulnerability I don’t know of and that’s why it is very unpopular to use environment variables this way.

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You don’t need to write require(‘dotenv’).config() in every file. Just include this as the top statement in the index.js or the main file that got executed at the very first place when you run your program.

Solution 2

Like the comment on your file mentioned, you should have an entry point for your ENVs. You don’t want to require('dotenv') in every file.

Instead, create a new file (named something like environment.js) that is in the utils or core folder.

require('dotenv').config();

/* eslint no-process-env:0 */
module.exports.default = {

    env: process.env.env,
    url: process.env.url,
    apiUrl: process.env.apiUrl,
    logLevel: process.env.logLevel,

    db: {
        host: process.env.db_host
        port: process.env.db_port
    }
    // Grab everything in you .env file here
}

Then in each of your other files you can include your configs in a nice json object.

const config = require('../utils/environment');

dbConnector(config.db.host, config.db.port);
// blah blah blah

Solution 3

You accepted the first comment but it’s not the right way/answer.
you can include require('dotenv').config() at the very beginning of your entry file (index.js , server.js ..) and you’ll get the process.env variables anywhere in your app by just calling process.env.VARIABLE_NAME

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply