designing-zod-schemas
Designs Zod schemas following Zod-first development. Use when creating validation schemas, branded types, discriminated unions, transforms, refinements, or inferring TypeScript types with z.infer.
Works with
---
name: designing-zod-schemas
description: Designs Zod schemas following Zod-first development. Use when creating validation schemas, branded types, discriminated unions, transforms, refinements, or inferring TypeScript types with z.infer.
license: BSD-3-Clause
---
# Zod Schema Designer
## Overview
Guide the design and implementation of Zod schemas following the project's Zod-first development approach, where schemas are defined before implementing business logic.
## When to Use
- Creating new data structures
- Adding validation to inputs
- Designing configuration schemas
- Implementing type-safe transformations
- Creating test data builders
## Core Principles
### Zod-First Development
1. **Define Schema First**: Schema is the source of truth
2. **Infer Types**: Use `z.infer<>` instead of manual type definitions
3. **Share Validation**: Same schema for runtime validation and tests
4. **Compose Schemas**: Build complex schemas from primitives
### Decision Guide
| Need | Pattern | Example |
|------|---------|---------|
| Basic validation | Primitives | `z.string().min(1)` |
| Domain safety | Branded types | `transform((v) => v as EntitySlug)` |
| Multiple types | Discriminated union | `z.discriminatedUnion('type', [...])` |
| Cross-field rules | Refinement | `.refine((data) => ...)` |
| Data normalization | Transform | `.transform((v) => v.trim())` |
| Partial updates | Partial schema | `Schema.partial()` |
## Quick Reference
### Project Schema Conventions
```typescript
import { z } from 'zod';
// Slug-based entity (Categories, Products, Channels, etc.)
const SlugSchema = z.string().regex(/^[a-z0-9-]+$/);
// Name-based entity (ProductTypes, Attributes, TaxClasses, etc.)
const NameSchema = z.string().min(1).max(100).trim();
// Branded types for domain safety
const EntitySlugSchema = SlugSchema.transform((v) => v as EntitySlug);
// Standard entity shape
const EntitySchema = z.object({
name: z.string().min(1),
slug: z.string().regex(/^[a-z0-9-]+$/),
description: z.string().optional(),
});
// Always infer types from schemas
type Entity = z.infer<typeof EntitySchema>;
```
## Schema Patterns
For detailed patterns and examples, see:
- **[Primitive Patterns](references/primitive-patterns.md)**: Strings, numbers, enums, branded types
- **[Object Patterns](references/object-patterns.md)**: Objects, discriminated unions, arrays, transforms, refinements
- **[Testing Patterns](references/testing-patterns.md)**: Test data builders, schema validation tests
## Project Schema Location
```
src/modules/config/schema/
├── schema.ts # Main configuration schema
├── primitives.ts # Reusable primitive schemas
├── entities/ # Entity-specific schemas
│ ├── category.ts
│ ├── product.ts
│ └── ...
└── index.ts # Schema exports
```
## Validation Checkpoints
| Phase | Validate | Command |
|-------|----------|---------|
| Schema defined | No TS errors | `npx tsc --noEmit` |
| Types inferred | `z.infer` works | Check type in IDE |
| Validation works | `safeParse` tests | `pnpm test` |
## Common Mistakes
| Mistake | Issue | Fix |
|---------|-------|-----|
| Manual type definitions | Type drift | Use `z.infer<typeof Schema>` |
| Using `.parse()` directly | Throws on invalid | Use `.safeParse()` for error handling |
| Missing `.optional()` | Runtime errors | Mark optional fields explicitly |
| Complex refinements | Hard to debug | Break into smaller schemas |
| Not using branded types | Type confusion | Use `.brand()` or transform for domain safety |
## External Documentation
For up-to-date Zod patterns, use Context7 MCP:
```
mcp__context7__get-library-docs with context7CompatibleLibraryID: "/colinhacks/zod"
```
## References
- `{baseDir}/src/modules/config/schema/schema.ts` - Main schema definitions
- `{baseDir}/docs/CODE_QUALITY.md#zod-first-development` - Quality standards
- Zod documentation: https://zod.dev
## Related Skills
- **Complete entity workflow**: See `adding-entity-types` for full schema-to-service implementation
- **Testing schemas**: See `analyzing-test-coverage` for test data builders
- **GraphQL type mapping**: See `writing-graphql-operations` for schema-to-GraphQL patterns
## Quick Reference Rule
For a condensed quick reference, see `.claude/rules/config-schema.md` (automatically loaded when editing `src/modules/config/**/*.ts` files).More Database skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pg_cron, pgmq), vector/semantic search (pgvector), and restoring dumps (pg_restore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-database-setup
prisma/skills
Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
prisma-postgres
prisma/skills
Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth.

