🎓 A1Learner
🔍
0 of 50 lessons completed

Environment Variables

An environment variable is a named value set outside the program. The program reads it from process.env.

Read the port

Run this with PORT set to 4000.

const port = process.env.PORT || 3000;
console.log(`Port: ${port}`);

Set the port

This command sets PORT and runs the program.

PORT=4000 node app.js

Example

const port = process.env.PORT || 3000;

console.log(`Port: ${port}`);

Key points

  • An environment variable is a named value set outside the program.
  • The program reads it from process.env.
  • process.env is an object that holds the set values.
  • Use process.env.PORT to read a value named PORT.
  • A port is the number a server listens on.
  • Give a fallback value for when the variable is missing.

In this example, process.env.PORT reads the value named PORT. The || 3000 part gives 3000 when PORT is missing. This run sets PORT to 4000. The print shows 4000, the value set for this run.

Note

Keep secrets in environment variables, never in the code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where does a program read an environment variable from?