0

I have a login component that talks with a backend to obtain a JWT token to be stored in localStorage. The API is successfully responding with the JWT but nothing is being stored in the localStorage. The code for onSubmit button in my component is provided below.

const onSubmit = (e) => {
    e.preventDefault();
    auth.login(() => {
      let roles = new Set();
      // As every user is a normal user
      roles.add({ role: "NORMAL_USER" });
      roles.add({ role: userType });
      let payload = {
        userName: email,
        password: password,
        roles: Array.from(roles),
      };
      axios
        .post(`${process.env.REACT_APP_API_URL}/login`, payload)
        .then((res) => {
          var info = {
            email: email,
            type: userType,
            jwt: res.data.jwt,
          };
          localStorage.setItem("info", JSON.stringify(info));
          if (userType === "NORMAL_USER") history.push("/usage");
          else if (userType === "RESEARCHER") history.push("/research");
        })
        .catch((error) => {
          if (error.response) {
            setShowError(true);
            setErrorMessage(error.response.data.detail);
          } else {
            setShowError(true);
            setErrorMessage("Server Error");
          }
          clearForm();
        });
    });
  };

The definition of auth.login() can be found as under:

class Auth{
    constructor(){
        this.authenticated = false;
    }

    login(callback){
        this.authenticated = true;
        callback();
    }

    logout(callback){
        this.authenticated = false;
        callback();
    }

    isAuthenticated(){
        return this.isAuthenticated;
    }
}

export default new Auth();

Kindly let me know in comments if more information is required.

  • There is nothing wrong with your localStorage call. You should provide more details. Are there any errors? How did you verify it doesnt exist? Have you tried debugging and verifying it does not reach that statement? – Deadron Jan 15 '21 at 18:15
  • I tried `localStorage.getItem("info")` in the console right after the next page is loaded. I also tried to log a string before setting localStorage and it logged successfully. There's no error in the console too. – sharmataveesh Jan 15 '21 at 18:18
  • Is it possible your next page is on a different domain? LocalStorage is only accessible within the same origin (protocol, domain, port). Try checking the localstorage on the page its set. – Deadron Jan 15 '21 at 18:21
  • The next page is in the same domain. Both the pages are on http://localhost:3000. – sharmataveesh Jan 15 '21 at 18:25
  • This doesn't fix your issue, but localStorage is not recommended for storing JWTs. Cookies are a better option because they include domain restrictions and the `httponly` property. There's some more detail [here](https://stackoverflow.com/a/44209185/5774952). – Zac Anger Jan 15 '21 at 18:31
  • @ZacAnger I guess I should use cookies instead of localStorage. Thanks for sharing the info. – sharmataveesh Jan 15 '21 at 18:43
  • @ZacAnger I tried storing JWT token as a cookie, the storage still shows nothing. – sharmataveesh Jan 15 '21 at 19:24

0 Answers0