Environment Variables for the App
Environment variables are named values that live outside the code. They hold settings that change between machines, like a database address.
A .env file
Two settings live in the file.
MONGO_URI=mongodb://localhost:27017/notes
PORT=3001Reading a variable
process.env holds every variable by name.
const uri = process.env.MONGO_URI;
const port = process.env.PORT;Example
process.env.MONGO_URI = 'mongodb://localhost:27017/notes';
process.env.PORT = '3001';
const uri = process.env.MONGO_URI;
const port = process.env.PORT;
console.log('MONGO_URI = ' + uri);
console.log('PORT = ' + port);Key points
- A variable is read in Node with process.env and its name.
- The database address belongs in a variable, not in the code.
- The port number belongs in a variable too.
- A .env file holds these values during local work.
- The .env file stays out of shared code.
In this example, the script sets two variables first. It then reads each one back with process.env. The printed lines show the values the app would use.
Note
A secret in the code can leak when the code is shared.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does the database address belong in a MERN app?