Zod validation on client side and server router?

Hi, I am currently using zod to validate my react-hook-form on the client side, I see that the t3 creation has also zod on the backend server route, should I validate using the same zod schema? I thought of extracting the schema to import it on the client and on the backend to not have duplicate schemas. Not sure if there is a difference.
4 Replies
Samathingamajig
If you want to use the same schema, instead of overcomplicating it by trying to pull it out of tRPC dynamically, define the schema outside and import in your frontend
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Samathingamajig
import { t } from "../trpc";
import { z } from "zod";

export const helloSchema = z.object({ text: z.string().nullish() }).nullish();

export const exampleRouter = t.router({
hello: t.procedure.input(helloSchema).query(({ input }) => {
return {
greeting: `Hello ${input?.text ?? "world"}`,
};
}),
});
import { t } from "../trpc";
import { z } from "zod";

export const helloSchema = z.object({ text: z.string().nullish() }).nullish();

export const exampleRouter = t.router({
hello: t.procedure.input(helloSchema).query(({ input }) => {
return {
greeting: `Hello ${input?.text ?? "world"}`,
};
}),
});
and then in frontend
import { helloSchema } from "../../idk/find/the/server/file";
import { helloSchema } from "../../idk/find/the/server/file";
you might need to bring the schema to another file, just to be sure that treeshaking isn't including any backend logic in your frontend
utdev
utdevOP3y ago
Thanks!
Want results from more Discord servers?
Add your server