Skip to content

feat: Validator (zod) definitions into OpenAPI schema #3542

Description

@dan-hale

Describe the feature

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?

Activity

  1. added
    pending triage
    on Aug 20, 2025
  2. ilnytskyi commented on Aug 25, 2025

    @ilnytskyi

    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.

    const myResponseJSONSchema = z.toJSONSchema(myObject, {target: "openapi-3.0"});
    
    defineRouteMeta({
        openAPI: {
            tags: ["test"],
            description: "Test schema description",
            responses: {
                200: {
                    description: "Test route description",
                    content: {
                        'application/json': {
                            schema: myResponseJSONSchema
                        }
                    }
                }
            }
        },
    });
    
    Image

    That would be really great to use this with single source of types for

    • validation
    • defining types
    • describing route request / response
    • swagger generation
    • other use cases where either toJSONSchema or their inferred types needed
  3. kogratte commented on Apr 8, 2026

    @kogratte

    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.

  4. dan-hale commented on Apr 29, 2026

    @dan-hale
    Author

    There must be a better way to do this. Perhaps a new build time composable?

    // server/utils/validation.ts
    import type { ZodType } from "zod";
    
    export function defineValidation<T extends ZodType>(schema: T) {
      // At runtime, this just returns the schema so you can still use it
      return schema;
    }

    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.ts
    import { defineNitroConfig } from "nitro/config";
    import { createJiti } from "jiti";
    
    export default defineNitroConfig({
      plugins: [
        {
          name: "custom-zod-extractor",
          hooks: {
            "compiled" (nitro) {
              const jiti = createJiti(import.meta.url);
              
              // 1. Iterate over all resolved route handlers
              for (const handler of nitro.scannedHandlers) {
                try {
                  // 2. Use jiti to evaluate the file
                  const mod = jiti.import(handler.handler);
                  
                  // 3. Logic to find your custom metadata
                  // If you exported it or called a specific utility
                  if (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
                }
              }
            }
          }
        }
      ]
    });
  5. dan-hale commented on Apr 29, 2026

    @dan-hale
    Author

    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.ts
    import type { StandardSchemaV1 } from '@standard-schema/spec'
    import { defineHandler, defineRouteSchema, HTTPError, useSafeQuery, useSafeResponse } from 'nitro/validation' // hypothetical
    
    export const schema = 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' } } } },
          },
        },
      },
    }) satisfies StandardSchemaV1
    
    async function getNames(kind: 'cow' | 'chicken' | 'pig' | 'sheep'): Promise<string[]> {
      // …
    }
    
    export default defineHandler<typeof schema>(async (event) => {
      const { kind } = useSafeQuery(event)
      const names = await getNames(kind)
    
      if (names.length === 0) {
        throw new HTTPError({ status: 404, message: `No ${kind} on this farm` })
      }
    
      return useSafeResponse(event, 200, names)
    })
  6. kogratte commented on Apr 30, 2026

    @kogratte

    What if...

    export default defineHandler<typeof schema>(async (event, input: typeof safeSchema) => {
    [...]
    })

    ?

  7. added
    enhancement
    and removed
    pending triage
    on Sep 2, 2026
  8. added and removed on Oct 17, 2026
  9. added
    openapi
    and removed
    enhancement
    on Nov 10, 2026
  10. added theissue type on Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    openapi

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions