9

I currently have to implement remember functionality for remembering my login info on my frontend website. How to implement remember me functionality for authentication in ReactJS when i only receive jwt token from backend API.

Bryan Lumbantobing
  • 604
  • 1
  • 7
  • 22

5 Answers5

13

Once you receive a jwt token, you can set an "expiry time" for your jwt token. For example, if I receive a token with id: "abc_token_123", I will create an object inside sessionstorage, localstorage, or even cookies with a key called expireTime (for example). And I will use a useEffect hook on the main file (App.js) to watch for the time, if the time exceeds the expiry time, log the user out, otherwise, if the expiry key is present inside your storage, keep the user logged in.

CookieMaster
  • 171
  • 3
4

Store the JWT in browser Local Storage if the user chooses the remember me option. Assuming you can change the backend JWT expiry, make the JWT expiry longer (whatever is an acceptable number of days between logins) where the user has chosen remember me.

Hopey One
  • 1,681
  • 5
  • 10
  • I only can access the token because I'm working on the frontend side and there is no way to make jwt expiry login from the frontend I think. so what you mean is if the user didn't choose the remember me option then the access token is saved in the cookie and if the user chooses the remember me options I store the token in local storage. ?? – Bryan Lumbantobing Dec 15 '20 at 04:47
  • 1
    Cookies would work too if they are permanent, I was referring to the difference between Session Storage (removed when you close your browser) and Local Storage (survives browser restart). But you get the gist, Local Storage for remember me Session Storage if not. You might be out of luck however if you can't change the JWT expiry at the server. Your remember me will be limited to the validity period of the JWT. – Hopey One Dec 15 '20 at 05:01
2

You can do this feature by creating the remember-me checkbox and making a reference for it:

const rememberCheck = useRef(null)

In this particular case I used useState to declare the credentials, because I think it's easier to set the defaultValue on my input fields just by setting them as the value on localStorage:

const [email, setEmail] = useState(localStorage.getItem("myapp-email") || "");
  const [password, setPassword] = useState(localStorage.getItem("myapp-password") || "");

And then create a function to check if it should be remembered or not:

function remember(){
        if(rememberCheck.current.checked){
          localStorage.setItem("myapp-email", email); localStorage.setItem("myapp-password", password)
        }
        else{
          localStorage.setItem("myapp-email", ""); localStorage.setItem("myapp-password", "")
        }
      }

Then use this function to increment your submit() function, check the response of your API call and if its 200 (JWT token received from backend) you call the remember() function to store your login and password on localStorage.

Note: Also remember that the "email" and "password" keys are shared between all applications, so it's nice to set a flag on it like "myapp-email" and "myapp-password".

Yuri Leon
  • 21
  • 2
0

After a search online I was able to find this answer in this website. The site also expands on how to load it.

function setWithExpiry(key, value, expiration) {
    const now = new Date()

    // `item` is an object which contains the original value
    // as well as the time when it's supposed to expire
    const item = {
        value: value,
        expiry: now.getTime() + expiration,
    }
    localStorage.setItem(key, JSON.stringify(item))
}

You do this to set up a way to save 'RememberMe' to your local storage with some expiration time.

0

I prefer @Hopey One's idea.

Store the JWT in browser Local Storage if the user chooses the remember me option.

In my case, I need a token to communicate with API from time to time(But right now I don't have a token in localStorage because the user hadn't chosen the remember me option). So I used a state to keep that. Everything worked perfectly but the problem is when I refresh the page my token is null. So, I used sessionStorage to store the token when the user don't select the remember me option. This is a code sample from my useAuth custom hook file.

const [token, setToken] = useState(
  sessionStorage.getItem('token') || localStorage.getItem('token'),
);

const login = (token: string, rememberMe = false) => {
  if (rememberMe) {
    localStorage.setItem('token', token);
  } else {
    sessionStorage.setItem('token', token);
  }
  setToken(token);
};

const logout = () => {
  localStorage.removeItem('token');
  sessionStorage.removeItem('token');
  setToken(null);
};
Sanka Sanjeewa
  • 1,993
  • 14
  • 16