Notes

Using environment variables with .env

Edit on GitHub

JavaScript
2 minutes

tl;dr

1npm i -D dotenv

define vars in .env file

1ACCESS_TOKEN=j1v7qstp59eodbn79tsp
2CLEINT_KEY=wp2aksuvduasepd2edre2rd
3CLIENT_SECRET=227tasgvdvqid2tedt2e

use vars in your code app.js file

add a .env-sample and commit that, .gitignore the actual .env file

1const connection = new API({
2	api_token: process.env.ACCESS_TOKEN,
3	client_key: process.env.CLEINT_KEY,
4	client_secret: process.env.CLIENT_SECRET
5})
1// .env
2SECRET_KEY=SuperSecretKey90965443241
1require('dotenv').config() // require config
2require('./../server/index') // entry point
3
4console.info(process.env.SECRET_KEY);

Set env variables by passing them as an argument

1# *nix
2NODE_ENV=development node app.js

For Windows you need to use the set keyword

1# windows
2set NODE_ENV=development&& node app.js 

cross-env can be used for cross-platform env variables

1npm insall cross-env --save-dev
2
3npx cross-env NODE_ENV=development node app.js
4npx cross-env NODE_ENV=development PORT=3000 node app.js

package.json

1"scripts": {
2	"dev": "NODE_ENV=development PORT=3000 node app"
3}
  • .js is optional in app.js
  • "cross-env NODE_ENV=development PORT=3000 node app" will run on any operating system

Sample .env

1NODE_ENV=development
2PORT=3000
3HOST
1const {
2	NODE_ENV, PORT, HOST
3} = process.env
4
5console.info(
6	NODE_ENV, PORT, HOST
7);
1# Load env variables and pass them along as cofig vars in terminal
2eval $(cat .env) node app.js
3
4# make values available to current Shell
5export $(cat .env) && node app.js
1require('dotenv').config() // by adding this one line you can now do `node app.js` and it'll have your vars
2
3const {
4	NODE_ENV, PORT, HOST
5} = process.env
6
7console.info(
8	NODE_ENV, PORT, HOST
9);
1node app.js