cookiesjwtbackendexpress-jwt

how to retrive cookis from browser


I have stored cookies in browser from backend. Using these lines of code.

userSchema.methods.generateAuthToken = async function () {
  try {
    let token = jwt.sign({ _id: this._id }, process.env.SECRET_KEY);
    this.tokens = this.tokens.concat({ token: token });
    await this.save();
    return token;
  } catch (error) {
    console.log(error);
  }
};

////////

const token = await loginNow.generateAuthToken();
        res.cookie("jwtoken", token, {
          expires: new Date(Date.now() + 100000000000000),
          httpOnly: true,
        });

I don't have understanding how i can retrieve it in frontend so that i can verify the user i want get these from frontend.How i can do it.


Solution

  • If you know the name of your cookie, you use the example function below to get the value of it using JavaScript on the Front-end. (From W3Schools)

    function getCookie(cname) {
      let name = cname + "=";
      let decodedCookie = decodeURIComponent(document.cookie);
      let ca = decodedCookie.split(';');
      for(let i = 0; i <ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length);
        }
      }
      return "";
    }