Skip to content

Middleware

ts
// 匹配任何方法和所有路由
app.use(logger());

// 指定 URL
app.use("/posts/*", cors());

// 指定 POST 和 URL
app.post("/posts/*", basicAuth());

app.post("/posts", (c) => c.text("Created!", 201));
ts
logger() -> cors() -> basicAuth() -> *handler*

执行顺序

js
app.use(async (_, next) => {
  console.log("middleware 1 start");
  await next();
  console.log("middleware 1 end");
});

app.use(async (_, next) => {
  console.log("middleware 2 start");
  await next();
  console.log("middleware 2 end");
});

app.use(async (_, next) => {
  console.log("middleware 3 start");
  await next();
  console.log("middleware 3 end");
});
js
app.get("/", (c) => {
  console.log("handler");
  return c.text("Hello!");
});
middleware 1 start
  middleware 2 start
    middleware 3 start
      handler
    middleware 3 end
  middleware 2 end
middleware 1 end

编写 middleware

ts
app.use(async (c, next) => {
  console.log(`[${c.req.method}] ${c.req.url}`);
  await next();
});

app.use 创建中间件会限制其复用,可以通过 createMiddleware() 创建一个可复用的 middleware。

js
const logger = createMiddleware(async (c, next) => {
  console.log(`[${c.req.method}] ${c.req.url}`);
  await next();
});

// 为制定的规则使用这个 middleware
app.use("/message/*", logger);

泛型

ts
const echoMiddleware = createMiddleware<{
  Variables: {
    echo: (str: string) => string;
  };
}>(async (c, next) => {
  c.set("echo", (str) => str);
  await next();
});

app.get("/echo", echoMiddleware, (c) => {
  return c.text(c.var.echo("Hello!"));
});

修改 Response

ts
createMiddleware(async (c, next) => {
  await next();
  c.res = undefined;
  c.res = new Response("New Response");
});

内置中间件

ts
import { Hono } from "hono";
import { poweredBy } from "hono/powered-by";
import { logger } from "hono/logger";
import { basicAuth } from "hono/basic-auth";

const app = new Hono();

app.use(poweredBy());
app.use(logger());

app.use(
  "/auth/*",
  basicAuth({
    username: "hono",
    password: "acoolproject",
  })
);