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.
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".
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);
};
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.
const [userID, setUserID] = useState(null);
const [isRemembered, setIsRemembered] = useState(false);
useEffect(() => {
const storedID = localStorage.getItem("userID");
const remembered = localStorage.getItem("isRemembered") === "true";
setUserID(storedID);
setIsRemembered(remembered);
// If remembered, fetch token and potentially set user state
}, []);
const handleLogin = async () => {
// ... login logic ...
if (isRemembered) {
localStorage.setItem("userID", userData.id); // Store user ID
} else {
localStorage.removeItem("userID"); // Clear stored ID
}
};
const handleLogout = () => {
localStorage.removeItem("userID");
localStorage.removeItem("isRemembered");
// ... logout logic ...
};
Storage: Use localStorage for user ID and isRemembered flag (not password!).
Checkbox & Storage: Add "Remember me" checkbox. Store data only if checked.
Retrieval: On component mount, check for stored data.
Logic:
- If userID and isRemembered:
- Fetch new JWT using userID from backend (backend dependent).
- If successful, set user state to logged-in.
- Else, proceed with normal login.
5 . Security:
- Never store passwords in plain text.
- Set expiration for "remember me" functionality.
- Consider HttpOnly cookies for added security.
- Logout: Clear stored data on logout.
© 2022 - 2024 — McMap. All rights reserved.