Four places in AgendaViva convert data they don't control by hand: parseEvent, booking, parseForecast and readEnv. All of them repeat the same thing: check a type, convert, collect messages and build an object you can trust. It's long code, and it's easy to forget a case in it.
A schema describes the expected shape just once, and from it you get the check, the conversion, the messages and the TypeScript type. We'll use Zod, the most widely used library. But the tool is only half the story. The other half is knowing what to validate and where: what separates a wrong format from a broken rule, what traps FormData hides, what time 20:30 actually means, and why browser validation doesn't count as validation.
- Schemas with Zod
The course uses version 4. A lot of published code is for version 3, and there are differences that cause confusion:
| Zod 3 | Zod 4 |
|---|---|
error.flatten(), error.format() |
z.flattenError(error), z.treeifyError(error) |
{ message: '…' }, { required_error: '…' } |
A string, or { error: '…' } |
z.string().email() |
z.email() |
z.nativeEnum(Enum) |
z.enum(Enum) |
The essentials, in one example:
import * as z from 'zod'
const forecastSchema = z.object({
sky: z.enum(['sun', 'clouds', 'rain']),
low: z.number(),
rain: z.number().min(0).max(100),
})
type Forecast = z.infer<typeof forecastSchema>
// { sky: 'sun' | 'clouds' | 'rain'; low: number; rain: number }
const result = forecastSchema.safeParse(data) // data: unknown
if (result.success) {
result.data // Forecast
} else {
result.error.issues // Every failure, with its path and its message
}parsethrows;safeParsereturns a union discriminated bysuccess. With outside data, a failure is to be expected: usesafeParse.datais a new value. Undeclared keys are dropped. If someone addsstatus=publishedto the form, it doesn't reach the database: it's a defense against mass assignment.z.strictObjectwould reject them instead of ignoring them.z.number()requires an actual number. Neither'12'norNaN. Conversions are requested separately.- It doesn't stop at the first error. It gathers all the ones it can, which is what a form wants.
The default messages are in English. The ones the public sees we write ourselves, as the first argument or in each rule; for the rest you can load another language with z.config(es()), importing es from zod/locales.
- FormData is text
Everything a form sends is text or a file. Zod offers z.coerce, which applies Number(value), Boolean(value) or new Date(value) before checking. It's tempting and, with forms, misleading:
| Schema | Input | Result | Problem |
|---|---|---|---|
z.coerce.number() |
'' (empty field) |
0 |
Number('') is 0: "typed nothing" passes as a zero |
z.coerce.number() |
null (missing field) |
0 |
Same |
z.coerce.boolean() |
'false' |
true |
Any non-empty string is true |
z.coerce.string() |
null |
'null' |
Four letters nobody typed |
z.coerce.date() |
'2028-05-12T20:30' |
It depends | It uses the server's time zone |
The alternative is to validate the text and convert it afterwards. These building blocks work for every form:
// lib/schemas/common.ts
import * as z from 'zod'
import { parseLocalDateTime } from '@/lib/dates'
interface Bounds {
min: number
max: number
}
export function text({ min, max }: Bounds) {
return z
.string('This field is required.')
.trim()
.min(min, `Write at least ${min} characters.`)
.max(max, `Use no more than ${max} characters.`)
}
export function integer({ min, max }: Bounds) {
const message = `Enter a whole number between ${min} and ${max}.`
return z
.string(message)
.trim()
.regex(/^\d+$/, message)
.transform(Number)
.pipe(z.number(message).min(min, message).max(max, message))
}
export const localDateTime = z.string('Enter a date and time.').transform((value, ctx) => {
const date = parseLocalDateTime(value)
if (!date) {
ctx.issues.push({
code: 'custom',
message: 'Enter a date and time that exist.',
input: value,
})
return z.NEVER
}
return date
})
// Identifiers that come from outside: a reasonable shape, nothing more
export const identifier = z.string().min(1).max(64)trimgoes beforemin. Otherwise, five spaces would be a valid title.transformconverts and changes the output type;pipepasses the result to another schema. If the first part fails, the second doesn't run, and that's whyintegergives a single message.ctx.issues.pushandz.NEVERare how you fail inside a transformation. Don't throw: Zod doesn't catch exceptions.- Always setting a maximum isn't fussiness. Without one, someone can save a half-megabyte title, up to the request body limit.
Other controls you'll come across:
| Control | What arrives | How to read it |
|---|---|---|
| Single checkbox | 'on', or nothing if it's unchecked |
formData.has('accept') or z.stringbool().default(false) |
Several checkboxes with the same name |
One entry per checked box | formData.getAll('days') and z.array(…); Object.fromEntries keeps only the last one |
select |
The option's value |
z.enum |
| Optional empty field | '' |
`transform((value) => value |
| File | File |
z.file(), and much more (06-05) |
- Dates and time zones
In 06-02 we wrote parseLocalDateTime to turn '2028-05-12T20:30' into an instant. Now it's clear why a schema isn't enough: z.iso.datetime({ local: true }) checks that the text looks like a date without a time zone, and that's where it stops. What's missing is knowing which place that time belongs to, and that isn't in the data: it's a product decision. A concert in Vallenar del Río at 20:30 is at 20:30 local time there, even if the person entering it is traveling and the server is on another continent.
// On a machine set to mainland Spain time, in summer
new Date('2028-05-12T20:30').toISOString() // '2028-05-12T18:30:00.000Z'
// The same code on a server running in UTC
new Date('2028-05-12T20:30').toISOString() // '2028-05-12T20:30:00.000Z'It's a bug you don't see in development and that shifts every event by two hours in production. The algorithm in lib/dates.ts avoids it in three steps: it interprets the text as if it were UTC, works out how far the guide's time zone is from UTC at that moment, and subtracts it. It does this twice because the first calculation can land on the other side of a clock change. Then it formats the resulting date and compares it with the original text: if they don't match, that time doesn't exist.
| Input | Result | Reason |
|---|---|---|
2028-01-12T00:00 |
January 11, 23:00 UTC | Winter: one hour's difference |
2028-05-12T20:30 |
18:30 UTC | Summer: two |
2028-02-31T10:00 |
null |
That day doesn't exist |
2028-03-26T02:30 |
null |
The clock jumps from 2:00 to 3:00 |
2028-10-29T02:30 |
01:30 UTC | It happens twice; the second one is taken |
The second-to-last case comes for free from the final comparison. For the last one there's no right answer, only a consistent decision; an event at half past two on that particular night would be sorted out by hand. If a project does a lot of time zone arithmetic, a specialized library is worth it.
And in the other direction, the edit form uses formatLocalDateTime, never toISOString().slice(0, 16), which would show the UTC time.
- The event schema
// lib/schemas/limits.ts — no dependencies: the browser uses it too
export const EVENT_LIMITS = {
title: { min: 5, max: 120 },
summary: { min: 20, max: 200 },
description: { min: 20, max: 5000 },
capacity: { min: 1, max: 5000 },
}// lib/schemas/event.ts
import * as z from 'zod'
import { integer, localDateTime, text } from '@/lib/schemas/common'
import { EVENT_LIMITS } from '@/lib/schemas/limits'
import { CATEGORIES } from '@/lib/types'
const period = z.object({ startsAt: z.date(), endsAt: z.date() })
export const eventSchema = z
.object({
title: text(EVENT_LIMITS.title),
summary: text(EVENT_LIMITS.summary),
description: text(EVENT_LIMITS.description),
category: z.enum(CATEGORIES, 'Choose a category.'),
venueId: z.string('Choose a venue.').min(1, 'Choose a venue.').max(64),
startsAt: localDateTime,
endsAt: localDateTime,
capacity: integer(EVENT_LIMITS.capacity),
})
.refine(({ startsAt, endsAt }) => endsAt > startsAt, {
error: 'It must be after the start.',
path: ['endsAt'],
when: ({ value }) => period.safeParse(value).success,
})z.enum(CATEGORIES)uses the list fromlib/types.ts. There's still a single source: the type, the PostgreSQL enumerated type and the schema all come from it.refinechecks something across fields, andpathsays which field the message is attributed to.whendecides when it runs. By default, an object-levelrefineisn't evaluated if any field has failed in a way that prevents continuing, even an unrelated one: with a mistyped capacity, the dates message would only show up on the second attempt. Here it's enough for the two dates to be valid.venueIdonly checks the shape. Whether it exists is a different question, answered in the next section.
The output type matches EventData. We don't take that for granted: the assignment in the action will check it at build time.
- Format and rules
"The capacity is an integer between 1 and 5000" can be known by looking at the data. "The capacity doesn't exceed the venue's" requires a query. They're two kinds of check and it's worth keeping them apart:
| Format | Business rules | |
|---|---|---|
| Depends on | The data itself | The database, the clock, who's asking |
| Where | A schema, shareable | A server function |
| It's | Synchronous and pure | Asynchronous |
| Can change between checking and writing | No | Yes: if it's critical, it's repeated in the transaction |
Zod supports asynchronous refine calls, with safeParseAsync, and you could put everything in the schema. We don't: the module would come to depend on the database, would no longer be shareable and would run queries even if the title were empty.
// lib/rules/event.ts
import 'server-only'
import { getVenueById } from '@/lib/data/venues'
import type { FieldErrors } from '@/lib/forms'
import type { EventField, EventData, EditableStatus } from '@/lib/types'
const MIN_REVIEW_DESCRIPTION = 80
export async function checkEventRules(
event: EventData,
status: EditableStatus,
): Promise<FieldErrors<EventField>> {
const errors: FieldErrors<EventField> = {}
const venue = await getVenueById(event.venueId)
if (!venue) {
errors.venueId = ['Choose a venue from the list.']
} else if (event.capacity > venue.capacity) {
errors.capacity = [`${venue.name} holds ${venue.capacity} people at most.`]
}
if (event.startsAt <= new Date()) errors.startsAt = ['It must be a future date.']
if (status === 'review' && event.description.length < MIN_REVIEW_DESCRIPTION) {
errors.description = [
`To submit it for review, describe the event in at least ${MIN_REVIEW_DESCRIPTION} characters.`,
]
}
return errors
}The future date is here and not in the schema because of a trap: z.date().min(new Date()), written in the module, would read the clock once, when the server starts. It's the same mistake we avoided in 05-03 with isCurrent.
The last rule depends on the intent. A draft can be half finished; what's sent for review can't.
And booking? Its rules (there are spots left, there isn't another booking, the event is still current) stay in createBooking, inside the transaction: they can change in the instant between the check and the write.
- In the actions
// actions/events.ts (saveEvent changes; readIntent goes away)
import * as z from 'zod'
import { eventSchema } from '@/lib/schemas/event'
import { checkEventRules } from '@/lib/rules/event'
import { EDITABLE_STATUSES /* … */ } from '@/lib/types'
const intentSchema = z.enum(EDITABLE_STATUSES).catch('draft')
const CHECK_FIELDS = 'Check the highlighted fields.'
async function saveEvent(
formData: FormData,
write: (event: EventData, status: EditableStatus) => Promise<boolean>,
): Promise<EventFormState> {
const values = readTextFields(formData, EVENT_FIELDS)
const result = eventSchema.safeParse(values)
if (!result.success) {
const { fieldErrors } = z.flattenError(result.error)
return { status: 'error', message: CHECK_FIELDS, errors: fieldErrors, values }
}
const event: EventData = result.data
const status = intentSchema.parse(formData.get('intent'))
try {
const errors = await checkEventRules(event, status)
if (Object.keys(errors).length > 0) {
return { status: 'error', message: CHECK_FIELDS, errors, values }
}
const saved = await write(event, status)
// … the rest, as in 06-02z.flattenErrorgroups the messages by field:{ formErrors, fieldErrors }. That's the shape of ourerrors, and it fits with no conversion. Messages that don't belong to any field would go informErrors. For nested objects or lists you usez.treeifyError.- The original strings are returned, not the trimmed or converted ones: what the person typed.
catch('draft')provides a value when the input isn't valid. Here it's sensible, because a draft is the harmless option. Don't use it to hide incorrect data.- The two rounds aren't shown together. Format first, then rules: asking about the venue on a half-filled form adds nothing.
Delete lib/parse-event.ts. In booking, the bind argument also goes through a schema, because arguments are input just like fields:
// actions/bookings.ts (inside bookSpots)
const { maxSpotsPerBooking: max } = readEnv()
const values = readTextFields(formData, ['spots'])
if (!identifier.safeParse(eventId).success) {
return { status: 'error', message: 'Invalid event.', errors: {}, values }
}
const result = z.object({ spots: integer({ min: 1, max }) }).safeParse(values)
if (!result.success) {
const { fieldErrors } = z.flattenError(result.error)
return { status: 'error', message: "The booking wasn't made.", errors: fieldErrors, values }
}
const { spots } = result.data
const booking = await createBooking(user.id, eventId, spots)The variable that used to be called result is now booking; adjust the lines that follow. The schema is built at call time because the maximum is read from the environment at runtime (03-05).
Why validate an identifier that won't exist anyway? TypeScript asserts it's a string, but at runtime an object, an array or a one-megabyte string could arrive. Schemas at the boundary let the rest of the code trust its types.
What Zod does not check is permission. A perfectly well-formed identifier can belong to someone else's event. The schema looks at the shape; ownership is handled by the where from 06-02 and, from module 8 on, by the session.
- Validation in the browser
HTML attributes (required, min, max, minLength, maxLength, type) give feedback without waiting for the server and without JavaScript. They're a help, not a barrier: they can be removed from the browser's tools in seconds, or bypassed with curl. The rule is easy to remember: if all browser validation were deleted, the application must still be correct, just less convenient.
So that the numbers don't contradict each other, they're taken from EVENT_LIMITS:
// event-form.tsx
<input
{...attributes}
name="title"
defaultValue={values.title}
minLength={EVENT_LIMITS.title.min}
maxLength={EVENT_LIMITS.title.max}
required
/>The schemas could also run in the browser: lib/schemas/ doesn't carry server-only. We don't do it because Zod would become part of the page's JavaScript, and for these forms the attributes cover almost everything. It pays off in very dynamic or multi-step forms, usually with a form library. Even then, the server always validates.
That's why the limits are in a file without dependencies. If EventForm imported lib/schemas/event.ts to read a maximum, it would drag in all of Zod.
Check it: remove required and minLength from the title with the browser's tools, submit two letters and you'll see the server's message, associated with the field, with everything else intact.
- The other two boundaries
8.1. An API's response
// lib/data/weather.ts (replaces isSky, isNumber and parseForecast)
import * as z from 'zod'
const forecastSchema = z.object({
sky: z.enum(SKIES),
low: z.number(),
high: z.number(),
rain: z.number().min(0).max(100),
})
// In requestForecast
const result = forecastSchema.safeParse(await response.json())
if (!result.success) {
throw new Error(`Unknown format: ${z.prettifyError(result.error)}`)
}
return { status: 'available', forecast: result.data }It's quite a bit shorter, and the log will say which field changed at the provider. z.prettifyError produces text that's readable for people reading logs; it isn't for the public. Since objects drop anything undeclared, a new field from the provider doesn't break anything.
8.2. The environment
// lib/env.ts
import 'server-only'
import * as z from 'zod'
const optional = z.string().trim().default('').transform((value) => value || null)
function integerWithDefault(defaultValue: number, min: number, max: number) {
const message = `Must be an integer between ${min} and ${max}`
return z
.string()
.trim()
.default('')
.transform((value) => (value === '' ? defaultValue : Number(value)))
.pipe(z.number(message).int(message).min(min, message).max(max, message))
}
const MISSING = 'Required: see .env.example'
const envSchema = z
.object({
SITE_NOTICE: optional,
MAX_SPOTS_PER_BOOKING: integerWithDefault(4, 1, 20),
WEATHER_URL: optional,
WEATHER_KEY: optional,
DATABASE_URL: z.string(MISSING).trim().min(1, MISSING),
QUERY_DELAY_MS: integerWithDefault(0, 0, 10_000),
})
.transform((variables) => ({
siteNotice: variables.SITE_NOTICE,
maxSpotsPerBooking: variables.MAX_SPOTS_PER_BOOKING,
weatherUrl: variables.WEATHER_URL,
weatherKey: variables.WEATHER_KEY,
databaseUrl: variables.DATABASE_URL,
queryDelay: variables.QUERY_DELAY_MS,
}))
export type Env = z.output<typeof envSchema>
export function readEnv(): Env {
const result = envSchema.safeParse(process.env)
if (!result.success) {
throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`)
}
return result.data
}readInteger and readRequired go away, and code that uses readEnv() doesn't notice. The gain is that it reports every incorrect variable at once. The messages name the variable but don't include its value, as we required in 03-05. It's still a function: the schema is created on import, but it doesn't read anything until it's called.
Here the empty string means "default", so it's handled before converting; a plain z.coerce.number() would have turned it into a zero.
Common Mistakes and Tips
- Validating only in the browser.
z.coerce.number()with an empty field. It gives 0.z.coerce.date()withdatetime-local. It uses the server's time zone.- Reading the clock when defining the schema.
- Forgetting maximum lengths.
trimaftermin.- Throwing inside
refineortransform. Zod doesn't catch it. - Confusing shape with permission. A valid identifier can belong to someone else.
- Not validating the arguments fixed with
bind. - Copying Zod 3 examples:
flatten,required_error,nativeEnum. - Importing the schema into a Client Component to read a constant.
- Checking a rule that can change outside the transaction.
Exercises
Exercise 1: the double-booked venue
Two published events mustn't overlap at the same venue. Add the rule to submitting for review, with a message that names the conflicting event. Does this guarantee there won't be two published at the same time?
Solution
// lib/data/events.ts (imports lt and gt)
export async function findOverlap(
venueId: string,
startsAt: Date,
endsAt: Date,
): Promise<string | null> {
const db = await getDb()
const [other] = await db
.select({ title: events.title })
.from(events)
.where(
and(
isPublished,
eq(events.venueId, venueId),
lt(events.startsAt, endsAt), // Starts before this one ends…
gt(events.endsAt, startsAt), // …and ends after this one starts
),
)
.limit(1)
return other?.title ?? null
}
// lib/rules/event.ts
if (status === 'review' && venue) {
const title = await findOverlap(venue.id, event.startsAt, event.endsAt)
if (title) errors.startsAt = [`There's another event at the venue at that time: "${title}".`]
}It doesn't guarantee it. Two events in review for the same time both pass, and if they're published at the same time they'll overlap. It's a useful warning for the organizer; the guarantee belongs to the moment of publishing, inside a transaction or with a PostgreSQL exclusion constraint. As practice, it isn't kept.
Exercise 2: fixing a schema
Find the problems in this schema, which validates Object.fromEntries(formData) from a form with a title, an optional price, a "featured" checkbox, several days and a deadline.
const schema = z.object({
title: z.string().min(3).trim(),
price: z.coerce.number().optional(),
featured: z.coerce.boolean(),
days: z.array(z.string()),
deadline: z.coerce.date().min(new Date()),
userId: z.string(),
})Solution
minbeforetrim: three spaces are accepted. A maximum is missing.- An empty price becomes 0, because
''isn'tundefined. The empty string has to be handled before converting. featuredwould accept the string'false'as true. An unchecked checkbox isn't sent;formData.has('featured')is better.Object.fromEntriesleaves a single day, as a string, andz.arrayrejects it. It's read withgetAll.- The date is interpreted in the server's time zone and the minimum is fixed when the module loads.
userIdmustn't come from the form.
Exercise 3: filters with Zod
normalizeFilters (02-02) ignores anything invalid. Write an equivalent schema for category, q and page from optional strings. How does it differ from a form schema? Is it worth replacing the function?
Solution
const filtersSchema = z.object({
category: z.enum(CATEGORIES).optional().catch(undefined),
q: z.string().trim().max(80).optional().catch(undefined),
page: integer({ min: 1, max: 1000 }).catch(1),
})Each field has catch: an incorrect input is replaced instead of rejecting the whole set, which is right for a query URL and the opposite of what you want when modifying data. There's one nuance: normalizeFilters trims q to 80 characters and this schema discards it. It isn't replaced: the function exists, it works and its module is neutral; with Zod inside, it would add weight in the browser the day a Client Component imports it.
Conclusion
A schema describes the shape of a piece of data once, and safeParse gives you either a trustworthy value or a list of errors that z.flattenError distributes by field. With FormData you validate the text and convert it afterwards, because direct coercion confuses empty with zero and moves times around. The format goes in the schema; the rules that depend on other data or on the clock, in server functions; and the ones that can change while writing, in the transaction. Browser validation helps and doesn't protect.
The data coming in can now be trusted. It's time to deal with how waiting feels: a button that doesn't respond, a cancellation that takes a while, spots that don't go down, a "saved" nobody confirms. That's the subject of Pending States and Optimistic Updates.
