Skip to content

Fastify's swagger crash when using @fastify/swagger 9.2.0 with zod-openapi auto registering schemaΒ #172

Description

@mottet

What is the bug

Fastify's swagger does not load when using zod-openapi auto registering schema with @fastify/swagger@9.2.0

How to reproduce the bug

I have create a repository that repoduce this issue: https://github.com/mottet/bug-fastify-zod-openapi

First start the fastify server

npm install
npm serve

Then try to open the swagger page: http://127.0.0.1:5000/documentation

The error "Failed to load API definition." should appear.

What causes this bug

Since @fastify/swagger version 9.2.0 that contains this PR fastify/fastify-swagger#826, when a response with no description contains a reference, it will try to get the description from the reference.

But this happen AFTER fastify-zod-openapi had add the ref in the response, but BEFORE fastify-zod-openapi created the actual component. So fastify/swagger try at this line to get a defnition on a component that does not exist yet and throw the error:

Exception has occurred: TypeError: Cannot read properties of undefined (reading 'schemas')

This description fallback happens in this function call that is between the 2 transformation steps of fastify-zod-openapi here and here

Workaround

Downgrade @fastify/swagger from 9.2.0 to 9.1.0

How to fix it

The fix can be easy by simply change in https://github.com/fastify/fastify-swagger/blob/master/lib/util/resolve-schema-reference.js

return resolvedReference.definitions[schemaId]

to this

return resolvedReference.definitions?.[schemaId]

I'm contacting you even if this issue seems to be more on the fastify/swagger side, because it is an edge case that is "setup" by zod-openapi and fastify-zod-openapi and affects you directly.

Activity

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions