how do i pass a zod schema from a server component as a prop in a client component in next v14? i keep getting the error: "Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.", which i assume is because next cant serialise the schema. any workarounds?
#passing zod schema from a server component to client component
1 messages · Page 1 of 1 (latest)
Hi @tepid kraken. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Based on the information provided in the extracts, it seems that you're encountering an issue because Zod schemas are not serializable by React. In Next.js, props passed from Server Components to Client Components need to be serializable by React. If your Client Components depend on data that is not serializable, you can fetch data on the client with a third party library or on the server via a Route Handler (source (https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#passing-props-from-server-to-client-components-serialization)).
Unfortunately, passing a Zod schema directly from a Server Component to a Client Component is not supported due to the serialization requirement. A potential workaround could be to convert the Zod schema to a serializable format on the server side, pass it to the client, and then reconstruct it on the client side. However, this approach might not be feasible if the Zod schema contains complex validation logic that cannot be easily serialized and reconstructed.
Another approach could be to perform the validation on the server side and pass the validation result to the client. For example, you could use a Next.js API route to accept the form data, validate it using the Zod schema, and return the validation result. The client can then submit the form data to this API route and handle the validation result.
Here's an example of how you might use Zod for server-side validation in a Next.js API route (source (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#form-validation)):
import type { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const parsed = schema.parse(req.body)
// ...
}
In this example, the handler function receives the form data in req.body, validates it using the Zod schema, and returns the validation result. The client can then handle the validation result as needed.