Node.js
Validation
Learn config validation and schema checking.
Validation
Environment variables always come as strings. It is good practice to verify that a variable is defined, has the right type and holds a valid value. This is validation.
Example: if (!process.env.PORT) throw new Error("PORT required");. This stops the app early if PORT is undefined. The error does not surface later in a hidden way; it shows up right at the start. Libraries like joi or zod are used for configuration validation. Example: const definition = Joi.object({ port: Joi.number().required() }); const config = definition.validate({ port: process.env.PORT });. This verifies that port is a number and is defined. Validation catches configuration errors early.
Validation with Joi
Joi is a popular validation library for Node.js. You define a structure and validate data against it. It is often used for configuration validation.
Example: const Joi = require("joi"); const definition = Joi.object({ port: Joi.number().port().required(), nodeEnv: Joi.string().valid("development", "production").required() }); const { error, value } = definition.validate({ port: process.env.PORT, nodeEnv: process.env.NODE_ENV });. If error exists the configuration is invalid; value is the validated configuration. Joi checks types and allowed values. If there is an error, the app stops early. This prevents hidden errors in production caused by bad configuration. zod or env-var can be used instead of Joi.
Exercise Add PORT validation
Enable dotenv. Add validation with if (!process.env.PORT) throw new Error("PORT required"). Write const port = process.env.PORT. Print port with console.log.
Show example solution
require("dotenv").config();
if (!process.env.PORT) throw new Error("PORT required");
const port = process.env.PORT;
console.log(port);
Test yourself
-
What is validation for?
if (!process.env.PORT) throw new Error(...)
- Catches configuration errors early
- Provides faster network
- Backs up the database
- Draws the user interface
Show answer
Catches configuration errors early — Validation catches errors early.
-
Complete the throw call
if (!process.env.PORT) ____ new Error("PORT required");
Show answer
if (!process.env.PORT) throw new Error("PORT required");
-
Match each piece to its role
- throw new Error
- Throws an error
- Joi.object
- Creates a definition
- definition.validate
- Validates data
- required()
- Required field
Next lesson: Secrets management