'Getting error: Cannot read properties of undefined (reading 'id')

I am getting the following error in my terminal while running the code:

Cannot read properties of undefined (reading 'id')

I have one middleware and other routes also. There I am not getting this error.

const router = express.Router();
const fetchuser = require("../middleware/fetchuser");
const Notes = require("../models/Notes");
const { body, validationResult } = require("express-validator");

//Route: 1 Fetch all notes using GET /api/auth/fetchallnotes     login required
router.get("/fetchallnotes", fetchuser, async (req, res) => {
  try {
    const notes = await Notes.find({ user: req.user.id });
    res.json(notes);
  } catch (error) {
    console.log(error.message);
    res.status(500).send("some error occured");
  }
});
//Route: 2 add a new note using post /api/auth/addnote     login required
router.post(
  "/addnote",
  fetchuser,
  [
    body("title", "Enter a valid title").isLength({ min: 3 }),
    body("description", "Description must be atleast 5 character").isLength({
      min: 5,
    }),
  ],
  async (req, res) => {
    try {
      const { title, description, tag } = req.body;
      //if there are errors return bad request and the error
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
      const notes = await new Notes({
        title,
        description,
        tag,
        user: req.user.id,
      });
      const savedNote = await notes.save();
      res.json(notes);
    } catch (error) {
      console.log(error.message);
      res.status(500).send("some error occured");
    }
  }
);

module.exports = router;

This is my authentication file, please have a look here I did most of the coding login of a user, fetching data of a user adding a user into the database

const User = require("../models/User");
const router = express.Router();
const { body, validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const fetchuser= require('../middleware/fetchuser');

const JWT_SECRET = "12345678@zxcvbnm";

// ROUTE: 1 Create a user using POST "/api/auth/createuser". no login required
router.post(
  "/createuser",
  [
    body("name").isLength({ min: 3 }),
    body("email").isEmail(),
    body("password").isLength({ min: 5 }),
  ],
  async (req, res) => {
    //if there are errors return bad request and the error
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    // check whether the user already exist with the same mail
    try {
      let user = await User.findOne({ email: req.body.email });
      if (user) {
        return res
          .status(400)
          .json({ error: "Sorry user with same email already exist" });
      }

      //Securing password
      const salt = await bcrypt.genSalt(10);
      const securePass = await bcrypt.hash(req.body.password, salt);

      //create a new user
        user = await User.create({
        name: req.body.name,
        email: req.body.email,
        password: securePass,
      });

      const data = {
        id: user.id,
      };
      const authToken = jwt.sign(data, JWT_SECRET);

      res.json({ authToken });
      //   res.json(user);
    } catch {
      console.log(error.message);
      res.status(500).send("some error occured");
    }
    //   .then(user => res.json(user))
    //   .catch(err=>console.log(err));
  }
);

// ROUTE : 2 authenticate a user using POST "/api/auth/login". no login required
router.post(
  "/login",
  [body("email", "Enter a valid email").isEmail()],
  [body("password", "Enter a valid email").exists()],
  async (req, res) => {
    //if there are errors return bad request and the error
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    const { email, password } = req.body;
    try {
      let user = await User.findOne({ email });
      if (!user) {
        return res
          .status(400)
          .json({ error: "Please provide correct email and Password" });
      }
      const comparePassword = await bcrypt.compare(password, user.password);
      if (!comparePassword) {
        return res
          .status(400)
          .json({ error: "Please provide correct email and Password" });
      }
      const data = {
        user: {
          id: user.id,
        },
      };
      const authToken = jwt.sign(data, JWT_SECRET);
      res.json({ authToken });
    } catch (error) {
      console.log(error.message);
      res.status(500).send("Internal server Error");
    }
  }
);

// ROUTE : 3 Get logged in user detail uding POST "api/auth/getuser" login required
router.post("/getuser", fetchuser, async (req, res) => {
  try {
    userID = req.user.id;
    const user = await User.findById(userID).select("-password");
    res.send(user);
  } catch (error) {
    console.log(error.message);
    res.status(500).send("Internal server Error");
  }
});
module.exports = router;

This is my fetch user file, I am very new to this course, could you please help where I need to change.

const JWT_SECRET = "12345678@zxcvbnm";

const fetchuser = (req, res, next) => {
  // Get the user from the JWT token and add id to the object
  const token = req.header("auth-token");
  if (!token) {
    res.status(401).send({ error: "Please authenticate using a valid token" });
  }
  try {
    const data = jwt.verify(token, JWT_SECRET);
    req.user = data.user;
    next();
  } catch (error) {
    res.status(401).send({ error: "Please authenticate using a valid token" });
  }
};

module.exports = fetchuser;```


Solution 1:[1]

Error Cannot read properties of undefined (reading 'id') means you trying to read <someObject>.id where <someObject> is undefined. In your code it's user.id or req.user.id.

Check user exists before trying to use .id.

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 Volodymyr Sichka