Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global values - anti-pattern?

Tags:

node.js

I was recently told, that accessing process.env values anywhere else, but start-up file is an anti-pattern. Is that true? If so, how am I supposed to access values assigned there? Should I assign them to global scope? I don't really understand WHY this would be anti-pattern, could someone explain this to me?

like image 502
Patryk Cieszkowski Avatar asked Feb 22 '26 00:02

Patryk Cieszkowski


1 Answers

Config variables from environment tend to be non-readable often. So, you can possibly end up with something like process.env.PRODUCTION_DATABASES_MONGO_PORT that will mess up your code. And if your have a lot of process.env-s in different files it might be hard to understand what possible options are (should you run NODE_ENV=dev node index or NODE_ENV=development node index or FOO=true node index?).

As most simple solution that doesn't require any dependency injection you can simply create config.js in the root folder with something like:

module.exports = {
  databases: {
    mongo: {
      port: process.env.BLAH_BLAH_BLAH
    }
  }
  // ...
};

and just require it wherever you want.

like image 58
Glen Swift Avatar answered Feb 23 '26 16:02

Glen Swift



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!