process.env
- Node.js course
- Intermediate
- Lesson 60/116
- 5 min
Learn environment variables with process.env.
What is process.env?
process.env is an object that holds environment variables. It gives Node.js access to the variables defined by the operating system. It is used for configuration data like port numbers, database addresses and API keys.
For example, if you start with PORT=3000 node app.js, then process.env.PORT is "3000". A variable that is not defined returns undefined, so the pattern process.env.PORT || 3000 is common to give a default. This way the same code can run with different settings in development and production.
Setting environment variables
You can set environment variables in two ways. On the command line you can pass them before starting: PORT=3000 node app.js. Or you can set them from code with process.env.PORT = "3000".
The first way is safer, because secret keys are not written into the code. The second way is fine for tests and temporary settings. In production, .env files and the dotenv package are also used; but these are not built in, they are installed with npm install. The key point is to keep configuration separate from code, so the code runs unchanged in different environments.
Practice Read the port and print it
Read the port variable with process.env.PORT. If it is not defined, use 3000 as a default with ||. Print it with console.log.
Starter code
// Read the port from the environment
// If missing, use 3000
// Print with console.log
// write hereSample solution
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 Read the port variable
const port = process.env.____ || 3000;
const port = process.env.PORT || 3000;
Explanation: PORT is read from the environment.
2 What does process.env.PORT return if not defined?
process.env.PORT- It throws an error
- An empty string
- 3000
- undefined Correct answer
Explanation: An undefined variable returns undefined; that is why || gives a default.
3 Match each piece to its role
| Term | Meaning |
|---|---|
process.env |
Environment variables |
PORT |
A variable name |
|| |
Default value |
undefined |
Undefined result |