Validation and data

Validate unknown input

Treat request data as unknown at runtime and turn invalid JSON fields into precise client-facing validation errors.

8 minute lesson

~~~

TypeScript cannot prove what a remote client sent. A type assertion changes the checker’s belief but performs no runtime validation.

Define a schema for writable book fields and validate before business logic. Reject missing, incorrectly typed, too-long, or unexpected values according to one documented policy. Hono validation middleware can attach the validated result to the request context.

Validation begins before the schema. Limit body size, require the expected media type, and turn JSON parse failures into a controlled client error. Then validate the parsed value as unknown. TypeScript types describe code after that boundary; they do not make a network payload trustworthy.

Use only the validated output in the handler. Decide whether unknown fields are rejected or stripped, and keep that policy consistent so misspelled input cannot appear to succeed. Normalize only where the contract says so: trimming a title may be useful, while silently coercing "2024" into a number hides a client bug. Test null, arrays, extra fields, whitespace-only strings, invalid years, and the largest accepted input.

Add runtime validation for non-empty title and author strings and an optional four-digit publication year.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →