honojs / middleware

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

[zod-openapi] c.req.valid in middleware returns undefined #787

Open MrSquaare opened 5 days ago

MrSquaare commented 5 days ago

Hi,

I'm trying to create a middleware that will retrieve the headers according to how they were described by the zod schema. So I'm using c.req.valid("header"). However, this method returns undefined in the middleware, where it would return the correct values in the handler.

Here's some reproduction code:

import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
import { Env } from "hono";
import { createMiddleware } from "hono/factory";

type MyCustomInput = {
  out: {
    header: {
      authorization: string;
    };
  };
};

const myMiddleware = createMiddleware<Env, string, MyCustomInput>((c, next) => {
  const headers = c.req.valid("header");

  console.log("My headers", headers);

  return next();
});

const myDemoApp = new OpenAPIHono().openapi(
  createRoute({
    method: "get",
    path: "/",
    middleware: [myMiddleware],
    request: {
      headers: z.object({
        authorization: z.string(),
      }),
    },
    responses: {
      200: {
        description: "Success",
        content: {
          "text/plain": {
            schema: z.string(),
          },
        },
      },
    },
  }),
  (c) => {
    const headers = c.req.valid("header");

    console.log("My headers", headers);

    return c.text("Hello, world!");
  },
);

Output:

My headers undefined
My headers { authorization: 'Bearer SECRET' }
MrSquaare commented 5 days ago

This seems expected: https://github.com/honojs/middleware/blob/2d1a89df26f2ec42e1dc0e5845cf691bdcbe23e2/packages/zod-openapi/src/index.ts#L440-L441

Middlewares are loaded before validators

What's the best way to handle my problem?