You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat: Validator (zod) definitions into OpenAPI schema #3542
I would like to propose an alternative way to sole issue #2974 by accepting a field on defineRouteMeta which can be parsed via custom processors (eg, z.toJSONSchema(schema)) and populated into openAPI global schemas.
Currently, there is no way to use a validator like Zod to define the structure of event handler inputs and re-use the schema in the OpenAPI definition within the route file itself. This is because defineRouteMeta is statically compiled, and therefor never sees the value. As a result, duplication of code is required in definitnng both a validator as well as a JSON schema.
Ideally there would be some way to export or define Zod (or other validators) objects in an event handler to automatically be converted into JSON Schema to define responses, request body and query params in OpenAPI via your validation code.
I would like to spark a conversation around ideal implementation for this. At minimum giving us a way to define objects into the global schema namespace would be helpful but not ideal.
Perhaps a better solution could be a new composable, such as defineSchema or defineValidation?
Looking forward to contributing for this once we have a clear direction.
Additional information
Would you be willing to help implement this feature?
Reacted by Dylan Kelly, Stanislav Ilnytskyi, ilnytskyistrix, Richard Collier, mola1129, Seven Du, dejan, Julian Pustkuchen, Gabriel Serejo, Thomas Waldbillig and 5 more
But then I discovered that nitro already has experimental openApi and one can define schema via defineRouteMeta and there is great scalar plugin, same as in elysia. So there is no need to integrate nuxt/nitro with foreign framework for this use case.
Big up on this one. I found @asteasolutions/zod-to-openapi but I'm struggling to make it work properly with nuxt4 and nitro.
Things may be way much simpler if we were allowed to use schema directly.
There must be a better way to do this. Perhaps a new build time composable?
// server/utils/validation.tsimporttype{ZodType}from"zod";exportfunctiondefineValidation<TextendsZodType>(schema: T){// At runtime, this just returns the schema so you can still use itreturnschema;}
Could also support other validation libraries.
We can use the same pipeline to extract the zod schema, and inject it globally while also returning the zod schema itself so it can be used in runtime to parse?
Some psudo code:
// nitro.config.tsimport{defineNitroConfig}from"nitro/config";import{createJiti}from"jiti";exportdefaultdefineNitroConfig({plugins: [{name: "custom-zod-extractor",hooks: {"compiled"(nitro){constjiti=createJiti(import.meta.url);// 1. Iterate over all resolved route handlersfor(consthandlerofnitro.scannedHandlers){try{// 2. Use jiti to evaluate the fileconstmod=jiti.import(handler.handler);// 3. Logic to find your custom metadata// If you exported it or called a specific utilityif(mod.validationSchema){console.log(`Found Zod schema for ${handler.route}`);// You can now access the actual Zod object here!// mod.validationSchema.parse(...)}}catch(e){// Handle files that aren't evaluatable}}}}}]});
After some discussion with @pi0, it sounds like Nitro v3 no longer uses jiti and is moving away from build time macro compilation.
I also realize this is apart of a larger conversation around end-to-end type Saftey and Validation.
I wonder if we can get defineHandler/defineRouteHandler to be type safe with the OpenAPI defintion on input and response.
Currently it's possible for the OpenAPI schema defined manually to be out of alignment with the route handler. This should result in type errors.
Two ideas:
Compaion Schema Files
Each route file e.g. /api/my-route.get.ts gets a companion schema file /api/my-route.get.ts that defines the StandardSchema
Export schema defintion
Each route can export schema: StandardSchemaV1 = {...}
Use:
The standard schema is then used to generate validators and type definitions for the route. defineHandler() then errors if the return type does not align with the schema's responses
AND
new composable useSafeHead(), useSafeQuery(), useSafeResponse() perform validation with type saftey built from the schema
for example:
/api/route.get.ts
// api/farm/animals.get.tsimporttype{StandardSchemaV1}from'@standard-schema/spec'import{defineHandler,defineRouteSchema,HTTPError,useSafeQuery,useSafeResponse}from'nitro/validation'// hypotheticalexportconstschema=defineRouteSchema({parameters: [{in: 'query',name: 'kind',required: true,description: 'Animal category at the farm',schema: {type: 'string',enum: ['cow','chicken','pig','sheep']},},],responses: {200: {description: 'Names of animals of that kind',content: {'application/json': {schema: {type: 'array',items: {type: 'string'}}},},},404: {description: 'No animals of that kind',content: {'application/json': {schema: {type: 'object',properties: {message: {type: 'string'}}}},},},},})satisfiesStandardSchemaV1asyncfunctiongetNames(kind: 'cow'|'chicken'|'pig'|'sheep'): Promise<string[]>{// …}exportdefaultdefineHandler<typeofschema>(async(event)=>{const{ kind }=useSafeQuery(event)constnames=awaitgetNames(kind)if(names.length===0){thrownewHTTPError({status: 404,message: `No ${kind} on this farm`})}returnuseSafeResponse(event,200,names)})
Activity
ilnytskyi commentedon Aug 25, 2025
Found the same issue after thinking about integrating elysiajs https://elysiajs.com/integrations/nuxt into nuxt api routes.
Found it unclear how to handle elysiajs properly (probably via custom composable) and not to loose nuxt-native code convention like
const { data } = await useFetch('/api/hello').But then I discovered that nitro already has experimental openApi and one can define schema via defineRouteMeta and there is great scalar plugin, same as in elysia. So there is no need to integrate nuxt/nitro with foreign framework for this use case.
Also I found it impossible to write a code like this.
So zod v4 https://zod.dev/json-schema seems to be unusable for this case.
I see the only workaround is probably to build/compile zod types into files before using with openAPI.
That would be really great to use this with single source of types for
toJSONSchemaor their inferred types neededkogratte commentedon Apr 8, 2026
Hey there!
Big up on this one. I found @asteasolutions/zod-to-openapi but I'm struggling to make it work properly with nuxt4 and nitro.
Things may be way much simpler if we were allowed to use schema directly.
dan-hale commentedon Apr 29, 2026
There must be a better way to do this. Perhaps a new build time composable?
Could also support other validation libraries.
We can use the same pipeline to extract the zod schema, and inject it globally while also returning the zod schema itself so it can be used in runtime to parse?
Some psudo code:
dan-hale commentedon Apr 29, 2026
After some discussion with @pi0, it sounds like Nitro v3 no longer uses
jitiand is moving away from build time macro compilation.I also realize this is apart of a larger conversation around end-to-end type Saftey and Validation.
I wonder if we can get
defineHandler/defineRouteHandlerto be type safe with the OpenAPI defintion on input and response.Currently it's possible for the OpenAPI schema defined manually to be out of alignment with the route handler. This should result in type errors.
Two ideas:
Compaion Schema Files
Each route file e.g.
/api/my-route.get.tsgets a companion schema file/api/my-route.get.tsthat defines the StandardSchemaExport schema defintion
Each route can export
schema: StandardSchemaV1 = {...}Use:
The standard schema is then used to generate validators and type definitions for the route.
defineHandler()then errors if the return type does not align with the schema's responsesAND
new composable
useSafeHead(),useSafeQuery(),useSafeResponse()perform validation with type saftey built from the schemafor example:
/api/route.get.ts
kogratte commentedon Apr 30, 2026
What if...
?