Centralized Zod Schema Management for a Next.js Project
Created by Prompts-GPT
Design a centralized, scalable, and maintainable validation and typing system using Zod in a Next.js project. All schemas must be defined in a single, centralized location (e.g., lib/schemas/ or schemas/) using Zod to act as the source of truth for both runtime validation and TypeScript static types across the entire application — including API routes, form validation in UI, Prisma models, and external API data ingestion. Key requirements: Centralization: Define all entity schemas (e.g., UserSchema, ProductSchema, PostSchema, etc.) in reusable Zod schema files. Export both the Zod schema and its inferred TypeScript type (z.infer<typeof UserSchema>) for strict type-checking throughout the app. Validation Everywhere: In API routes (/api), validate incoming request bodies, query parameters, and headers using the relevant Zod schemas. In React forms, use Zod schemas with form libraries like React Hook Form or Formik via adapters. In seed scripts or background jobs, validate any external API data before inserting it into the database. Prisma Compatibility: Optionally generate Zod schemas from the Prisma schema using tools like @anatine/zod-prisma-types or define schemas manually to ensure compatibility. Sync field types (e.g., enums, optionality, nullability) between Prisma and Zod without duplication. Transformations & Defaults: Use Zod's .transform() and .default() methods to normalize and enrich incoming data before usage. Include coercion for strings, numbers, dates, etc., as needed for API or form inputs. Error Management: Integrate a global error handler for Zod validation errors in both API routes and UI. Return structured, developer-friendly and user-friendly error messages. Extensibility & Maintenance: Each schema should be independently versionable and composable (e.g., UserCreateSchema, UserUpdateSchema, etc.). Document clearly how and where each schema is used. Avoid repetition and make types importable across server and client.