'Getting "Cannot set headers after they are sent to the client" error in Express [closed]

Screenshot of the error:

Screenshot of the error

Code of client side:

Code of client side

jwt attached api:

jwt attached api

Here's the jwt verifying function:

    const authHeader = req.headers?.authorization;
    if(!authHeader){
        return res.status(401).send({message: 'Unauthorized access'})
    }
    const token = authHeader.split(' ')[1];
    jwt.verify(token, process.env.SECRET_TOKEN, (err, decoded)=>{
        if(err){
            return res.status(403).send({message: 'Forbidden access'})
        }
        console.log('decoded', decoded);
        req.decoded = decoded;
    })
    next();
}


Solution 1:[1]

This error isn't related to jwt. This error happens if you try to do something with res object after response is sent. You can try to use return statement after or along with all your res.send() statements on server and that should resolve this error.

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 Shankar