Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Advanced

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:

js
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

Node.js · editable

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:

Node.js · editable

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:

bash
PORT=8080 DATABASE_URL=postgres://localhost/shop node server.js
js
const 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:

bash
node --env-file=.env server.js

or from code with process.loadEnvFile():

Node.js · editable

Never commit .env to Git. Add it to .gitignore, and commit a .env.example with 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:

Node.js · editable

The program stops before doing anything with a broken configuration. Add JWT_SECRET with 32+ characters to .env and run it again.

Practice

  1. Write a Zod schema for an order: items (a non-empty array of { productId: number, qty: integer 1–10 }) and an optional couponCode (6 uppercase letters, use .regex()).
  2. Use the validate middleware for POST /orders and return the parsed order.
  3. Add LOG_LEVEL (debug, info, warn or error, default info) to the config schema.
✎ Check your understanding

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?

← Connecting a database