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.
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.
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.
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.
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.