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.userbecomes undefined - No error is thrown.
Question:
- Under what conditions can
req.userbecome 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
reqobject is correctly passed to the route handler?