Middleware
A middleware.ts file applies to all handlers in its folder and subdirectories.
- Runs before schema validation and the handler.
- Can short-circuit by throwing
HTTPException(e.g. 401) — the client gets{ error, message, code }. - Shares context with the handler via
c.set(key, value)andc.get(key). - Exports a single function or an array of functions (executed left → right).
Single middleware:
// app/orders/middleware.ts
import type { MiddlewareHandler } from "hono";
import { HTTPException } from "hono/http-exception";
const auth: MiddlewareHandler = async (c, next) => {
const token = c.req.header("authorization");
if (!token) {
throw new HTTPException(401, { message: "Unauthorized" });
}
c.set("user", { id: "123" });
await next();
};
export default auth;Middleware pipeline:
// app/orders/middleware.ts
import type { MiddlewareHandler } from "hono";
import { HTTPException } from "hono/http-exception";
const logger: MiddlewareHandler = async (c, next) => {
console.log(`[${c.req.method}] ${c.req.path}`);
await next();
};
const auth: MiddlewareHandler = async (c, next) => {
if (!c.req.header("authorization")) {
throw new HTTPException(401, { message: "Unauthorized" });
}
c.set("user", { id: "123" });
await next();
};
export default [logger, auth];Reading context in a handler:
export default async function handler(c) {
const user = c.get("user");
return { user };
}Execution order:
Request → Parent Middleware → Child Middleware → Schema Validation → Handler → ResponseLast updated on