The walks API now reads PORT and DATA_FILE from the environment, and npm start loads them from .env. However, nothing looks at those values before the code uses them. A typo in .env can change what the server does without stopping it.
In this lesson, you’ll write one module that reads every setting once, when the API starts. You’ll convert each value to the type the code needs, give optional settings a default, and stop the server with a message that names the variable when a required setting is missing or a value is invalid. Start with what happens today when a setting is wrong.
See a Wrong Setting Slip Through
A setting that nobody checks can be wrong without anyone noticing. Remember Priya, who wants to try her booking page against a copy of the walks so her test bookings never reach the real file. She copies data/walks.json to data/test-walks.json and edits her .env, but she swaps two letters in the variable’s name:
.env
PORT=3000
DATA_FLIE=data/test-walks.json
You can make the same slip in your own .env and start the API:
$ npm start
> [email protected] start
> node --env-file=.env server.ts
Elm Lane walks API on http://localhost:3000
The API starts as if all were well. Why didn’t anything complain? Node.js loaded a variable called DATA_FLIE, which no code reads.
process.env.DATA_FILE is undefined, so the ?? in server.ts falls back to "data/walks.json". Every test booking Priya makes now lands in the co-op’s real file.
The code has two more weaknesses. PORT is a string when the variable is set and the number 3000 when it isn’t, so its type depends on the machine. And the code reads each setting where it needs it, far from the others. Validating them there would mean scattering checks across the code, and you could miss a setting.
All three problems have the same fix. Read every setting in one place, once, when the server starts, and turn the raw strings into checked, typed values before any other code runs.
Check the Settings in config.ts
Environment variables are external data, like a request body, so the server can’t trust them. You already guard request bodies with a Zod schema, and the same tool works for the environment. Create a file called config.ts next to server.ts, with a schema for the two settings the API uses:
config.ts
import { z } from "zod";
const envSchema = z.object({
PORT: z.coerce.number().int().min(1).max(65535)
.default(3000),
DATA_FILE: z.string().min(1),
});
Each key in the schema is the name of an environment variable, and each value says what’s allowed:
PORT:z.coerce.number()passes the string throughNumber()before checking it, so"3000"becomes the number3000. Not every number is a valid port number, though, so.int().min(1).max(65535)accepts only whole numbers from 1 to 65535. When the variable isn’t set at all,.default(3000)supplies the value instead. An emptyPORT=line counts as set.Number("")is 0, so the line fails the check instead of getting the default.DATA_FILE:z.string().min(1)has no default, so the setting is required, and.min(1)rejects an emptyDATA_FILE=line too. A missingDATA_FILEis now an error rather than a quiet switch to the real walks file. The schema checks only the text of the path. It doesn’t check that the file exists. A path to a missing file gives you an empty list of walks, and the first booking creates the file there. If the list comes back empty, check the path.
Why does PORT keep a default when DATA_FILE loses it? Any free port works on a development machine, but the wrong data file means bookings land in the wrong place. A setting that can do damage when it’s wrong shouldn’t have a default.
Next, check the environment against the schema and stop the server if anything fails. Add this below the schema:
config.ts
const result = envSchema.safeParse(process.env);
if (!result.success) {
for (const issue of result.error.issues) {
const name = issue.path.join(".");
console.error(`Invalid setting ${name}: ${issue.message}`);
}
process.exit(1);
}
.safeParse() returns a result instead of throwing, so you decide what the message looks like. For each problem Zod finds, issue.path holds the schema key it belongs to, which here is the variable’s name. The message leaves out the value on purpose, because a setting can hold a secret that shouldn’t end up in a log. process.exit(1) then ends the process with exit code 1, the usual signal that a program failed.
The last part hands the checked values to the rest of the code, under names that read like JavaScript rather than like environment variables:
config.ts
export const config = {
port: result.data.PORT,
dataFile: result.data.DATA_FILE,
};
After the if block, TypeScript knows the parse succeeded, so config.port is a number and config.dataFile is a string. The rest of the API never touches process.env again.
Now switch server.ts over. Delete the PORT and DATA_FILE constants and import config. Then use its properties wherever the constants appeared:
server.ts
import { config } from "./config.ts";
// ...
app.listen(config.port, () => {
console.log(`Elm Lane walks API on http://localhost:${config.port}`);
});
Wherever the code reads the data file, DATA_FILE becomes config.dataFile in the same way. When does the check run? The code at the top level of a module runs once, the first time any file imports it. Every file that imports config gets the same object, so the environment is parsed once, before server.ts reads the walks or listens on a port.
The API you started earlier is still running on the old code, so stop it with Ctrl+C. Then start it again with Priya’s typo still in .env:
$ npm start
> [email protected] start
> node --env-file=.env server.ts
Invalid setting DATA_FILE: Invalid input: expected string, received undefined
The server stops before it touches any file, and the message names the variable to look for. Now break a second setting on purpose. Change the port to 300000, with two zeros too many, as a tired finger might type it:
.env
PORT=300000
DATA_FLIE=data/test-walks.json
Run npm start again, and both problems appear at once:
$ npm start
> [email protected] start
> node --env-file=.env server.ts
Invalid setting PORT: Too big: expected number to be <=65535
Invalid setting DATA_FILE: Invalid input: expected string, received undefined
300000 is a number, but no port goes that high, so .max(65535) rejects it. Zod reports every issue in one go, so Priya can fix her whole .env in one pass. Fix both lines, setting PORT=3000 and DATA_FILE=data/walks.json, and the API starts on port 3000 as before. Stop it with Ctrl+C before you add the next setting.
If you’d like to see why the module stops the process instead of letting an error escape, the mentor can talk it through:
Add a Flag Without the "false" Slip
When Priya reads the API’s responses in her terminal, she’d like the JSON indented so she can scan it. On the co-op’s server, compact JSON is fine. Express has a "json spaces" setting for this, which sets how many spaces res.json() indents with.
You’ll control it with a new variable, PRETTY_JSON, set to true or false. Watch out for the value "false".
A check like if (process.env.PRETTY_JSON) treats it as on, because every non-empty string is truthy. z.coerce.boolean() has the same problem, because it calls Boolean() on the string and so turns "false" into true as well.
Zod’s z.stringbool() reads the string’s meaning instead of its truthiness. It maps "true" to true and "false" to false, ignoring case. It also accepts a few common spellings such as "yes" and "no" or "1" and "0", and it rejects every other string. Add it to the schema with a default of false, and pass it on in config:
config.ts
const envSchema = z.object({
PORT: z.coerce.number().int().min(1).max(65535)
.default(3000),
DATA_FILE: z.string().min(1),
PRETTY_JSON: z.stringbool().default(false),
});
// ...
export const config = {
port: result.data.PORT,
dataFile: result.data.DATA_FILE,
prettyJson: result.data.PRETTY_JSON,
};
In server.ts, right after you create app, use the flag to pick the indentation with the ternary operator:
server.ts
app.set("json spaces", config.prettyJson ? 2 : 0);
Add every new setting to .env with the value you want on this machine and to .env.example so the next person knows it exists:
.env.example
PORT=3000
DATA_FILE=data/walks.json
PRETTY_JSON=false
Set PRETTY_JSON=true in your .env, start the API, and call it from a second terminal with curl -s http://localhost:3000/walks. The list now comes back over several lines, indented by two more spaces at each level: each walk’s braces sit two spaces in, and its properties four.
Stop the API and set PRETTY_JSON=false. Then start it again with npm start and repeat the curl command in the second terminal. The whole list comes back on one line, as it did before.
With z.coerce.boolean() in the schema instead, that last run would have printed the indented list, because Boolean("false") is true.
Last, stop the API and put a typo in the flag’s value, PRETTY_JSON=ture. Then start the API again. The error line is wrapped for display here:
$ npm start
> [email protected] start
> node --env-file=.env server.ts
Invalid setting PRETTY_JSON: Invalid option: expected one of
"true"|"1"|"yes"|"on"|"y"|"enabled"|"false"|"0"|"no"|"off"|"n"|"disabled"
The message lists every spelling z.stringbool() accepts. Set the value back to false or true before you go on.
Check that you can configure the API through a checked config module:
- Your neighbor Tomás has this
.env:PORT=8080andPRETTY_JSON=no, with noDATA_FILEline. What doesnpm startprint? - Why does
PORThave a default in the schema whileDATA_FILEdoesn’t?
Question 1: It prints one line after npm’s two: Invalid setting DATA_FILE: Invalid input: expected string, received undefined. Then the server stops.
"8080" converts to a number, and "no" is one of the spellings z.stringbool() accepts, so neither of those is a problem.
Question 2: Any free port is fine on a development machine, so a default saves you a setup step. A wrong data file sends bookings to the wrong place, so the server should stop rather than guess.
For optional extra practice, the mentor can quiz you on how the module treats different .env files:
The next item is the course’s first coding exercise, and it runs in your browser. You edit the code in the editor on the page, click Run Tests, and automated tests report what passes and what fails. Run them early, and read a failing test’s message for clues. The Contents tab below the editor explains how coding exercises work, including Full screen for more room.
Your API now checks every setting once, at startup, and stops with the variable’s name when a required setting is missing or a value is invalid. In Exercise: Check the Co-op’s Settings, you’ll write that check yourself, turning environment variables into the co-op’s settings or a clear message about what’s wrong.