How to make .env variables work inside JS class constructors?

Viewed 1595

I'm working on a Node/Express project. Most of the code is contained in files that are inside folders, so that a folder named 'controllers' contains all of the project's controllers, a folder named 'services' contains all of the project's services etc. The code that starts the server is inside a file called app.js which is directly in the project root.

All controllers and services are declared as JS classes and contain a constructor. Dotenv is loaded inside app.js and env variables work nicely everywhere BUT inside class constructors, as those seem to be loaded before dotenv is initialized.

An example of the class syntax used:

export default class exampleService {
    constructor() {
        console.log('This is not working', process.env.EXAMPLE); // process.env.EXAMPLE is undefined
    }

    myFunction() {
        console.log('This works just fine', process.env.EXAMPLE); // process.env.EXAMPLE is exactly how it's defined in .env
    }

    // All other class methods are here.
}

Is there a way I could get dotenv variables to work inside class constructors without having to import and init dotenv in the beginning of each class file?

If I do resort to importing dotenv individually to each class file, will it have any other cons besides making the code less clean?

1 Answers

Try loading the application with preload on dotenv (copied from the source):

Preload

You can use the --require (-r) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require.

$ node -r dotenv/config your_script.js

The configuration options below are supported as command line arguments in the format dotenv_config_<option>=value

$ node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/your/env/vars

Additionally, you can use environment variables to set configuration options. Command line arguments will precede these.

$ DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
$ DOTENV_CONFIG_ENCODING=latin1 node -r dotenv/config your_script.js dotenv
Related