I’m building an authentication system with Express + JWT + Cookie. I have a middleware userAuth that decodes the token and puts the userId into req.body.
Here is the code:
import jwt from "jsonwebtoken";
const userAuth = async (req, res, next) => {
const { token } = req.cookies;
if (!token) {
return res.json({ success: false, message: "Not Authorized Login Again" });
}
try {
const tokenDecode = jwt.verify(token, process.env.JWT_SECRET);
if (tokenDecode.id) {
req.body.userId = tokenDecode.id; // <--- ERROR happens here
next();
} else {
return res.json({ success: false, message: "Not Authorized Login Again" });
}
} catch (error) {
return res.json({ success: false, message: error.message + " userAuth" });
}
};
export default userAuth;
When I send a POST request from Postman with an empty raw body, I get this error:
Cannot set properties of undefined (setting 'userId')
What I Tried
- I’m already using app.use(express.json()) in my server.js.
- If I send a JSON body like {}, it works (no error).
- But when the request body is completely empty, the error is show.
Question
- How can I make sure that req.body.userId is not undefined in my middleware. so I can safely set
req.body.userId, because i follow this video https://www.youtube.com/watch?v=7BTsepZ9xp8&t=64s is working.
req.jwt = { userId: tokenDecode.id }without modifying thereq.body