DEV Community

Kos-M
Kos-M

Posted on

Supercharge your .env powered projects!

Hello out there !

I Just create a tiny lib to solve a common problem with .env files ,
... and wanted to share it :D

The Problem:
Well with git and other code versioning systems we want to keep our secretes documented but conveniently ported to our code.
There comes dotenv lib which does its job nice and smooth..

-- But --
If you want to update any of these env variables described in your .env file , you must stop/kill/close the proccess of your app , and restart it -- you guessed right.
Having a web server running 24/7 we don't want any zero down time at all..

Installation:

npm install env-hot-reload 
Enter fullscreen mode Exit fullscreen mode

or

yarn add env-hot-reload
Enter fullscreen mode Exit fullscreen mode

So here comes my lib ,( env-hot-reload ) in play

const  envHotReloader = require('env-hot-reload');
new envHotReloader({
function runs on every .env update
    watchInterval: 1500  // optionall default 3500
   }).watch()
Enter fullscreen mode Exit fullscreen mode

after adding these 4 lines to your app , every change to .env will take effect instantly to your process.env variable.

Bonus:
You can specify a callback function to triggered every time something is changed to your config.

const  envHotReloader = require('env-hot-reload');
new envHotReloader({
    onEnvChange: myFunctToCall, // optionall callback function runs on every .env update
    watchInterval: 1500  // optionall default 3500 in ms
   }).watch()

function myFunctToCall() {
    // your code to run on .env is updated...
  }
Enter fullscreen mode Exit fullscreen mode

In github repo you will find an express server under examples folder , which i found it a common use case .
Included a function to restart webserver in new port when you will change it from .env .

Give it a try ,
I hope you 'll found it usefull ,
if you have any question just drop a comment

Links:
https://www.npmjs.com/package/env-hot-reload
https://github.com/Kos-M/env-hot-reload

Thanks for your time!!
Kos M <<

Top comments (0)