Unrecognized keys are sent in responses
By default Zod object schemas strip out unrecognized keys during parsing. It works fine in requests, but it doesn't work in responses.
Example:
.openapi(
createRoute({
method: "post",
path: "/test",
responses: {
201: {
content: {
"application/json": {
schema: z.object({
shouldBePassed: z.string(),
}),
},
},
description: "",
},
},
}),
async (c) => {
return c.json({ shouldBePassed: "1", shouldNotBePassed: "2" }, 201);
}
)
The route returns the next reponse:
{
"shouldBePassed": "1",
"shouldNotBePassed": "2"
}
But the response should be:
{
"shouldBePassed": "1"
}
Deps:
"hono": "4.4.7",
"@hono/zod-validator": "0.2.2",
It appears to me that the response schema is not used for any type checking or run time parsing of the router return value. You can return anything from the router.
Am I missing anything?
If true, we’re missing an important check. One value of types on an API return value is to help prevent developers from accidentally returning extra, possibly sensitive data.
The answer:
You are correct, Hono's Validator does not validate the response.
https://github.com/honojs/middleware/issues/181
Would be great to have unrecognized keys stripped.
Is this something that is still in the pipeline somewhere? Willing to help on this, though not very familiar with the Hono codebase yet.