Sub topic 17
Sharing one schema between client and server
This chapter assumes you have built a form with useForm and zodResolver, that you know z.infer, and that you have used setError after a failed request. It also assumes you can read a fetch call and a request handler that returns JSON.
Why share a schema
The browser check improves the user experience. It does not protect anything, because any client can send a request that skips your form. The server must validate again.
If you write the rules twice, the two copies drift apart. The client accepts a value the server rejects, or the reverse. A single Zod schema in a module both sides import removes that drift, and the same file gives both sides the same TypeScript type.
The shared module
Put the schema in a file that has no browser-only and no server-only imports. It should depend on zod and nothing else.
// src/shared/sign-up-schema.ts
import { z } from "zod";
export const signUpSchema = z.object({
email: z.string().min(1, "Email is required").email("Enter a valid email"),
password: z.string().min(8, "Use at least 8 characters"),
});
export type SignUpValues = z.infer<typeof signUpSchema>;
export type FieldErrors = Record<string, string>;
// Keeps the first message for each field path, for example "items.0.name".
export function toFieldErrors(error: z.ZodError): FieldErrors {
const result: FieldErrors = {};
for (const issue of error.issues) {
const key = issue.path.join(".");
if (!(key in result)) result[key] = issue.message;
}
return result;
}toFieldErrors is shared as well, so the server and the client agree on the shape of an error response. It reads error.issues, which exists in every Zod version.
The server side
The server parses the request body with the same schema. Use safeParse, which returns a result object and does not throw.
// src/app/api/sign-up/route.ts (a Fetch-style handler)
import { signUpSchema, toFieldErrors } from "../../../shared/sign-up-schema";
export async function POST(request: Request): Promise<Response> {
let body: unknown;
try {
body = await request.json();
} catch {
return Response.json({ errors: { form: "Invalid JSON" } }, { status: 400 });
}
const parsed = signUpSchema.safeParse(body);
if (!parsed.success) {
return Response.json({ errors: toFieldErrors(parsed.error) }, { status: 400 });
}
const { email, password } = parsed.data;
const taken = await emailExists(email);
if (taken) {
return Response.json(
{ errors: { email: "This email is already registered" } },
{ status: 409 },
);
}
await createUser(email, password);
return Response.json({ ok: true }, { status: 201 });
}
// Stand-ins for your data layer.
declare function emailExists(email: string): Promise<boolean>;
declare function createUser(email: string, password: string): Promise<void>;Use parsed.data from here on, not body. parsed.data is typed, and Zod strips unknown keys from objects by default, so extra properties a client sends do not reach your database.
The flow looks like this:
The client side
The form is the one from earlier chapters. Only the import changes, and onSubmit gains a mapping step.
// src/components/SignUpForm.tsx
import { useForm } from "react-hook-form";
import type { FieldPath, FieldValues, UseFormSetError } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
signUpSchema,
type SignUpValues,
type FieldErrors,
} from "../shared/sign-up-schema";
function applyServerErrors<T extends FieldValues>(
setError: UseFormSetError<T>,
errors: FieldErrors,
) {
for (const [name, message] of Object.entries(errors)) {
setError(name as FieldPath<T>, { type: "server", message });
}
}
export function SignUpForm() {
const {
register,
handleSubmit,
setError,
formState: { errors, isSubmitting },
} = useForm<SignUpValues>({
resolver: zodResolver(signUpSchema),
defaultValues: { email: "", password: "" },
});
const onSubmit = async (values: SignUpValues) => {
const response = await fetch("/api/sign-up", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (response.status === 400 || response.status === 409) {
const data: { errors: FieldErrors } = await response.json();
applyServerErrors(setError, data.errors);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="email">Email</label>
<input id="email" type="email" {...register("email")} />
{errors.email && <p role="alert">{errors.email.message}</p>}
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register("password")} />
{errors.password && <p role="alert">{errors.password.message}</p>}
<button type="submit" disabled={isSubmitting}>
Create account
</button>
</form>
);
}Dotted names such as items.0.name work with setError, so the same helper covers field arrays. The form key from the invalid-JSON branch is not a registered field. Handle it separately, for example by showing it above the form, if you expect it to happen.
What to share and what to keep on the server
Not every rule belongs in the shared file. Use this table to decide.
| Rule | Where it lives | Reason |
|---|---|---|
| Required, length, format, ranges | Shared schema | Pure functions of the input |
| Cross-field `refine` checks | Shared schema | Also pure, and `path` controls where the error appears |
| Email already registered | Server only, after parsing | Needs the database |
| Permission or rate checks | Server only | Depends on the session and server state |
| Secret or internal constants | Server only | The shared file ships to the browser |
You can run an async check inside refine in the shared schema, but then the server needs parseAsync, and the check would run in the browser too. Keep database checks out of the shared file and report them with a 409 and setError.
Gotchas with transforms and types
A schema with .transform has different input and output types, as covered in the earlier chapter on transforms. When the client posts data, decide which type travels over the wire.
Take a quantity field defined as z.string().regex(/^\d+$/).transform(Number). The form's handleSubmit callback receives the output, a number. If you send that number to the server, the same schema rejects it, because the input type is a string.
You have two options:
- Send the raw input (
getValues()or a string-typed copy) and let the server transform it. - Define a separate server schema that accepts the output type.
Option 1 keeps a single schema. It is usually the simpler choice, because the server always receives the same shape the schema describes as input.
Other points to keep in mind:
- Status codes. Use 400 (or 422) for schema failures and 409 for conflicts. The client above treats both as field errors, but other statuses such as 500 need a general message.
- Unknown keys. A server error key that matches no registered field still calls
setError. React Hook Form stores it, but nothing displays it. Log mismatches during development. - Versions. Pin the same
zodversion on both sides. In a monorepo, make the shared package a single dependency, so a client and server running different Zod versions do not parse differently. - Passwords.
confirmPasswordfrom the refine example is a client concern. Strip it before storing, or keep the base object and the refined schema separate so the server can use the base object.
Summary
- One schema module gives the browser and the server the same rules and the same TypeScript type.
- The server must always call
safeParseand useparsed.data. - Return errors as a map from field path to message, and apply them with
setError. - Keep rules that need a database or session on the server.
- With transforms, send the schema's input type, not its output.
Exercise
Your shared schema transforms quantity from a string to a number. The form's onSubmit sends values (where quantity is already a number) to the server, which parses with the same schema and returns 400 for every request. What is wrong, and how do you fix it?
Show answer
The server schema expects the input type, a string, but the client sent the output type, a number, so regex fails on a non-string. Fix it by sending the raw input (for example JSON.stringify(getValues()), whose quantity is still a string), letting the server run the transform, or by giving the server a separate schema that accepts a number.
Exercise
A signup needs to reject emails that already exist in the database. Should that check go in the shared schema? Where should it go, and how does the user see the error?
Show answer
No. It needs the database, and the shared file is bundled for the browser. Run it in the handler after safeParse succeeds, return status 409 with { errors: { email: "..." } }, and in the form call setError("email", { type: "server", message }) so the message appears in errors.email.