Share Zod Validation Schema Between Server and Client

I recently encountered a scenario where the server and the client needed to use the same Zod validation schema.

The only solution I could find was to define the schema on the client and then import it on the server. However, sharing the validation schema from the client to the server is not the best idea.

Solution

My solution is to extract the validation schema (or schemas) in a separate file and import it (them) where necessary.

Let's take the following validation schemas as an example:

import * as z from "zod";

export const FormSchema = z.object({
  username: z.string(),
  email: z.string(),
  isAdmin: z.boolean(),
  createdAt: z.date(),
});

export const BlogPostSchema = z.object({
  title: z.string(),
  content: z.string(),
  url: z.string(),
  published: z.boolean(),
  cover_img: z.string(),
});

You could add the code in the src/utils/schemas.tsx file and import the schemas where needed.

If you are using Zod, you might be interested in these articles about form validation with React Hook Form and Zod and validating environment variables with Zod.