-2

I'm implementing JWT Authentication in a full-stack (React + Node.js + Express) application. Login works, token is generated correctly, and the client sends it in the Authorization header.
However, inside my protected route, req.user is always undefined even though the token verifies successfully.

Frontend:

axios.get("http://localhost:5000/api/profile", {
  headers: {
    Authorization: "Bearer " + localStorage.getItem("token")
  }
})
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

Middleware:

const jwt = require("jsonwebtoken");

module.exports = function (req, res, next) {
  const authHeader = req.headers["authorization"];
  
  if (!authHeader)
    return res.status(401).json({ message: "No token" });

  const token = authHeader.split(" ")[1];

  jwt.verify(token, "mysecretkey", (err, decoded) => {
    if (err)
      return res.status(403).json({ message: "Invalid token" });

    console.log("Decoded:", decoded); // shows correct payload
    req.user = decoded;               // supposed to attach user
    next();
  });
}

Protected Route:

router.get("/profile", authMiddleware, (req, res) => {
  console.log("User inside route:", req.user); // prints undefined
  res.json({ message: "Success", user: req.user });
});

Expected behavior

req.user should contain the decoded token payload inside /profile.

Actual behavior

  • jwt.verify() prints the correct decoded payload
  • But inside the route, req.user becomes undefined
  • No error is thrown.

Question:

  • Under what conditions can req.user become undefined after being set in a middleware?
  • Is this due to middleware order, multiple handlers on the same route, or something else?
  • What should I check to ensure the modified req object is correctly passed to the route handler?
New contributor
Pranay Reddy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
0

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.