Skip to content

[zod-openapi] defineOpenAPIRoute does not infer handler Context variables from route middleware #1879

Description

@alirostami1

Which middleware has the bug?

@hono/zod-openapi

What version of the middleware?

1.3.0

What version of Hono are you using?

4.12.16

What runtime/platform is your app running on? (with version if possible)

@hono/node-server 4.12.16 on node runtime v22.22.0

What steps can reproduce the bug?

import { createMiddleware } from 'hono/factory'
import { createRoute, defineOpenAPIRoute } from '@hono/zod-openapi'

type Identity = { id: string }

const requireIdentity = createMiddleware<{
  Variables: {
    identity: Identity
  }
}>(async (c, next) => {
  c.set('identity', { id: '123' })
  await next()
})

const route = defineOpenAPIRoute({
  route: createRoute({
    method: 'get',
    path: '/me',
    middleware: [requireIdentity] as const,
    responses: {
      200: {
        description: 'ok',
      },
    },
  }),
  handler: (c) => {
    c.var.identity.id
    return c.text('ok')
  },
})

What is the expected behavior?

type of c.var.identity to be correctly inferred from middleware: [requireIdentity] as const to be of type Identity.

What do you see instead?

c.var.identity is of type any

Additional information

There seems to be an easy fix in the code already we just need to use it. If we use what has been done for OpenAPIHono.openapi() instead of ignoring the middleware in HanlderFromRoute and HookFromRoute we can fix this. If you think this is good I can open a pull request with the proposed fix.

Regards,
aros

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions