2

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

4
  • Since there’s no body sent then there’s no body to modify. You could always create the object. But I would strongly recommend NOT to put any extra things into request body. What if the request coming in has that property? What if your middleware misbehaves and malicious user can just send the userId in? So many things can go wrong here. Rather add a property to the actual request object that the user cannot access. Commented Sep 6 at 6:52
  • You can do instead req.jwt = { userId: tokenDecode.id } without modifying the req.body Commented Sep 6 at 7:02
  • ahh ok but i'm really need the body to store user id bocouse the other functions is already using body to store the data. can you give me suggest to add userId on req.body ? Commented Sep 6 at 7:18
  • 1
    @RidwanAnugrah Then this was a mistake to use req.body for purposes it's not suitable for. You'd naturally have this problem for get requests too. I don't see much problem in removing .body part through the app Commented Sep 6 at 10:17

1 Answer 1

2

The error Cannot set properties of undefined (setting 'userId') happens because req.body is undefined when you send a request without any body, even though you have app.use(express.json()).

if (tokenDecode.id) {
  // makesure req.body exists before adding properties
  req.body = req.body || {};
  req.body.userId = tokenDecode.id;
  next();
}

Alternative (Recommended)

Instead of modifying the body, you can attach userId to req.user

req.user = { id: tokenDecode.id };
# to access in controller use `req.user.id`
Sign up to request clarification or add additional context in comments.

1 Comment

but in this video somehow it's work. youtube.com/watch?v=7BTsepZ9xp8&t=64s your can cek in the minute 01:52:17.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.