Home > Software design >  Implement a timer for user logout after timeout in the frontend
Implement a timer for user logout after timeout in the frontend

Time:02-08

I was wondering what the best way of implementing a timer in the frontend would be.

The idea is to notify the user after 13 minutes of inactivity (= not made a request to the backend) that he will be logged out in 2 minutes.

My first attempt was to just use a Timer which is executed every second (I am doing this with Flutter web but it shouldn't make a difference) and counts down from 15 minutes.

Then we tested this internally and noticed that the Browser somehow stops JavaScript execution if the user switches to a different tab for a long time or if the computer goes into stand by such that the timer stops.

We already have a session timeout after 15 minutes from the backend, this is just to make the user experience better.

How would this be correctly implemented?

CodePudding user response:

For short, I think it's impossible for only using frontend

As you examine, the javascript code will be stop whenever switching tab or close tab, computer stands by. So that it will not be good to use a timeout or something like that.

I used an idea before but not implemented it yet because I switched to simpler idea with sessionStorage. But you could see and somehow success with it: when last request is made, created a cookie with expire time is 13 minutes. If next request is made, clear old cookie and add a new cookie with 13 minutes too. If the request will not made during 13 minutes, when cookie expire, fire a event to annouce to user. To listening cookie change, I think there are a lot solutions out there. But for me, this idea is not so good so I forgot it.

If you can use a nodejs backend, you could try to use Server Send Event - SSE. This will create one-way sending data. Therefore you can stream a chunk of data. And the frontend will listen that streaming and decide whether to annouce to user.

  •  Tags:  
  • Related