What are Environment Variables?

Accessing Environment Variables

console.log(process.env.PORT); // prints the value of PORT

Setting Environment Variables

Temporarily (per command):

PORT=3000 node app.js

Permanently (using a .env file + dotenv package):

1️⃣ Install dotenv

npm install dotenv

2️⃣ Create a .env file

PORT=3000
DB_URL=mongodb://localhost:27017/mydb
SECRET_KEY=secret#199

3️⃣ Load .env variables in your app

require('dotenv').config();

console.log(process.env.PORT);        // 3000
console.log(process.env.DB_URL);      // mongodb://localhost:27017/mydb

Best Practices