'In nodejs how to add a greeting that greets someone after a login with their first name from the mongodb database?

I want to make a react login and signup form that takes name ,email and password as input and then next page is custom congratulation page with dynamic name in it .Can anyone tell me approach of doing this .Pls



Solution 1:[1]

In login route, you can create a token using jsonwebtoken with necessary information like id, name or any other information that you need about that user. Once you have the token, send the token in response of login request.

When you need the name of user from token, you can use jwtDecode(token) function from jwt-decode package.

Login Route Example:

router.post("/login", validateUserLoginMW, async (req, res) => {
    let userData = await User.findOne({
        email: req.body.email,
    });
    if (!userData)
        return res.status(400).send("Sorry, User with this email not found.");

    let password = await bcrypt.compare(req.body.password, userData.password);
    if (!password) return res.status(400).send("Wrong password");

    let token = jwt.sign(
    {
        _id: userData._id,
        name: userData.fullName,
    },
        "SomeKey"
    );

    let user2 = jwt.verify(token, "SomeKey");
    return res.send({ ok: "Login successfull", token, user2 });
});

Get User Information Example:

export function getloggedinuser() {
  try {
    const jwt = localStorage.getItem("token");
    return jwtDecode(jwt);
  } catch (ex) {
    console.log(ex);
    return null;
  }
}

You will have id and name in jwt object.

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 Uzair Ahmad