'How to store and get req.user from JsonwebToken
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
Solution 1:[1]
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);
}
Solution 2:[2]
exports.userId = (req,res,next)=> {
const token=req.cookies.jwt;
jwt.verify(token, jwtSecret, (err, decodedToken) => {
req.userId= decodedToken.id;
})
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);
}
});
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 | |
| Solution 2 |
