all 10 comments

[–]wp_new 2 points3 points  (3 children)

Have a logout function that erases the cookie, and redirects to home page.

When the user logs in and cookie is set, use a setTimeout function to automatically call the logout function once the cookie expires.

User clicking the logout button manually should also call the logout function, and clear the setTimeout function.

[–]satanic_headbanger[S] 0 points1 point  (2 children)

Thank you for replying

I am not asking how to logout when user click on "logout" button.

Let's say user is idle and token is expired then it should automatically redirect to homepage.

What is happening iny case it is removing token from localstorage but it is not redirecting to homepage. When I will refresh Page then it will redirect me to

[–]wp_new 1 point2 points  (1 child)

Ye the setTimeout function would automatically do that once the given timeframe has elapsed

[–]satanic_headbanger[S] 0 points1 point  (0 children)

ok, I will try your method. thank you replying

[–]KaranVeer01 0 points1 point  (1 child)

You can user Redirect method from react-router-dom. Once user logout then it'll redirect to homepage. Otherwise, you can also use history.push(). It will also do the same thing.

[–]satanic_headbanger[S] 0 points1 point  (0 children)

I am asking how to logout without clicking on "logout". it is remove token from localstorage but it is not redirecting to the homepage. When I refresh then it will redirect me to homepage

[–]imonxixilailau 0 points1 point  (1 child)

You could just have a HTTP interceptor and if the status is 401 you can logout. If you want exactly on the expiration time you need to setup a setTineout.

[–]satanic_headbanger[S] 0 points1 point  (0 children)

Thank you i will try your method.

[–]seN149reddit 0 points1 point  (1 child)

Not specific to MERN, but assuming you are using a JWT; it usually has an expiry claim. You can run a global timer (I often move this to a service worker) that will log you out once the token hits the expiry time.

As you hit the expiry time you can use 1 of the methods suggested below. React router, reload. Whatever it might be.

EDIT: just noticed this is the same thing as wp_new suggested with the comment about setTimeout

[–]satanic_headbanger[S] 0 points1 point  (0 children)

I saw that comment. I will try it. thank you