Validation and configuration
Two habits separate hobby servers from professional ones: never trust incoming data, and never hard-code configuration. This lesson covers both: validating requests with Zod, and configuring apps with environment variables.
Why validate?
Anything can arrive in a request body: missing fields, wrong types, a 10 MB string, negative prices, extra fields you didn't expect. Checking by hand quickly gets messy:
if (!req.body.name || typeof req.body.name !== 'string' || req.body.name.length > 100) …
if (typeof req.body.price !== 'number' || req.body.price <= 0) …A schema library lets you describe the shape you expect once, then check data against it. Zod is the most popular choice for TypeScript and JavaScript.
Zod schemas
Notice that parse also transforms: the name was trimmed and tags got its default. Unknown fields are removed, so a client can't sneak in isAdmin: true.
Useful schema pieces
| Schema | Accepts |
|---|---|
z.string().min(1).max(200) |
Non-empty strings up to 200 characters |
z.email(), z.url(), z.uuid() |
Correctly formatted strings |
z.number().int().min(0) |
Whole numbers ≥ 0 |
z.coerce.number() |
Converts '42' to 42 (handy for query strings) |
z.boolean() |
true or false |
z.enum(['a', 'b']) |
One of the listed values |
z.array(schema) |
Arrays of that schema |
.optional(), .nullable(), .default(x) |
Missing, null or defaulted values |
.refine(fn, message) |
Any custom rule |
A validation middleware
Wrap validation in a reusable middleware, so routes only ever see valid data:
Configuration and environment variables
Settings that change between your laptop, the test server and production (ports, database URLs, API keys) don't belong in your code. They come from environment variables:
PORT=8080 DATABASE_URL=postgres://localhost/shop node server.jsconst port = Number(process.env.PORT ?? 3000);
const databaseUrl = process.env.DATABASE_URL;This follows the Twelve-Factor App rule: store config in the environment. The same code runs everywhere; only the environment differs.
.env files
Typing variables on every run is tedious, so during development they live in a .env file. Node can load it itself, no package needed:
node --env-file=.env server.jsor from code with process.loadEnvFile():
Never commit
.envto Git. Add it to.gitignore, and commit a.env.examplewith the variable names and harmless placeholder values instead, so teammates know what to set. In production, set real values in your hosting platform's settings or a secrets manager.
Validate your config at startup
Environment variables are strings and can be missing or misspelled. Validate them once, when the app starts, and crash immediately with a clear message, instead of failing mysteriously an hour later:
The program stops before doing anything with a broken configuration. Add JWT_SECRET with 32+ characters to .env and run it again.
Practice
- Write a Zod schema for an order:
items(a non-empty array of{ productId: number, qty: integer 1–10 }) and an optionalcouponCode(6 uppercase letters, use.regex()). - Use the
validatemiddleware forPOST /ordersand return the parsed order. - Add
LOG_LEVEL(debug,info,warnorerror, defaultinfo) to the config schema.
1.What's the difference between parse and safeParse in Zod?
2.What type are values in process.env?
3.What should happen if a required environment variable is missing?