Validating on the client and the server

Intermediate · 28 min

Write one Zod schema, run it in the browser for fast feedback and again on the server for safety, and treat only the server's check as the one that counts.

Before thisShared types and code between client and serverEnd-to-end type safety

Cosden Solutions · 28 min

Validating on the client and the server

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Cosden SolutionsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Client-side validation exists for speed and kindness, and server-side validation exists for safety, so you need both and they do different jobs.
  • A request can reach the API without ever touching your form, for example from curl, so the server can never assume the client validated anything.
  • One shared Zod schema keeps the two checks from drifting, because the rule is written once and the inferred type comes from it.
  • Zod transforms such as trim and default run on parse, so the value the server stores can differ from the raw input.
  • Some rules can only be checked on the server, such as whether an email is already registered, and they must come back as field errors the form can display.

Two checks, two jobs

Imagine the signup form shows “Use at least 10 characters” the moment the password field loses focus. That message is kindness: it saves the user a round trip. It is also entirely optional from a security standpoint, because the person on the other end can skip your form and run:

curl -X POST /api/signup -d '{"email":"nope","password":"x"}'

So the rule has two jobs. In the browser it exists for speed and clear messages. On the server it exists to refuse bad data, and nothing else is allowed to be trusted. Input validation and injection attacks covers why the server side is not negotiable.

The trouble is that two jobs usually means two copies of the rule, and two copies disagree. The browser says 8 characters and the server says 10, and users are told “fine” and then rejected.

One schema, written once

Taskboard keeps its rules in a file both sides can import:

import { z } from "zod";

export const createTask = z.object({
  title: z.string().trim().min(1, "Give the task a title").max(120),
  status: z.enum(["todo", "doing", "done"]).default("todo"),
  assigneeId: z.number().int().positive().optional(),
});
export type CreateTask = z.infer<typeof createTask>;

I ran this schema (Zod 4.6.7) on input a hurried user might send:

createTask.safeParse({ title: "   ", status: "blocked" })

It failed with:

{"fieldErrors":{"title":["Give the task a title"],"status":["Invalid option: expected one of \"todo\"|\"doing\"|\"done\""]}}

and createTask.parse({ title: " Ship it " }) returned {"title":"Ship it","status":"todo"}. Notice what happened: the whitespace was trimmed and the status defaulted. Parsing is not just checking, it is also normalising, so the value the server stores can differ from what was typed.

The .default("todo") is worth a pause. It means a client may omit status, and the inferred CreateTask type has status required on the output side. Zod distinguishes the input type from the output type for exactly this reason, which matters when you wire a form library to it.

Running it on the server

The API plugs the same schema into the route with @hono/zod-validator:

.post("/api/projects/:id/tasks", requireUser,
  zValidator("json", createTask, (r) => {
    if (!r.success)
      throw new ApiError(422, "validation", "Fix the highlighted fields",
        z.flattenError(r.error).fieldErrors);
  }),
  (c) => {
    const t = c.req.valid("json");   // typed, trimmed, defaulted
    ...
  })

The handler body only runs with data that passed, and c.req.valid("json") carries the right type, which is what made the end-to-end types lesson work. Sending the bad task over HTTP gave 422 with the same fields object shown above.

In Zod 4, the flattening helper is the function z.flattenError(error); the older error.flatten() method that appears in many tutorials is not on the error type the validator hands back. I hit that as a compile error, so if you are following an older video, expect to translate.

Running it in the browser

On the client, a form library calls the same schema before submitting. With React Hook Form it looks like this (from the library’s docs, not something I ran here):

const { register, handleSubmit, formState: { errors } } = useForm({
  resolver: zodResolver(createTask),
});

Errors appear next to each field as the user works. Because both sides import the same file, a rule change is one edit. The forms and form validation lesson covers the browser’s own constraint validation; the schema approach sits on top.

The rules the browser cannot check

Some rules need data only the server has:

  • Uniqueness. “That email already has an account.” I ran signup twice with the same address and the second returned 409 with {"fields":{"email":["Already registered"]}}.
  • Existence. The assigneeId must belong to a user on this project.
  • Permissions. Whether this user may do this at all.

These cannot be in the shared schema. Instead, make the server return them in the same shape as schema failures: a fields map keyed by input name. Then the form has one code path for showing field errors, whether they came from Zod in the browser or from the database on the server. The next lesson builds that shape properly, and forms from submit to database wires it into the UI.

Don’t validate the wrong thing

A quick checklist for deciding where a rule lives:

  • Format and length of a field: the shared schema.
  • Cross-field rules (“end date after start date”): the shared schema, with a refinement.
  • Anything that needs a lookup: the server only.
  • Anything that protects data: the server, always, even if the client also checks it.

What the video covers

Cosden Solutions’ “React Hook Form - Complete Tutorial (with Zod)” is about 28 minutes, published January 2024. Its description says it covers building a form with React Hook Form, writing your own validation, submitting the data, and finally using Zod for validation. It is client-side focused, and I did not find the server half in its description, so that half comes from this lesson. I could not read a transcript. Web Dev Simplified’s “Learn Zod In 30 Minutes” is linked as a deeper look at the schema library on its own.

Where this fits

Validation produces errors, and now the whole stack needs a consistent way to carry them from the database to a message on screen. Next: error handling across the stack.

Check yourself

  1. 01Why validate on the server if the form already validated?

    Anyone can send a request without using your form, so the browser's check protects the user experience and nothing else.

  2. 02What is the benefit of sharing one schema between client and server?

    The rules cannot disagree, and the TypeScript type is inferred from the schema, so a change to the rule updates both sides and the types together.

  3. 03What does the schema return for the title " " and the status "blocked"?

    Two field errors, one asking for a title because the value is empty after trim, and one saying status must be one of todo, doing or done.

  4. 04Which rule on the signup form cannot be checked in the browser?

    Whether the email is already taken, because only the server's database knows, so the server returns it as a field error.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark