middleware
middleware copied to clipboard
[zod-openapi] Route with middleware doesn't infer context variables
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!