Home > Net >  "Cannot read properties of null (reading 'role')"
"Cannot read properties of null (reading 'role')"

Time:03-29

Code this is my code in VS code to check if the user is an admin or a user

  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return next(
        new ErrorHandler(
          `Role: ${req.user.role} is not allowed to access this resource`,
          403
        )
      );
    }

    next();
  };
};```

**Error in postman API**
the used declaration should be fine i don't know what's this problem
"success": false,
    "message": "Cannot read properties of null (reading 'role')"

CodePudding user response:

Based on your description, I assume your user object on req.user is null, therefor it tries reading the property role of a null object.

Now, you can just check for null before validating the role, this way the API will at least return the correct error. (e.g. see here)

Something along the lines of (haven't tested the code):

if (null == req?.user?.role) {
    return next(new ErrorHandler(`Bad request`, 400));
}

But that still doesn't solve the issue for a valid request. For that I suggest you give us some more information on how you declare the request.

CodePudding user response:

From the place you called this method and you assigned role: null, then change it to role: '' it may work.

  • Related