here is the code for auth using jsonwebtoken which i got from youtube tutorial, why req.user =user
import jwt from "jsonwebtoken";
const auth = (req, res, next) => {
try {
const token = req.header("Authorization");
if (!token) return res.status(400).json({ msg: "Invalid Authentication" });
jwt.verify(token, process.env.SECRET_JWT, (err, user) => {
if (err) return res.status(400).json({ msg: "Authentication Failed" });
req.user = user;
next();
});
You set req.user = user
so that you can actually use this in a later middleware function called after this one (triggered by next()
.
If you do not do something similar to this, you would not know who the user is in the next middleware function or you would have to verify/decode the token every time you need to know who the user is.