Input Validation — Node.js

Don't trust data from the client: check it before storing it. That check is called validation. With no validation, {"title":""} still gets a 201 and is…

The frontend form (the web page people use) already has required, the HTML attribute that makes a field mandatory. So a note's title can't be empty. Sounds safe, until someone sends a request directly with curl, without going through the form at all. Your server takes whatever arrives: from a tidy form, from curl, or from someone just trying things.

That's why the server needs validation: checking the data a client sends before you use or store it. When something is wrong, like a required field left empty or a number where text should be, the data is refused with a message that says what's wrong, and it isn't processed.

With no validation, everything gets in

The POST route from the CRUD lesson takes title and content and stores them right away:

Body sent Answer (no validation)
{"title":"","content":"run 5 km"} 201 {"id":3,"title":"","content":"run 5 km"}
{"title":123,"content":"run 5 km"} 201 {"id":4,"title":123,"content":"run 5 km"}
{} 201 {"id":5}

All of them are 201 Created. A note with no title is stored too. Broken data like this is only noticed later, when the frontend tries to display a title that is empty or a number.

Manual validation: collect the errors, then 400

The check is written as middleware, validateNote, placed before the POST handler:

function validateNote(req, res, next) {
  const { title, content } = req.body;
  const errors = [];
  if (typeof title !== "string" || title.trim() === "") {
    errors.push("title is required");
  } else if (title.length > 50) {
    errors.push("title is at most 50 characters");
  }
  if (typeof content !== "string") {
    errors.push("content must be text");
  }
  if (errors.length > 0) {
    return res.status(400).json({ errors });
  }
  next();
}

app.post("/notes", validateNote, (req, res) => {
  const { title, content } = req.body;
  const newNote = { id: nextId++, title, content };
  notes.push(newNote);
  res.status(201).json(newNote);
});

The answers now, with validation:

Body Answer
{"title":"","content":"run 5 km"} 400 {"errors":["title is required"]}
{"title":"Workout"} 400 {"errors":["content must be text"]}
{} 400 {"errors":["title is required","content must be text"]}
{"title":"Workout","content":"run 5 km"} 201 {"id":3,"title":"Workout","content":"run 5 km"}

Zod: the rules written as a schema

The same rules can be written more briefly with Zod, a library for validation (npm install zod). In Zod, the rules are written as a schema: a description of the shape of the data you accept, meaning which fields there are and what each field must look like. Here is the same POST route, validated with Zod:

const { z } = require("zod");

const NoteSchema = z.object({
  title: z.string().trim().min(1).max(50),
  content: z.string(),
});

app.post("/notes", (req, res) => {
  const result = NoteSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ errors: z.flattenError(result.error).fieldErrors });
  }
  const newNote = { id: nextId++, ...result.data };
  notes.push(newNote);
  res.status(201).json(newNote);
});

Here are the answers, exactly as the server sends them. The messages are Zod 4's built-in ones:

Body Answer
{"title":"","content":"run 5 km"} 400 {"errors":{"title":["Too small: expected string to have >=1 characters"]}}
{"title":123,"content":"run 5 km"} 400 {"errors":{"title":["Invalid input: expected string, received number"]}}
{"title":"Workout"} 400 {"errors":{"content":["Invalid input: expected string, received undefined"]}}
{"title":" Workout ","content":"run 5 km"} 201 {"id":3,"title":"Workout","content":"run 5 km"}

Other popular libraries for validation in Express: express-validator (its rules go on the route as middleware) and Joi (uses schemas, like Zod).

📌 400 or 422?

Most Express APIs answer data that fails validation with 400 Bad Request. Some APIs, for example ones built with Laravel (a PHP framework), use 422 Unprocessable Content: the request was read, but its content can't be processed. Both are fine. What matters is that one API uses the same status on all of its routes.

In the exercise: validateUser with no server

In the exercise, the function validateUser(data) works like validateNote, but doesn't answer a request. It returns the object { valid, errors }. Its rules and messages must be exact:

valid holds errors.length === 0 (already in the starter). When the rules are right, the starter prints the results of three tests:

Test 1 (valid): {"valid":true,"errors":[]}
Test 2 (invalid): {"valid":false,"errors":["name is required","email must be valid"]}
Test 3 (negative age): {"valid":false,"errors":["age must be a positive number"]}

⚠️ Small gaps in validation

TL;DR: Don't trust data from the client: check it before storing it. That check is called validation. With no validation, {"title":""} still gets a 201 and is stored. Manual validation collects messages in an errors array, then answers 400 with if (errors.length > 0) return res.status(400).json({ errors }). That code is tidiest as middleware placed before the handler. With the Zod library, you write the rules as a schema (a description of the data you accept), for example z.string().trim().min(1).max(50). safeParse returns success and data, or error, with messages like Too small: expected string to have >=1 characters. Store result.data (the cleaned-up data from safeParse), not req.body. Other libraries: express-validator and Joi. The status for wrong data: 400 Bad Request.

⚡ The server can't trust anyone

Guess first: the note form on the web page already uses required (the field is mandatory). If someone sends {"title":""} with curl, what does the POST /notes route with no validation answer?

201, and a note with no title is stored too. curl sends the request directly to the server, so a form with required doesn't stop it.

Meaning: Validation means checking the data a client sends before you use or store it. Server validation is a must. Browser validation is only for the user's comfort.

⚡ Collect the errors, answer 400

Write:

const errors = [];
if (typeof title !== "string" || title.trim() === "") {
  errors.push("title is required");
}
if (errors.length > 0) {
  return res.status(400).json({ errors });
}
next();

Meaning: This code is part of a validation middleware, and title comes from req.body. Every broken rule adds one message to errors, so the client learns everything that's wrong at once. If there are errors, the middleware answers 400 Bad Request, then stops with return. If there are none, next() passes the request on to the handler.

⚡ Zod: the rules as a schema

Write:

const NoteSchema = z.object({
  title: z.string().trim().min(1).max(50),
  content: z.string(),
});

const result = NoteSchema.safeParse(req.body);

Meaning: Zod is a validation library, used through z. A schema is a description of the data you accept. Here title must be a string, the spaces at its edges are removed, and then its length must be 1 to 50 characters. When the data is wrong, safeParse doesn't throw an error. It returns success and data, or error. Store result.data, the cleaned-up version, not req.body.

What you will learn