Read Settings From the Environment

The Elm Lane walks API already responds to curl requests. Six households use it to book walks for Biscuit, Juno, Pickle, and the other dogs, and Priya’s booking page is waiting to call it. Before that can happen, the API has to run on more than one computer, and each computer needs its own settings.

In this lesson, you’ll move the API’s port number and data file path out of the code and into the environment. You’ll see where a running server’s settings come from, and you’ll be able to predict which value it ends up with when two sources disagree.

Find the Settings in the Code

This course takes an API that works on your machine and gets it ready for real use. Along the way, you’ll configure it per machine, let Priya’s page call it from the browser, and make it log every request without leaking the owners’ phone numbers.

In most lessons, you type the changes into the starting project and run them in your terminal. If your code and the lesson’s disagree, compare yours with the finished code in the same download. A coding exercise in your browser follows each section.

You need a current version of Node.js installed and the course’s code download. The examples use Node 26. Open a terminal in the download’s 00-intro/starting-project folder and install the packages with npm:

Language: Shell
$ npm install

npm lists the packages it added, including Express and Zod. Now start the API with the project’s start script:

Language: Shell
$ npm start

> [email protected] start
> node server.ts

Elm Lane walks API on http://localhost:3000

The API is listening, so stop it with Ctrl+C. Then open server.ts and look at its first lines after the imports:

Language: TypeScript Filename: server.ts
const PORT = 3000;
const DATA_FILE = "data/walks.json";

These two constants are settings: values the code needs that can change from one machine to the next, while the code stays the same. Port 3000 might already be taken on someone’s laptop. Priya might want to test her page against a copy of the walks, so her test bookings never reach the real file.

With the values in server.ts, each of those changes means editing the code. The edit then lands in Git, and the next person who pulls it gets your settings instead of theirs.

Move the Settings Into .env

The settings need to live outside the code, where each machine can set its own. Every Node.js program can already read its environment variables, the named text values its shell hands to it when it starts, through process.env. Each value is a string, or undefined when the variable isn’t set.

Change the two constants in server.ts so that each reads its variable and falls back to a default with the nullish coalescing operator (??):

Language: TypeScript Filename: server.ts
const PORT = process.env.PORT ?? 3000;
const DATA_FILE = process.env.DATA_FILE ?? "data/walks.json";

The defaults keep the API running in development when nothing is set. Setting each variable in the shell before every run would get old fast, so the usual home for these values is a file named .env in the project folder, with one KEY=value line per setting. Create it with a port that’s different from the default, so you can tell which value the server used:

Language: Text Filename: .env
PORT=4000
DATA_FILE=data/walks.json

The file sits right next to server.ts. Start the API again, but predict which port it reports before you press Enter:

Language: Shell
$ npm start
Language: Shell
$ npm start

> [email protected] start
> node server.ts

Elm Lane walks API on http://localhost:3000

The API starts on 3000, the default, with no warning. The start script runs plain node server.ts, and Node.js doesn’t load .env unless you tell it to.

You can confirm that nothing from .env arrived. Stop the API, and save this short script as peek-env.ts in the same folder:

Language: TypeScript Filename: peek-env.ts
console.log("PORT:", process.env.PORT);
console.log("DATA_FILE:", process.env.DATA_FILE);

Run it once with plain node, and once with Node.js’s --env-file option, which reads the named file and adds its lines to process.env before your code runs:

Language: Shell
$ node peek-env.ts
PORT: undefined
DATA_FILE: undefined
$ node --env-file=.env peek-env.ts
PORT: 4000
DATA_FILE: data/walks.json

Without the option, both variables are undefined, so server.ts quietly used its defaults. With it, both values arrive as strings. Node.js needs no package for this. You’ll often see a package called dotenv doing the same job in projects written before Node.js had the option.

Nobody should have to remember the option, so put it in the start script in package.json:

Language: JSON Filename: package.json
"scripts": {
  "start": "node --env-file=.env server.ts"
}

Only the start line changes. Keep the other scripts as they are. Run npm start again, and the API reports the port from .env:

Language: Shell
$ npm start

> [email protected] start
> node --env-file=.env server.ts

Elm Lane walks API on http://localhost:4000

If the silent fallback to 3000 still feels slippery, the mentor can walk through it with you:

Decide Which Value Wins

A setting can now come from three places, and they won’t always agree. A variable can already be set in the environment the command runs with, the same name can be in .env, and the code has its default. Stop the API with Ctrl+C, then set PORT in the environment while leaving .env unchanged, and watch which port wins:

Language: Windows PowerShell
PS> $env:PORT = "5000"; npm start

> elm-lane-walks@1.0.0 start
> node --env-file=.env server.ts

Elm Lane walks API on http://localhost:5000

PowerShell keeps $env:PORT for the rest of the session, so stop the API with Ctrl+C and run Remove-Item Env:PORT before you go on.

Language: Shell
$ PORT=5000 npm start

> [email protected] start
> node --env-file=.env server.ts

Elm Lane walks API on http://localhost:5000

Writing PORT=5000 in front of a command puts the variable in the environment of that one command only. A plain PORT=5000 on its own line would set a shell variable that Node.js never sees, while export PORT=5000 puts it in the environment for every later command. Stop the API with Ctrl+C before you go on.

The environment’s value wins. --env-file fills in only the variables that the environment doesn’t already have. The order is always the same:

PORT comes from the shell if set there (5000), else from .env if Node loaded it (4000), else from the code's default (3000).
The First Source That Has the Variable Wins

With this order, .env holds your everyday values, and you can still override one for a single run without editing any file.

Port 4000 has done its job, so change the first line of .env back to PORT=3000, the port Priya’s page calls.

Your .env holds this machine’s values, and later in the course it could hold secrets too. Keep it out of Git from the start by adding it to the project’s .gitignore:

Language: Text Filename: .gitignore
.env

Then give the next person a template to copy. Commit a .env.example that lists every variable the API reads, with safe placeholder values:

Language: Text Filename: .env.example
PORT=3000
DATA_FILE=data/walks.json

A private repository doesn’t make a committed .env safe. Everyone who can clone the repository can read every old commit, and deleting the file in a later commit leaves it in the history. A secret that was ever committed must be replaced.

If you want to try the order on a few more combinations, the mentor can quiz you:

Check that you can explain where the API’s settings come from:

  1. Your .env has PORT=3000 and DATA_FILE=data/walks-dev.json, and the start script is node --env-file=.env server.ts. Earlier in this terminal, you ran export PORT=8080 or, in PowerShell, $env:PORT = "8080". Now npm start and plain node server.ts both report port 8080, and the node server.ts run reads its walks from data/walks.json. Where does each run’s port come from, and where does that run’s data file come from?
  2. Your neighbor Tomás clones the co-op’s repository and runs npm start. Node.js stops at once with node: .env: not found. Why doesn’t Tomás have a .env, and what should he do?

Question 1: PORT is already in the environment, so --env-file doesn’t overwrite it with the 3000 from .env, and node server.ts gets the same 8080 from the environment. In the node server.ts run, nothing loads .env, so process.env.DATA_FILE is undefined and the API uses its default, "data/walks.json". In that run, the data/walks-dev.json path in .env is never read.

Question 2: .env is in .gitignore, so it never reached the repository, and --env-file stops when its file is missing. Tomás copies .env.example to .env and puts in his own values. If you want to allow a missing file, Node.js also has --env-file-if-exists, which carries on without it.

Your API now reads its port number and data file path from the environment, and npm start loads .env for you. However, every environment value is still an unchecked string. Nothing confirms that PORT holds a number or that DATA_FILE points anywhere useful. In the next lesson, Check Every Setting at Startup, you’ll check all the settings in one place before the API answers a single request.

Become a Member to join the conversation.