I am trying to write authentication logic for my app. I wrote a middleware that verifies a token, and therefore I need req.id
. I had to write an interface that extends from express.Request
to be able to access id
(similar issue).
import { Request } from "express";
export interface IGetUserAuthInfoRequest extends Request {
id: number;
}
This is how I implement the interface in my middleware to be able to use the req.id
property.
export const verifyToken = (req: IGetUserAuthInfoRequest, res: Response, next: NextFunction) => {
req.id = 1; // do something with req.id
/**
* some more logic
**/
next();
}
When I try calling the middleware, TypeScript complains, I think this is because of the custom type.
app.get("/api/try/admin", verifyToken, (req: Request, res: Response) => {
res.json({message: "try admin"})
});
The error looks something like this.
Type '(req: IGetUserAuthInfoRequest, res: Response, next: NextFunction)
=> Response | void' is not assignable to type
'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>> |
RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<...>>'.
How could I type this correctly (preferably without using any
)?