Dave
Dave

Reputation: 2018

Detect expired cookie and logout user

After log in, I have a cookie enter image description here. I am wondering, if it's possible for my app to detect if cookie has expired, and then force logout action? Or just force router push to /login

Does it needs to be done with axios interceptors response or in router guard?

Upvotes: 1

Views: 2186

Answers (1)

Tom Bombadil
Tom Bombadil

Reputation: 3975

You have two options that I know of.

Option 1 (recommended)

Setup an axios interceptor on the response object and listen to the returned responses from the server. Particularly error codes. If the server sends a 401 you can logout the user or request for a new access token to keep user logged in. You can use this npm library to implement the axios interceptors. With the library you can mention the error codes you want to listen to. So, I usually send a 498 error code from the server for all cases that involve expired access tokens, so its easier for me distinguish between expired and unauthorized tokens.

Option 2 (not recommended)

You can use this npm library to decode the JWT on the frontend and extract the expiry time from the token. Create a setInterval() function that regularly checks if the current time is greater or equal to the expiry time. If it is true logout user or request a new token.

Go with option 1 because authenticating a token or its expiry time is the job of the auth server and nobody else. The front-end shouldn't be in charge of deciding whether the token is valid or not. Plus, you don't have to work with setInterval() or setTimeout(), because you'll have to take into account additional edge cases as well.

Upvotes: 2

Related Questions