Environment variables
- Node.js course
- Advanced
- Lesson 68/83
- 5 min
Learn environment variables with process.env.
process.env
process.env is a global object in Node.js that holds all environment variables. After dotenv is loaded, the values from the .env file arrive here. Code reads configuration from this object.
Example: const port = process.env.PORT || 3000;. This uses PORT if it is defined, otherwise 3000. Giving a default with || is a common pattern. Environment variables are always strings; if you need a number, convert with Number(process.env.PORT). In production, values like port, database URL, API keys are given as environment variables. This lets the same code run with different configuration in different environments. The code does not change, only the environment does.
Default value
If an environment variable is not defined, you give a default value so the code can keep running. The || operator is a common way to do this.
Example: const port = process.env.PORT || 3000;. If PORT is defined it uses it, otherwise 3000. This lets the app run in development even if the variable is not set. In production the real value is given as an environment variable. Similar pattern: const dbUrl = process.env.DATABASE_URL || "postgres://localhost/dev";. This approach lets code work flexibly across environments. Configuration is not embedded in code; it is left to the environment. This is the basis of good configuration practice.
Practice Read the PORT variable
Enable dotenv with require("dotenv").config(). Read the port with const port = process.env.PORT || 3000. Print port with console.log.
Starter code
// Enable dotenv
// write here
// Read PORT variable, default 3000
// write here
// Print port
// write hereSample solution
require("dotenv").config();
const port = process.env.PORT || 3000;
console.log(port);Expected output
3000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the process.env access
const port = process.____.PORT || 3000;
const port = process.env.PORT || 3000;
Explanation: process.env.PORT accesses it.
2 Match each expression to its meaning
| Term | Meaning |
|---|---|
process.env.PORT |
PORT variable |
|| 3000 |
Default value |
Number(...) |
Converts to number |
require("dotenv") |
Imports dotenv |
3 What happens if an environment variable is not defined?
const port = process.env.PORT || 3000- The app crashes
- A default value is used Correct answer
- The server closes
- The file is deleted
Explanation: A default value is used with ||.