H
Hono3mo ago
Paul Dlug

Type safety for middleware that sets context variables

I have an authentication middleware which ensures the user is logged in and adds the user to the context if they are. My middleware adds the type of this context variable per the docs:
declare module "hono" {
interface ContextVariableMap {
user: User;
}
}
declare module "hono" {
interface ContextVariableMap {
user: User;
}
}
The problem is, all handlers see c.get('user') as being present even if they don't use the middleware. If I make user optional then in every handler that uses my middleware I need a guard if (!user) return c.json(...) which is redundant because the middleware is already guaranteeing that the context variable is set. Is there any way around this?
6 Replies
Mihai Andrei
Mihai Andrei3mo ago
No description
Mihai Andrei
Mihai Andrei3mo ago
Hello If you do it like this, you don’t need to use the declare module “hono” Just use your middleware on the route and it will have access to it Notice you don’t provide a type when you create the hono instance
Mihai Andrei
Mihai Andrei3mo ago
If you do it like here, and use the middleware in every route
No description
Mihai Andrei
Mihai Andrei3mo ago
Then. You need to pass the type and do the declare module Sorry for the print screens but it is easier since I’m on the phone
Paul Dlug
Paul DlugOP3mo ago
Thanks that really helped!
icetouch
icetouch2mo ago
Sorry for hijacking this thread, but I'm facing a similar issue and the above solution doesn't seem to work for me.
const app = new Hono();

type Env = {
Variables: {
var: boolean;
};
};

const echoMiddleware = createMiddleware<Env>(async (c, next) => {
await next();
});

app.get("/echo", echoMiddleware, (c) => {});
const app = new Hono();

type Env = {
Variables: {
var: boolean;
};
};

const echoMiddleware = createMiddleware<Env>(async (c, next) => {
await next();
});

app.get("/echo", echoMiddleware, (c) => {});
This returns error Type 'BlankEnv' is not assignable to type 'Env'. when using echoMiddleware in my get handler. It seems like app defaults to BlankEnv and does not work with middlewares with custom variables. Defining Variables when initializing Hono() fixes the issue but just like OP, I do not want all other handlers to get access to it.
Want results from more Discord servers?
Add your server