Sub topic 17
Sharing one schema between client and server
This chapter assumes you have built a form with useForm and zodResolver, and that you know how setError works. You should also be comfortable with async/await and with TypeScript's z.infer.
Why share a schema
Client-side validation improves the user experience, but it does not protect your API. Anyone can send a request without your form. The server must validate every request itself.
If you write the rules twice, the two copies drift apart. The client accepts a value the server rejects, or the reverse. A single schema module that both sides import removes that problem.
Put the schema in its own module
The module should contain only the schema and its types. It should not import React, the database, or anything specific to one environment.
// 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>;The form imports this file for zodResolver(signUpSchema). The server imports the same file to check the request body.
Validate again on the server
On the server, use safeParse. It returns a result object instead of throwing. When parsing fails, flatten().fieldErrors gives a map from field name to a list of messages.
// app/api/sign-up/route.ts
import { signUpSchema } from "../../../shared/sign-up-schema";
export async function POST(request: Request) {
const body: unknown = await request.json();
const result = signUpSchema.safeParse(body);
if (!result.success) {
return Response.json(
{ fieldErrors: result.error.flatten().fieldErrors },
{ status: 400 }
);
}
// result.data is typed as SignUpValues and has passed every rule.
return Response.json({ ok: true }, { status: 201 });
}Treat request.json() as unknown. Only result.data is safe to use as typed data.
Show server field errors in the form
Because the server uses the same field names as the form, you can pass its messages straight to setError.
import type { UseFormSetError } from "react-hook-form";
import type { SignUpValues } from "../shared/sign-up-schema";
export function applyServerErrors(
fieldErrors: Partial<Record<keyof SignUpValues, string[]>>,
setError: UseFormSetError<SignUpValues>
) {
for (const [name, messages] of Object.entries(fieldErrors)) {
if (messages?.length) {
setError(name as keyof SignUpValues, {
type: "server",
message: messages[0],
});
}
}
}Call it in onSubmit when the response status is 400.
Common problems
- Transforms differ in meaning. The server receives the JSON the client sends. If the schema uses
transformon a string, the client'shandleSubmitgives you the output type. Send the output only if the server schema expects it. Otherwise send the raw input, and let the server run the transform. - Server-only rules do not belong in the shared file. Checks such as "email is not taken" need a database. Do them after
safeParseand report them with a 409 status. - Bundle size and secrets. Anything in the shared module ships to the browser. Keep it free of secrets and server imports.
Exercise
Why must the server call safeParse even though the form already validates with zodResolver? Name one rule that should not live in the shared schema.
Show answer
Requests can be sent without the form, so the browser check cannot be trusted. The server must validate every body itself. A rule that needs a database lookup, such as checking that an email is not already registered, should stay out of the shared schema and run on the server after safeParse succeeds.