honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
413 stars 142 forks source link

[zod-openapi] Route with middleware doesn't infer context variables #715

Open markkkkas opened 4 weeks ago

markkkkas commented 4 weeks ago

Hey, thanks for the neat tool for effortlessly building OpenAPI schemas. I've noticed (or maybe I'm doing something wrong) that middleware with context variables is not inferred at the route level when trying to access the route's context object.

export type AuthMiddlewareEnv = {
  Variables: {
    user: {
      id: string;
    };
  };
};

export const authMiddleware = createMiddleware<AuthMiddlewareEnv>(
  async (c, next) => {
    const authToken = getCookie(c, Config.Cookie.AuthToken);
    if (!authToken) {
      throw new HTTPException(401);
    }

    const { sub } = await verifyToken(authToken);
    const user = { id: sub };

    c.set("user", user);
    await next();
  }
);

// ...

export const getSessionRoute = createRoute({
  method: "get",
  path: "/session",
  summary: "Get Session",
  middleware: authMiddleware,
  tags,
  responses,
});

// ...

const router = new OpenAPIHono();

router.openapi(getSessionRoute, (c) => c.json(c.var.user)); 
// Property 'user' does not exist on type 'Readonly<ContextVariableMap & object>'

Thanks in advance!

yusukebe commented 1 week ago

Hi @markkkkas

Thank you for the issue. When we solve this problem, the type definition inside the Zod OpenAPI may be super complicated or verbose. I think finding a nice workaround is good for this issue, though I don't have an idea now.

abielzulio commented 5 days ago

Any updates on this?

Updates: What I did to make it work was simply adding the AuthMiddlewareEnv type to the OpenAPIHono initiation, so it looks like this:

const router = new OpenAPIHono<AuthMiddlewareEnv>();

I'm not sure if this is scalable (as we need to do it on repeat). What do you think? @yusukebe