DEV Community

Cover image for How do you handle jwt token expiration?

How do you handle jwt token expiration?

nikosdev profile image Nikos Kanakis Updated on ・1 min read

Let's say we have the following scenario: A user login with correct credentials and he gets a token with expiration date. After some time
(lets say 30 minutes) the token is expired and the user has to give again his credentials to be authorized. Our Goal is to not force the user give his username and password again.

How would you handle this problem? 😉

Discussion (5)

Editor guide
rhymes profile image

Let me understand, you are asking for a refresh token for such expired token right?

I would do it with OAuth 2.

Client asks for authorization -> User authenticates -> Server issues an expiring access token (the jwt) and a refresh token -> User does their business -> Token expires -> client exchanges the refresh token with a new access token

Basically you can just use OAuth, the only difference is the token instead of being a random string it's a "speaking" JWT token with all the attributes you insert into it.


adityathebe profile image
Aditya Thebe

How is this advantageous over setting the expiration duration to like a month ?

rhymes profile image

Well, it doesn't fit the requirements :) Also, it can be a security liability, depending on the ability of the server to expire/invalidate the content of the access token. This is a good overview of three strategies: Access Token Lifetime

The first strategy is the one I was talking about: short expiration for tokens, long for refresh tokens. The second is the one where you make tokens expire and make the user login often (but it defies the requirements), the third one is the one where the token never expires but it strongly depends on the infrastructure and the ability to revoke tokens

nikosdev profile image
Nikos Kanakis Author

Thanks for your answer! 🚀

tetch6 profile image

I have a question about generating a new token with the refresh token.
let's say a user logged in, got his access token and a refresh token, the access token will expire in 15 minutes.
What is the best way to go about it ?
1) set a timeout that will execute an API call to get a new access token after 15 minutes (let's say 14.5 minutes to be on the safe side)
2) set an interceptor that will check if the token is still valid and if not first get a new token and then continue with the request
3) is there another way I didn't considered?

I am using jsonwebtoken, axios and node.js

will appreciate any answer
thanks :)