Configuration Checked at Startup

An API reads every setting it needs in one config module that checks them all with Zod when the server starts, so a missing or mistyped setting stops it at once with a message naming each problem, and NODE_ENV, an .env file and the host's own settings decide the values in each place it runs.

Journeyman · Node.js · Web Development · Updated

By

After this lesson you can

  • Read every setting once in a config module that checks them with Zod at startup and stops with a message naming each problem
  • Choose where a setting comes from in each environment, such as NODE_ENV, an .env file loaded with --env-file, or the host's settings

Key takeaways

  • Settings read all over the code fail late and far from the mistake, such as a typo in a variable's name that shows up as a crash on the first request.
  • One config module reads every setting once, checks it, turns text into the right type, fills in defaults, and hands the rest of the code one object.
  • Checking with Zod's safeParse at startup lets the server stop at once with one message naming every problem, which is called failing fast.
  • NODE_ENV says where the code is running, such as development, test or production. On your computer the values come from .env with --env-file, and online from the host's settings.

The same API code will run on your laptop, in your tests, and on a host where real riders use it. Each place needs its own port, its own database and its own amount of logging. Every job you take will have a config file or module like the one in this lesson, and "it worked on my machine" is often a setting nobody checked.

The Campus Shuttle API reads its settings wherever it needs them. server.js has const port = process.env.PORT ?? 3100;, and a teammate's .env says PORT=31OO, with two capital letter O's. The server starts and prints:

Listening on http://localhost:31OO

No request can ever reach it: a port is a number, and Express handed that text to Node as something else entirely. Meanwhile db.js reads process.env.MONGO_URI, a name nobody sets (the .env file says MONGODB_URI), and stops with TypeError: Cannot read properties of undefined (reading 'startsWith'), from deep inside the MongoDB driver. Both mistakes are one line in .env, and both show up somewhere else.

One config module, checked at startup

A pilot runs through a checklist before takeoff, not halfway down the runway. The API can do the same: read every setting in one place, as it starts, and refuse to start if any is wrong. Stopping at the first sign of trouble, with a clear reason, instead of limping on is called failing fast.

So the API gets one config module, config.js. It's the only file that reads process.env. It checks each setting, turns text into numbers, fills in defaults, and gives the rest of the code one object, config.port, config.mongodbUri, to use. Validating with Zod checked request bodies with a schema; a config check is the same job, done on process.env.

Every setting, checked with Zod

import { z } from "zod";

const portProblem = "PORT must be a whole number from 1 to 65535";

const schema = z.object({
  NODE_ENV: z.enum(["development", "test", "production"], {
    error: "NODE_ENV must be development, test or production",
  }).default("development"),
  PORT: z.coerce.number({ error: portProblem }).int({ error: portProblem })
    .min(1, { error: portProblem }).max(65535, { error: portProblem }).default(3100),
  MONGODB_URI: z.string({ error: "MONGODB_URI is missing" })
    .refine((uri) => uri.startsWith("mongodb://") || uri.startsWith("mongodb+srv://"), {
      error: "MONGODB_URI must start with mongodb:// or mongodb+srv://",
    }),
  LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace"], {
    error: "LOG_LEVEL must be fatal, error, warn, info, debug or trace",
  }).default("info"),
});

export function loadConfig(env) {
  const result = schema.safeParse(env);
  if (!result.success) {
    const problems = result.error.issues.map((issue) => issue.message);
    throw new Error(`Fix these settings, then start again: ${problems.join("; ")}.`);
  }
  return {
    env: result.data.NODE_ENV,
    port: result.data.PORT,
    mongodbUri: result.data.MONGODB_URI,
    logLevel: result.data.LOG_LEVEL,
  };
}

z.coerce.number() turns the text "3200" into the number 3200 before checking it; .default() fills in a value only when the setting isn't there at all. safeParse never throws: it collects every problem in error.issues, so one message can name them all. loadConfig takes env as a parameter instead of reading process.env itself, so a test can hand it any settings it likes.

server.js calls it first, before it connects to anything:

import { loadConfig } from "./config.js";

let config;
try {
  config = loadConfig(process.env);
} catch (error) {
  console.error(error.message);
  process.exit(1);
}

console.log(`Starting in ${config.env} on port ${config.port}, logging at ${config.logLevel}`);

Started with the teammate's mistakes (PORT=31OO, no MONGODB_URI, LOG_LEVEL=loud), it stops before anything else happens, with exit code 1:

Fix these settings, then start again: PORT must be a whole number from 1 to 65535; MONGODB_URI is missing; LOG_LEVEL must be fatal, error, warn, info, debug or trace.

NODE_ENV, and where the values come from

NODE_ENV is the setting that says where the code is running: development on your computer, test while tests run, production on the host. Code can check it for things that should differ, such as pino-pretty only in development; many packages, Express among them, read it too. The values themselves come from one of two places:

  • On your computer: a .env file, loaded with node --env-file=.env server.js, as Settings from Environment Variables showed. It's in .gitignore.
  • On a host: the host's settings page, where you type each name and value. They reach your code as real environment variables, with no file at all.

--env-file-if-exists=.env loads the file when it's there and carries on when it isn't, which suits code that runs in both places. And a real environment variable wins over the same name in the file. With this .env:

PORT=3100
MONGODB_URI=mongodb://localhost:27017/campus_shuttle
LOG_LEVEL=debug

node --env-file=.env server.js prints Starting in development on port 3100, logging at debug. Set PORT for one run in zsh with PORT=8080 node --env-file=.env server.js (in PowerShell, $env:PORT = "8080" first), and it prints Starting in development on port 8080, logging at debug.

Do it: check the shuttle's settings

The shuttle's timetable code needs one more setting, the time zone the bus times are in, and the team wants one function that reads every setting and refuses to go on when a required one is missing.

Your job: write loadConfig(env). env is an object of settings, as process.env would hold them: every value is text. It gives back an object with four properties:

  • port: env.PORT turned into a number, or 3100 when PORT isn't set.
  • mongodbUri: env.MONGODB_URI. Required.
  • timeZone: env.TIME_ZONE. Required.
  • logLevel: env.LOG_LEVEL, or "info" when it isn't set.

When a required setting is missing or is the empty text "", throw an Error whose message is Missing settings: followed by every missing name, in the order MONGODB_URI, TIME_ZONE, separated by a comma and a space.

Worked through: loadConfig({ PORT: "3200", MONGODB_URI: "mongodb://localhost:27017/campus_shuttle", TIME_ZONE: "America/Denver" }) has both required settings, so nothing is thrown. PORT is the text "3200", which becomes the number 3200. LOG_LEVEL isn't set, so it's "info". It gives back { port: 3200, mongodbUri: "mongodb://localhost:27017/campus_shuttle", timeZone: "America/Denver", logLevel: "info" }.

Practiced live on the lesson page: write the JavaScript right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

One module that reads and checks every setting at startup turns a typo in .env from a mystery crash on the first request into one clear sentence, before a single rider is affected.

Key terms

Related