Beginner Fundamentals
Environment Variables
Environment variables hold configuration outside your code, such as ports, API keys, and database URLs. Node.js exposes them through process.env.
Reading a variable
console.log(process.env.HOME); // the user's home folder
console.log(process.env.PORT); // undefined if not set
Every value in process.env is a string.
Setting a variable when running
You can set a variable just for one run:
// In the terminal:
// PORT=4000 node app.js
// In app.js:
const port = process.env.PORT || 3000;
console.log("Listening on port", port);
The || 3000 provides a default when the variable is missing.
Why use them
- Keep secrets out of your source code.
- Change behavior between development and production.
- Avoid hardcoding values that differ per machine.
Loading from a file
Many projects keep variables in a .env file and load them with a package like dotenv. Never commit secrets to version control.
Summary
Use process.env to read configuration at runtime. Provide sensible defaults and keep sensitive values out of your code.