Validate response objects

Using the zod validator middleware it is possible to validate params , query, request body like:
const route = app.post(
'/posts',
zValidator(
'form',
z.object({
body: z.string(),
})
),
(c) => {
// ...
return {
..
}
}
)
const route = app.post(
'/posts',
zValidator(
'form',
z.object({
body: z.string(),
})
),
(c) => {
// ...
return {
..
}
}
)
But is it also possible to validate the response object returned by the handler, to eg make sure response does contain required properties, but also does not include any unwanted properties?
2 Replies
ex0ns
ex0ns4mo ago
You can do this directly in the body of the handler can't you ? Before returning c.json(content) you could call returnSchema.parse(content) (where returnSchema is a zod schema)
Marcel Overdijk
Marcel Overdijk4mo ago
Yes that’s an option but the same could be said for parsing the request body. I wonder if it would be possible to use a global middleware, or – even better – to have a type safe return value..