Home > Back-end >  React JS delete cookie based on browser inactivity
React JS delete cookie based on browser inactivity

Time:12-15

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

CodePudding user response:

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 Delete Cookie,expires to a passed date.

CodePudding user response:

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();

CodePudding user response:

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.

  • Related