# Validating with Zod

Zod writes a request body's rules as a schema, an object that describes the shape the data must have, and safeParse checks a body against it, giving back either the cleaned data or a list of issues that the API turns into its field problems.

Journeyman · Node.js · REST API · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Write a Zod schema for a request body and check a body against it with safeParse
- Turn Zod's issues into the API's list of field problems, and reuse a schema for PATCH with partial()

## Key takeaways

- A Zod schema is the rules written as data. z.object lists the fields, and each field's chain, such as z.string().trim().min(1), says what that field must be.
- safeParse never throws. When the body passes, success is true and data holds the cleaned values. When it doesn't, success is false and error.issues lists every problem.
- The data safeParse gives back is trimmed and holds only the schema's fields, so a field the client sneaks in, such as an id, is dropped.
- Each issue has a path, the field it's about, and a message. Mapping them to { field, message } gives the API the same problem list as checking by hand.
- schema.partial() makes every field optional, so one ticket schema checks both a new ticket and a PATCH that sends only some fields.

Most Node APIs you'll work on check their request bodies with a schema library, and Zod is one you'll meet often in new projects. Once you've read one Zod schema, you can read the rules of any API that uses it, and add a field to it in a line.

*Checking Input by Hand* gave Spoke & Chain's `POST /tickets` route a `validateTicket` function, about twenty lines of `if`s for four fields. The shop now wants `PATCH /tickets/:id` checked too. A PATCH sends only some fields, so `validateTicket` doesn't fit: it reports every missing field as required. A second function would mean the same rules written twice, and the day someone changes one copy and forgets the other, the two routes disagree.

## A schema: the rules written as data

A **schema** is a description of the shape data must have: which fields, what kind of value each one holds, and its limits. You write it once, and a library checks any value against it. Install **Zod**, the schema library this course uses, in your project's terminal:

```bash
npm install zod
```

```text
added 1 package, and audited 2 packages in 1s

1 package is looking for funding
  run `npm fund` for details

found 0 vulnerabilities
```

`package.json` now lists `"zod": "^4.6.7"`. Here are the ticket's four rules as a Zod schema:

```javascript
import * as z from "zod";

const ticketSchema = z.object({
  customer: z.string().trim().min(1),
  bike: z.string().trim().min(1),
  problem: z.string().trim().min(1).max(200),
  status: z.enum(["waiting", "in repair", "ready", "picked up"]).optional(),
});

const result = ticketSchema.safeParse({
  customer: " Lena ",
  bike: "folding bike",
  problem: "gears won't shift",
  id: 99,
});
console.log(result);
```

```text
{
  success: true,
  data: {
    customer: 'Lena',
    bike: 'folding bike',
    problem: "gears won't shift"
  }
}
```

Read each field's chain from left to right. `z.string()` says it must be text, `.trim()` takes the spaces off both ends, `.min(1)` says at least one character is left, and `.max(200)` at most 200. `z.enum([...])` allows only the values in the list, and `.optional()` lets the field be left out. A field without `.optional()` is required. `import * as z` brings everything Zod offers in under one name, `z`.

`safeParse` checked the body and gave back `success: true` and `data`. Look closely at `data`: Lena's name is trimmed, and the `id: 99` the client sent is gone. A Zod object keeps only the fields its schema lists, so a caller can't choose a ticket's id by sneaking one in.

## When the body breaks a rule

Now a body with four mistakes: a number for a name, a blank bike, no problem at all, and a status the shop doesn't use:

```javascript
const result = ticketSchema.safeParse({ customer: 42, bike: "   ", status: "fixed?" });
console.log(result.success);
for (const issue of result.error.issues) {
  console.log(issue.path, issue.message);
}
```

```text
false
[ 'customer' ] Invalid input: expected string, received number
[ 'bike' ] Too small: expected string to have >=1 characters
[ 'problem' ] Invalid input: expected string, received undefined
[ 'status' ] Invalid option: expected one of "waiting"|"in repair"|"ready"|"picked up"
```

Zod checked every field and collected every problem, as the hand-written version did. Each **issue** has a `path`, a list naming the field it's about, and a `message`. The blank bike counts as too short because `.trim()` ran before `.min(1)`. `safeParse` never throws: whatever arrives, you get an object back and check `success`. Its sibling, `parse`, gives back the data alone and throws an error when the body breaks a rule.

## Turning issues into the API's problem list

The API already answers with a list of `{ field, message }` problems, and a caller shouldn't have to care which way the server checks. One small function turns Zod's issues into that list. `path.join(".")` turns `['customer']` into `"customer"` (and a field inside another, `['address', 'city']`, into `"address.city"`):

```javascript
function toProblems(issues) {
  return issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
}

app.post("/tickets", (req, res) => {
  const result = ticketSchema.safeParse(req.body ?? {});
  if (!result.success) {
    res.status(400).json({ message: "The ticket isn't valid.", problems: toProblems(result.error.issues) });
    return;
  }
  const ticket = {
    id: nextId,
    customer: result.data.customer,
    bike: result.data.bike,
    problem: result.data.problem,
    status: result.data.status ?? "waiting",
  };
  nextId = nextId + 1;
  tickets.push(ticket);
  res.status(201).json(ticket);
});
```

The route builds the ticket from `result.data`, the checked and trimmed values, never from `req.body`. Zod's messages are clear enough to send as they are. To word one your own way, give the rule an `error`, as the shop did for `status`:

```javascript
  status: z
    .enum(["waiting", "in repair", "ready", "picked up"], {
      error: "status must be one of: waiting, in repair, ready, picked up.",
    })
    .optional(),
```

With that rule in the schema, the same four mistakes sent to the route get:

```text
POST /tickets  { "customer": 42, "bike": "   ", "status": "fixed?" }
HTTP/1.1 400 Bad Request
{"message":"The ticket isn't valid.","problems":[{"field":"customer","message":"Invalid input: expected string, received number"},{"field":"bike","message":"Too small: expected string to have >=1 characters"},{"field":"problem","message":"Invalid input: expected string, received undefined"},{"field":"status","message":"status must be one of: waiting, in repair, ready, picked up."}]}
```

## One schema for PATCH: partial()

`ticketSchema.partial()` makes a new schema with every field optional and every other rule kept. A PATCH can leave fields out, but whatever it sends must still follow the ticket's rules:

```javascript
const ticketChangesSchema = ticketSchema.partial();

console.log(ticketChangesSchema.safeParse({ status: "ready" }));
console.log(ticketChangesSchema.safeParse({ status: "done" }).success);
console.log(ticketChangesSchema.safeParse({ bike: "" }).success);
console.log(ticketChangesSchema.safeParse({}).success);
```

```text
{ success: true, data: { status: 'ready' } }
false
false
true
```

In the PATCH route, `Object.assign(ticket, result.data)` copies every field of the checked data onto the ticket. That's safe because the data holds only the schema's fields: `PATCH /tickets/2` with `{ "status": "ready", "id": 7 }` answers ticket 2, now ready, with its id still 2. Change a rule in `ticketSchema`, and both routes follow it.

## Check yourself

2 questions to try on the lesson page.

## So what

A schema is one place where an API's rules live, so the routes stay short, the rules can't drift apart, and anyone who opens the file can read exactly what each request must look like.

## Key terms

- [Zod](https://www.ask-codey.com/glossary/zod)
- [Validation Schema](https://www.ask-codey.com/glossary/validation-schema)
- [Server-Side Validation](https://www.ask-codey.com/glossary/server-side-validation)
- [400 Bad Request](https://www.ask-codey.com/glossary/400-bad-request)

## Related

- [Checking Input by Hand](https://www.ask-codey.com/lessons/node-validation-by-hand)
- [Error Handling and Consistent Error Responses](https://www.ask-codey.com/lessons/node-express-error-handling)

Source: https://www.ask-codey.com/lessons/node-validation-with-zod
