'JWT TypeError: Cannot read properties of undefined (reading 'jwt')

i am creating a JWT token and this error came up. And i am getting this error : TypeError: Cannot read properties of undefined (reading 'jwt') Here is the code :

const maxAge = 3*24*60*60;  
    db.query('SELECT * FROM USERS WHERE EMAIL=?', [email], async (err, results, fields)=>{
        if(err){
            console.log(err);
        }       
        else if(results.length > 0)
        {
            const comparison = await bcrypt.compare(password, results[0].password); 
            if(comparison){
                 

                const token = jwt.sign({user_id:results[0].user_id, name:results[0].name},
                    process.env.SECRET_KEY , { expiresIn:maxAge });
                res.cookie('jwt', token, { httpOnly:true, maxAge:maxAge*1000 });
                console.log(token);
                return res.render('user', {
                    message: results[0].name
                });
            }
            else{
                res.render('login', {
                    message: 'Incorrect Email and Password.'
                });
            }
        }
        else{
            res.render('login', {
                message: "Email doesn't Exists."
            });
        }
    })

And here is the code of Middleware function

const requireAuth = (req, res, next)=>{
    const token = res.cookies.jwt;    //  Here this error came up    
    if(token){
        jwt.verify(token, process.env.SECRET_KEY, (err, decoded)=>{
            if(err){
                console.log(' You are not logged in.');
                res.redirect("/");
            }
            else{
                console.log(decoded);
                next();
            }
        });
    }   
    else{
        res.redirect('/');
    }
}



Solution 1:[1]

Your code is wrong in there:

const token = res.cookies.jwt;

You should read cookies from the request.

I don't know the syntax, it depends of the dependency used for the server here. Can you please tell us the server dependency ?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 karkael