Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 133 ยท Frameworks and Ecosystem

Validating Input

Validate untrusted input in Node.js - hand-written checks, a small schema library, JSON Schema, zod and ajv, sanitizing, helpful error messages and checking environment config at startup.

Everything that enters your program from outside is untrusted: HTTP request bodies, query strings, headers, files, messages from a queue, environment variables, even data from your own database after years of changes. JavaScript will happily let a string flow where you expected a number, an array where you expected an object, or a missing field turn into undefined three functions later and crash far from the real cause.

Validation is the habit of checking data at the boundary, once, and refusing to continue with anything that does not match what your code expects. After that point, the rest of the program can treat the data as trustworthy. It is the first line of defense against bugs, crashes and many attacks, and it is also the best documentation of what your API accepts.

This lesson builds the idea from scratch: a hand-written check, a tiny schema library you can run here, the standard JSON Schema format, how the popular libraries zod, valibot and ajv look (read-only, since no npm packages are installed in the editor), plus sanitizing, error messages and validating configuration at startup. It connects to JSON and Data Handling, Request Bodies, JSON and Forms, Designing REST APIs and Web Application Security.

Validate, parse, sanitize: three different jobs

People use these words loosely, so separate them:

  • Validation answers "is this acceptable?" It returns yes or a list of problems and changes nothing. (age must be an integer from 0 to 150.)
  • Parsing (or coercion) converts raw input into the type you want: the string "42" from a query string becomes the number 42. A good validator does both at once: "parse, don't validate" means the function returns a trusted, correctly typed value or fails.
  • Sanitizing cleans or escapes data that is valid but could be harmful or messy: trimming spaces, removing control characters, escaping HTML before showing it.

Do these at the edge, then pass the result inward. Never validate only in the browser: client-side checks are for friendliness, server-side checks are for safety, because anyone can send requests without your form.

The hand-written way

The simplest validator is a function. Its important property is that it reports all problems, not only the first, and says where each one is.

Node.js A hand-written validator that collects every problem

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This works, and for one endpoint it may be all you need. But with fifty endpoints, hand-written checks repeat themselves and drift apart. That is the reason schemas exist: you describe the shape once as data or as a small composed object, and a generic engine does the checking and the error reporting.

Building a tiny schema library

To understand what zod and friends do, build a miniature version. Every schema is an object with a function that checks a value, pushes problems into a shared list with a path, and returns the cleaned value. Composite schemas (object, array) call their children, extending the path as they go.

Node.js mini-schema: composable validation from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study what happened in the first call. The input contained isAdmin: true, which is not in the schema, and the result does not have it: schemas that strip unknown keys protect you from mass assignment, where a client smuggles in a field like isAdmin or role that your code then copies into a database record. The string '3' for quantity was coerced to the number 3, and shipping received its default. Meanwhile the invalid input produced a list of problems with exact paths such as items.1.quantity, which a client can use to highlight the right form field.

The library is small, but every feature you see in zod or valibot is a variation on this loop: check, push issues with a path, return the cleaned value.

The real libraries (read-only)

You rarely need to write your own schema engine; use a maintained one. These snippets need npm install and so cannot run in the editor. They show the same Order idea in each style.

zod (the most popular; schemas double as TypeScript types):

JavaScript
import { z } from 'zod';

const Order = z.object({
  customer: z.object({
    name: z.string().trim().min(1),
    email: z.email(),
  }),
  items: z.array(z.object({
    sku: z.string().regex(/^[A-Z]{3}-\d{3}$/),
    quantity: z.coerce.number().int().min(1).max(99),
  })).min(1),
  shipping: z.enum(['standard', 'express']).default('standard'),
  note: z.string().max(40).optional(),
});

const result = Order.safeParse(request.body);
if (!result.success) {
  return res.status(422).json({ errors: result.error.issues });
}
const order = result.data;   // fully typed and cleaned
TEXT
// result.error.issues for a bad quantity looks like:
[ { code: 'too_small', minimum: 1, path: ['items', 0, 'quantity'],
    message: 'Too small: expected number to be >=1' } ]

valibot has the same ideas with small, tree-shakable functions (v.object({ ... }), v.pipe(v.string(), v.minLength(1))), which matters when bundle size is important, for example in browsers.

ajv validates against JSON Schema, a language-independent standard. It compiles each schema to a fast JavaScript function, which makes it a favorite for servers (Fastify uses it internally):

JavaScript
import Ajv from 'ajv';

const ajv = new Ajv({ allErrors: true, coerceTypes: true, removeAdditional: true });
const validate = ajv.compile(orderSchema);       // compile once, at startup

if (!validate(request.body)) {
  return res.status(422).json({ errors: validate.errors });
}

Which should you pick? zod or valibot when you write TypeScript and want types derived from the schema. ajv when schemas should be shared as JSON files with other languages and tools, such as OpenAPI documents.

JSON Schema

JSON Schema describes the shape of JSON data as JSON. A schema is itself a JSON document, so it can be stored, versioned, published as API documentation and used by any language. Core keywords:

Keyword Meaning
type string, number, integer, boolean, object, array, null
properties, required Fields of an object, and which must be present
additionalProperties false rejects fields that are not listed
minLength, maxLength, pattern String limits and regular expression
minimum, maximum Number bounds
enum A fixed list of allowed values
items, minItems, maxItems Array elements and size

You can write a small checker for this subset in a few lines. Here the schema is plain data, exactly as you would give it to ajv, and our function is the "engine".

Node.js A JSON Schema subset validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real ajv supports the whole specification (oneOf, $ref, formats such as email and date-time, conditionals), compiles schemas to fast code, and reports errors in a standard format. Do not use this teaching version in production.

Sanitizing and normalizing

After the shape is right, look at the content.

  • Trim and normalize. Trim whitespace, and for identifiers like emails use toLowerCase(). Unicode text can have several byte-level spellings of the same visible characters, so text.normalize('NFC') makes comparisons consistent.
  • Allow-list, do not block-list. Define what is permitted (letters, digits, specific enum values) instead of trying to list what is dangerous.
  • Limit sizes. Cap string lengths, array sizes, nesting depth and body size. A schema without maximums invites memory attacks.
  • Escape on output, not on input. Store the user's text as typed and escape for the destination (HTML, SQL, shell) when you write it there. Better still, use mechanisms that avoid the problem: parameterized queries for SQL and templating engines that escape HTML by default.
  • Beware special keys. A JSON body with the key __proto__ can attack code that merges objects carelessly (prototype pollution). JSON.parse creates it as a harmless own property, but copying it with a naive deep-merge function is where trouble starts. Building your result object from a schema's known keys, as our mini-library did, avoids this.
Node.js Cleaning up text input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The control character, tabs and extra spaces were cleaned up, and the dangerous-looking HTML was only made harmless when escaped for output. (The order of the steps matters: removing every control character first would also delete the newline and tab and glue words together, so we keep whitespace characters and collapse them afterwards.)

Now the last lines. JSON.parse stores __proto__ as an ordinary own key, so parsing alone pollutes nothing (Object.prototype is untouched). But Object.assign then assigns to copy.__proto__, which triggers the special setter and changes the prototype of copy: the copy suddenly "has" isAdmin: true through inheritance, without that being one of its own keys. A recursive merge helper that assigns into target[key] can go one step further and modify Object.prototype itself, which is called prototype pollution. This is why allow-listing the keys you accept, as the schema did, is the safe approach.

Error messages that help

A validation error is part of your API. Compare {"error": "invalid"} with this:

JSON
{
  "type": "https://example.com/problems/validation",
  "title": "Your request has problems",
  "status": 422,
  "errors": [
    { "path": "items.1.quantity", "message": "must be an integer" },
    { "path": "customer.email", "message": "has the wrong format" }
  ]
}

Good habits:

  • Return all problems at once, with a machine-readable path and a human-readable message.
  • Use status 400 for a body that cannot be parsed at all (broken JSON) and 422 for well-formed data that fails the rules. Many APIs use 400 for both; choose one convention and document it (see Designing REST APIs).
  • Never echo secrets back, and never reveal internals such as stack traces, SQL or file paths.
  • Write messages for the person fixing the problem: say what is expected ("must be at most 40 characters"), not just what is wrong ("invalid").
  • For passwords and login forms, keep messages deliberately generic where specificity would leak information (for example, whether an email exists).

Here is the whole flow in an HTTP server: parse the JSON, validate with a schema, answer 400, 422 or 201.

Node.js Validation at the HTTP boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the first payload reached users. The others were rejected at the boundary with the right status code and a useful body.

Validating configuration and environment at startup

Environment variables are untrusted input too, and they are all strings. A missing DATABASE_URL or a PORT of "eighty" should stop the app at boot with a clear report, not break the first request an hour later. Validate once, build a typed config object, and pass that around instead of reading process.env everywhere. See also Configuration, Secrets and Environment.

Node.js Fail fast: validating environment variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reporting every problem at once saves the "fix one, restart, find the next" loop. In production the app would print this message and exit with a non-zero code before opening any port.

Types and validation

TypeScript checks types while you write code, but its types vanish when the program runs, so they cannot protect you from a bad request body. The common solution is to define the schema once and derive the TypeScript type from it, so the two cannot disagree. With zod, for example, type Order = z.infer<typeof Order> gives you the type of the validated data (read-only; it needs TypeScript and zod). Another approach is to write a type guard, a function that returns value is Order, and call it at the boundary; see Type guards and Narrowing in the TypeScript tutorial. In both cases the pattern is the same: unknown data goes in, validation happens once, and typed data comes out.

TypeScript
import { z } from 'zod';

const User = z.object({ name: z.string(), age: z.number().int().optional() });
type User = z.infer<typeof User>;          // { name: string; age?: number | undefined }

function handle(body: unknown) {
  const user: User = User.parse(body);      // throws unless body really matches
  return user.name.toUpperCase();
}

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a server validate input even if the browser form already checks it?

    Client-side validation is for convenience. Attackers and scripts talk directly to your API, so the server must enforce every rule.
  2. 2. What does it mean for a schema to strip unknown keys, and why is that useful?

    Only the fields you declared reach your code, so a client cannot sneak extra properties into a record you build from the body.
  3. 3. Which status code best fits a request with well-formed JSON that fails your business rules?

    The server understood the request but the data is not acceptable. 500 would wrongly suggest a server bug, and 200 would hide the problem.
  4. 4. Why validate environment variables once at startup?

    Failing fast shows every configuration problem at boot time and gives the rest of the code a trusted, typed config object.
  5. 5. A TypeScript type says a request body is { name: string }. Why is it not enough on its own?

    Types are erased when the code runs. You need runtime validation at the boundary, and libraries like zod derive the type from the schema so both agree.

Summary

  • Treat all external data (bodies, queries, headers, files, environment variables) as untrusted and check it once, at the boundary.
  • Validation checks, parsing converts to the right types, sanitizing cleans or escapes; a good schema library does the first two together and returns a trusted value.
  • Collect every problem with a path and a helpful message; use 400 for unparseable input and 422 (or your documented convention) for rule violations.
  • Schemas should strip unknown keys, set maximum sizes and use allow-lists; escape for the destination on output.
  • zod and valibot give TypeScript-friendly schemas; ajv and JSON Schema give language-neutral, fast, shareable ones.
  • Validate configuration at startup and exit with a clear message if anything is wrong.
  • Derive types from schemas (or use type guards) so compile-time types and runtime checks stay in agreement.

Next: Logging and Observability