Node - Managing Your Local Environment Variables With Dotenv
In your node projects, tired of fooling with your Terminal to set your local environment variables?
Try the dotenv package.
1.
Navigate, using your terminal, to the root directory of your project
2.
Type the following
npm install dotenv --save
3.
Navigate to your startup file… ie, whatever file you use when you type node app.js
, or node server.js
Type
touch .env
so that the .env file will be in the same folder as your startup file
3.
You now have a .env file. Add it to your .gitignore file like so,
/.env
otherwise you will upload it to github, which would put all your secrets info out in public.
4.
In your .env file, put your secret information like so. Note that quotes are not necessary.
DB_USER=whatever
DB_PASS=whatever
DB_HOST=ds000000.mongolab.com:0000/whatever
SUPERSECRET=987df87d9f87g9d8f7g98ds7f9g
5.
Add this line as early as possible to your main startup file.
`require('dotenv').load();`
Then, after you reboot your server, you can access those secret variables in your code like so
// server.js
var superSecret = process.env.SUPERSECRET;
var mongoAddress = 'mongodb://'+
process.env.DB_USER+':'+
process.env.DB_PASS+'@'+
process.env.DB_HOST;
mongoose.connect(mongoAddress);