In create-t3-app how to get tRPC zod schema on client?
I know we have
RouterInputs
to get the input type, but can we get the zod schema to validate things on the client?
Of course we could just export the schema from each router file and import it in the client, but I imagine something like this would be very ergonomic:
(this is just an example, it could be a different object for the schemas)
What do you think?6 Replies
this wouldn't work because the only thing that the frontend imports from the backend is a type
there is zero backend code included in the frontend bundle by default
your best bet is defining the schema outside of the router itself, and then importing it in the frontend
Yeah, but then I would have to declare 2 things for each procedure and then import 2 things for each. I was hoping for some way to automate this. Maybe by traversing the router and getting the schemas, but not sure how feasible/secure this is. I wonder how it's done in practice (I searched theo's repos but couldn't find client side validation)
Yeah but I think there must be a better solution. Importing random ui component files in your router doesn't seem ideal, especially as it becomes more complex. What I love about trpc is the simplicity of defining a procedure in one place and then being able to use it. I wonder what people do in practice. On a related note - do you know any library for automatically generating forms from a schema? Something like jsonforms
I'm not sure this is what you want but check this out https://github.com/chrishoermann/zod-prisma-types
GitHub
GitHub - chrishoermann/zod-prisma-types: Generator creates zod type...
Generator creates zod types for your prisma models with advanced validation - GitHub - chrishoermann/zod-prisma-types: Generator creates zod types for your prisma models with advanced validation
The routers are backend only. Just put all your reused schemas in a file and import them on client and server. Don't mangle your backend and frontend structures for no reason.