Using Zod validation with Elysia and OpenAPI
I tried out Elysia v1.4 which adds support for Standard Schema, so type validation and coercion works out of the box with Zod.
import { z } from 'zod'
import { Elysia } from 'elysia'
export default new Elysia().get(
'/thing',
({ query }) => {
return { id: query.id }
},
{
query: z.object({ id: z.coerce.number() }),
}
)OpenAPI docs generation integration issues
When integrating with OpenAPI generation plugin @elysiajs/openapi, I ran into 2 problems:
- It generates docs for the
OPTIONSmethod, which is distracting (they came from @elysiajs/cors) - The Zod schema does not get serialized into OpenAPI docs, leading to missing documentation for request parameters.
It turns out that some extra configuration is neededr:
.use(
openapi({
// Use a more standardized path
specPath: "/openapi.json",
// Serialize Zod schema
mapJsonSchema: { zod: z.toJSONSchema },
// Skip documenting CORS endpoints
exclude: {
methods: ["OPTIONS"],
},
})
)The key parts:
mapJsonSchema: { zod: z.toJSONSchema }- enables Zod schema serialization for OpenAPIexclude: { methods: ["OPTIONS"] }- removes CORS OPTIONS endpoints from documentation