How to store and get req.user from JsonwebToken I am developing a booking application using node the only thing left to do now is to get the user information who booked the product and display it in the admin portal
.then((user) => {
const maxAge = 3 * 60 * 60;
const token = jwt.sign(
{ id: user._id, username, role: user.role },
jwtSecret,
{
expiresIn: maxAge, // 3hrs
}
);
res.cookie("jwt", token, {
httpOnly: true,
maxAge: maxAge * 1000,
});
now i wanna access the user id from any router i have
CodePudding user response:
Pass the token to your backend and deserialize it to get the data you need.
app.use("/your_route", async function (req, res, next)
{
console.log( req.headers.cookie);
var token = ""
//HERE GET YOUR JWT and put it in variable token
//jwtSecret is your secret jwt
var tokenData = jwt.verify(token, jwtSecret)
console.log(tokenData);
}
CodePudding user response:
install npm jwt-decode
const jwt_decode = require("jwt-decode");
//make a middleware and call it where you need the jws id
exports.userId = (req, res, next) => {
const token = req.cookies.jwt;
const { id, role } = jwt_decode(token);
req.userId = id; // Add to req object
next();
}
and this is the file where I want the userid
router.get("/",userId, async (req, res) => {
try {
const id = req.userId;
console.log(id);
} catch (e) {
console.log(e);
}
});