Pedro Brost
Pedro Brost

Reputation: 1452

Best practices for refreshing JWT in SPA?

Hi I'm developing a React app that communicates with an Express API. I'm trying to implement JWT authentication but I don't know what should happen when the jwt expires. It not seems very user friendly if the user is logged out when the token expires.

Should I use refresh tokens? As it says in the node-jsonwebtoken package documentation (jsonwebtoken). This may not be the best approach.

Should I create a new jwt in every request to the server? If the user reads an article for a long time without doing any request, he is going to be logged out.

Maybe I'm wrong and the best practice is using a big expiration time and let the user be logged out. If this is the case what would be a reasonable time?

Thanks!

Upvotes: 2

Views: 2202

Answers (1)

Steve Vaughan
Steve Vaughan

Reputation: 2189

A pattern commonly used along with refresh tokens is to follow a workflow along the lines of:

  1. Some API call / resource returns with a 401, alerting that the token has expired, this sometimes is accompanied by a reason, e.g. Expired token, invalid token
  2. Create a reference to the API call that failed, to retry later
  3. Attempt to refresh the token with the refresh_token
  4. If the refresh works, go ahead and perform the queued API call again
  5. If the refresh fails, the user will need to log in again

You can also use the above approach to queue multiple failed requests, in the event that multiple calls fails whilst a refresh is taking place.

Coupled with a decent expiry time, which really depends on your application, this has proven to be a robust solution in the past for me.

An alternative approach would be to implement a 'heartbeat' API call that updates the user's token periodically whilst they are on the site, however this may come with side effects that may not be desired.

Upvotes: 2

Related Questions