Unable to compile TypeScript. Property 'user' does not exist on type 'Request<ParamsDictionary

Hello, I getting annoyed about typescript in my node api. I have written a jwtverify.ts. At first typescript has not accepted the req.user. I found a hint on StackOverflow and brought in a @types folder with a file named index.d.ts and the following code:

 import * as express from "express"
declare global {
    namespace Express {
        interface Request {
            user? : Record<string, any>
        }
    }
}

That solved this issue first, but today the app crashes and throws me that error in my title. When I hover req.user in my verifytoken. Vs-code tells me:

The object may be undefined

Thanks for help

Hello there,

The user object does exist on the Request object type. Instead of manually adding the typedef to a declaration file, I suggest adding the types for Express with:

npm i -D @types/express

This being said, it sounds like you are not checking for the existence of req.user before using it.

As shown in the type def, user is optional on Request. Meaning, it might exist.

So, you need to guard against the cases where it might not exist by doing something like:

if (req.user) {
  // Now you can use user
  const { user } = req;
  ...
}

Beyond this, without seeing the code responsible for throwing that error, we cannot help any further.

Hope this helps

Thank you Sky020. With two other modifyings it works.

Hello Sky020, thanks for your help, sadly it only solved the issue in that way, that there are no errors anymore. The jwtVerify not works.
Here is the code:

export const verifyToken = (req:Request, res:Response, next:NextFunction)=>{
    const sec:string = process.env.JWT_SEC as string;
    const authHeader = req.headers.token;
    console.log(authHeader);
    if(authHeader){
        const token = (authHeader as string).split(' ')[1];
        jwt.verify(token, sec, async (err, user)=>{
            if(err){
                res.status(403).json('Token not valid');
            }
            if(!user) return res.status(400).json({error:"Not authorized"})
            console.log(user, req.user);
            if(req.user){
               const {user} = req;
            }
            next();
        })
    } else{
        return res.status(401).json('Not authorized');
    }
};

Log authHeader gives back the correct header. Log (user, req.user) gives back: {
[0] id: ‘6346af949778eba63822fd8b’,
[0] isAdmin: false,
[0] iat: 1665576936,
[0] exp: 1668168936
[0] } undefined
Without typescript I was used to say req.user = user and that has worked.

saying:

 if(user){
   req.user = <any>user;
}

brought the solution. I don’t know if it is the best solution but ist seems to work. Thanks