Why does not a request pass through Middleware ? #3487
-
I want to check cookie in Middleware. Sample code is here. import { Hono } from "hono"
import { serve } from "@hono/node-server";
import { createMiddleware } from "hono/factory";
const app = new Hono({ strict: false })
app.get("/service", (c) => {
return c.json({ data: "foobar" });
});
const checkSession = createMiddleware(async (c, next) => {
const sessionToken = getCookie(c, "session_token");
if (sessionToken !== SessionToken) {
c.status(401);
return c.text("Unauthorized");
}
await next();
});
app.use("/service", checkSession);
const port = 3000;
console.log(`Server is running on port ${port}`);
serve({
fetch: app.fetch,
port,
}); And the log of Why does not a request pass through Middleware ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
This is an issue with the ordering of your middlewares and handlers. In the sample code you provided, the middleware is registered after the handler, which means that nothing it is technically never invoked. You can fix it like this: const checkSession = createMiddleware(async (c, next) => {
const sessionToken = getCookie(c, "session_token");
if (sessionToken !== SessionToken) {
c.status(401);
return c.text("Unauthorized");
}
await next();
});
// First, register the middleware
app.use("/service", checkSession);
// Second, register the handler
app.get("/service", (c) => {
return c.json({ data: "foobar" });
});
const port = 3000;
console.log(`Server is running on port ${port}`);
serve({
fetch: app.fetch,
port,
}); |
Beta Was this translation helpful? Give feedback.
-
Appreciate your response. |
Beta Was this translation helpful? Give feedback.
This is an issue with the ordering of your middlewares and handlers.
Middlewares and handlers are executed in an "onion" layout. You can see that documented here and here. Essentially, everything before the
await next()
in your middleware will be executed before the handler, and everything after theawait next()
will be executed after the handler.In the sample code you provided, the middleware is registered after the handler, which means that nothing it is technically never invoked. You can fix it like this: