Cover your environment variables at runtime

dotenv is a popular package to load environment variables from .env file. It’s easy to use and noob friendly. Everyone love it, I’m not an exception. I just have concern about how does environment stored.

This one is simplest code to load all environment variables from .env file:

After dotenv triggered, .env file will be loaded to process.env as a key values object.

  • process.env able to access everywhere without restriction
  • process.env is also store all credential data
  • All key in process.env could be overwrite
  • TEST_ENV wasn’t friendly to typescript and linter

In the try to improve everything that was pointed above, I’ve found Proxy could help a lot. The idea is, I will clone a copy of process.env and wrapper all accesses through and Proxy object.

This code get things done following steps:

  • Cache default environments variables
  • Load configuration from .env file
  • Create a singleton Proxy that’s hide all keys and protect read and write

Let’s take a look into example .env:

Here is the result:

It works, just like expected.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store