2

I want to automatically logout the user based on inactivity of the user. I am trying to delete the cookies which store user token, but this is not working. Can you Please provide me the better solution.?

3
  • 1
    Can you Please share all the approaches which you have tried till now. Commented Dec 15, 2021 at 14:29
  • I want to detect user inactivity on browser Commented Dec 15, 2021 at 15:22
  • Okay, I got your point, I have written the answer for you. I hope it will help you. Commented Dec 15, 2021 at 15:25

3 Answers 3

2

You should first verify the browser's inactivity, afterwards you can delete the cookie as per your requirements. Following library is optional, hence it would be beneficial:

import { useCookies } from 'react-cookie';


const [cookies, setCookies, removeCookies] = useCookies(['token']);
function checkIdleness() {
var t;
window.onload = timerReset;
window.onmousemove = timerReset;
window.onmousedown = timerReset;  // catches touchscreen presses as well      
window.ontouchstart = timerReset; // catches touchscreen swipes as well 
window.onclick = timerReset;      // catches touchpad clicks as well
window.onkeydown = timerReset;
window.addEventListener('scroll', timerReset, true); // improved; see comments

function writeYourFunction() {
  // your function for too long inactivity goes here
  removeCookies('token', { path: '/' })
}

function timerReset() {
  clearTimeout(t);
  t = setTimeout(writeYourFunction, 10000);  // time is in milliseconds
}


}


checkIdleness();
Sign up to request clarification or add additional context in comments.

Comments

1

You first need to check the idleness of the browser. For detecting idle time, refer to this Question How to detect idle time in JavaScript After that, you can delete the cookie as per your need. For deleting the cookey, follow this link https://www.guru99.com/cookies-in-javascript-ultimate-guide.html#:~:text=JavaScript%20Delete%20Cookie,expires%20to%20a%20passed%20date.

Comments

0

If the cookie you're trying to delete is an httpOnly cookie, which is often the case and a best practice for storing authorization tokens, you won't be able to delete it using client-side javascript. Instead, you'll need to make another request to your backend, which can remove the cookie.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.