Tutorial · Step 6 of 12
Validation & errors
Schema-validated input, thrown HTTP errors, and enforced response contracts.
Validate the input#
Never parse request bodies by hand. validate(target, schema) accepts any Standard Schema validator (zod, valibot, arktype…), extracts the target ("body", "query", or "param"), and on failure answers 400 with the issues — the handler never runs on bad input. On success the parsed value lands on ctx.valid, fully typed:
// src/notes/notes.schema.ts
import { z } from "zod";
export const createNoteSchema = z.object({
title: z.string().trim().min(1, "title must be a non-empty string"),
content: z.string().default(""),
});
export const updateNoteSchema = z.object({
title: z.string().trim().min(1, "title must be a non-empty string").optional(),
content: z.string().optional(),
});
export type CreateNoteInput = z.infer<typeof createNoteSchema>;
export type UpdateNoteInput = z.infer<typeof updateNoteSchema>;import { validate } from "@rhythmjs/middleware/validate";
import { json } from "@rhythmjs/router/response";
notesController.post("/api/notes", validate("body", createNoteSchema), (ctx) => {
// ctx.valid.body is CreateNoteInput — parsed, defaulted, typed
json(ctx, ctx.notesService.create(ctx.valid.body), 201);
});validate is typed like derive(): it widens the context for the handlers after it, so it must be the first handler of a route, and a route takes one such handler.
Throw HTTP errors#
filter() is the error boundary: put it first on the router, and any thrown HttpError becomes the matching JSON response while unexpected errors become a generic 500 — no stack traces or internals ever reach the client. Handlers then just throw:
import { HttpError, filter } from "@rhythmjs/middleware/filter";
import { json } from "@rhythmjs/router/response";
export const notesController = new RhythmRouter<NotesContext>({ name: "notes" })
.use(filter()) // first: every route below it is covered
.get("/api/notes/:id", (ctx) => {
const note = ctx.notesService.get(ctx.params.id);
if (!note) throw new HttpError(404, "Note not found");
json(ctx, note);
});mount() wraps anything thrown inside a mounted router as mounted router "notes" failed, with the original as its cause. A filter() on the app would therefore never see your HttpError and answer a generic 500. Keep filter() and intercept() on the router they protect. Requests no router matched are still the plain 404 from toFetchHandler.
Validate the output#
intercept(schema) is the mirror image: it validates (and re-serializes) what your handlers return, so a stripping schema genuinely removes over-exposed fields before they leave the process. Put it on the controller and every route of it honors the response contract. Only successful responses with a body are touched, so errors and 204s pass through:
import { intercept } from "@rhythmjs/middleware/intercept";
export const noteSchema = z.object({
id: z.string(),
title: z.string(),
content: z.string(),
});
export const notesResponseSchema = z.union([noteSchema, z.array(noteSchema)]);
export const notesController = new RhythmRouter<NotesContext>({ name: "notes" })
.use(filter())
.use(intercept(notesResponseSchema))
.get("/api/notes", (ctx) => { /* ... */ });The full shape#
Error filter, output interception, and input validation compose into the standard controller shape you will keep for the rest of the tutorial:
export const notesController = new RhythmRouter<NotesContext>({ name: "notes" })
.use(filter())
.use(intercept(notesResponseSchema))
.get("/api/notes", (ctx) => {
json(ctx, ctx.notesService.list());
})
.get("/api/notes/:id", (ctx) => {
const note = ctx.notesService.get(ctx.params.id);
if (!note) throw new HttpError(404, "Note not found");
json(ctx, note);
})
.post("/api/notes", validate("body", createNoteSchema), (ctx) => {
json(ctx, ctx.notesService.create(ctx.valid.body), 201);
})
.patch("/api/notes/:id", validate("body", updateNoteSchema), (ctx) => {
const note = ctx.notesService.update(ctx.params.id, ctx.valid.body);
if (!note) throw new HttpError(404, "Note not found");
json(ctx, note);
})
.delete("/api/notes/:id", (ctx) => {
if (!ctx.notesService.remove(ctx.params.id)) throw new HttpError(404, "Note not found");
ctx.response.status = 204;
});In production put bodyLimit(maxBytes) from @rhythmjs/http/body-limit in front of anything that reads request bodies — it answers 413 the moment a body crosses the limit, without buffering more than the limit itself. Add it with .use(bodyLimit(1_000_000)) on the app or on the router.