Validation
- Node.js course
- Advanced
- Lesson 70/83
- 5 min
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.
Practice 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.
Starter code
// Enable dotenv
// write here
// Add PORT validation
// write here
// Print port
// write hereSample solution
require("dotenv").config();
if (!process.env.PORT) throw new Error("PORT required");
const port = process.env.PORT;
console.log(port);Expected output
3000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is validation for?
if (!process.env.PORT) throw new Error(...)- Catches configuration errors early Correct answer
- Provides faster network
- Backs up the database
- Draws the user interface
Explanation: Validation catches errors early.
2 Complete the throw call
if (!process.env.PORT) ____ new Error("PORT required");
if (!process.env.PORT) throw new Error("PORT required");
Explanation: throw new Error throws an error.
3 Match each piece to its role
| Term | Meaning |
|---|---|
throw new Error |
Throws an error |
Joi.object |
Creates a definition |
definition.validate |
Validates data |
required() |
Required field |