Node.js
Environment variables
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.
Exercise 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.
Show example solution
require("dotenv").config();
const port = process.env.PORT || 3000;
console.log(port);
Test yourself
-
Complete the process.env access
const port = process.____.PORT || 3000;
Show answer
const port = process.env.PORT || 3000;
-
Match each expression to its meaning
- process.env.PORT
- PORT variable
- || 3000
- Default value
- Number(...)
- Converts to number
- require("dotenv")
- Imports dotenv
-
What happens if an environment variable is not defined?
const port = process.env.PORT || 3000
- The app crashes
- A default value is used
- The server closes
- The file is deleted
Show answer
A default value is used — A default value is used with ||.
Next lesson: Config hierarchy