I am trying to set up a custom middleware function in Node.js with typescript, where I want to store a decoded json web token into a custom request property 'user' like this
function auth(req: Request, res: Response, next: NextFunction) {
const decodedToken = jwt.verify(token, config.get("secret"));
req.user = decodedToken.user;
next();
}
but I keep getting a compiler error in the terminal
error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
I found several answers on here that suggested creating a custom.d.ts file and extend the Request type which I did like this:
namespace Express {
interface Request {
user?: string;
}
}
now, the VS Code is happy, I get no linting, I get the correct intellisense and autocompletion and it does not let me assign a number, because it understands it needs to be a string. So it obviously works. However, when I run the code the terminal keeps giving me the same error and insists that property 'user' does not exist.
I tried restarting the TS server but that did not help.
I can make it work by creating a custom interface which extends the Request type and then using that, but I really want to know how to do it with the original Request type.