Faizan Ahmed
Faizan Ahmed

Reputation: 21

React JS delete cookie based on browser inactivity

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

Upvotes: 2

Views: 1022

Answers (3)

Aamir
Aamir

Reputation: 176

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

Upvotes: 2

Mehr Muhammad Hamza
Mehr Muhammad Hamza

Reputation: 117

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.

Upvotes: 1

TLadd
TLadd

Reputation: 6884

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.

Upvotes: 0

Related Questions