[Vuejs]-How to be warned when jwt expires?

0👍

Check if the token has expired when you load the token from local storage, but before you set the token within the application’s state:

let token = localStorage.getItem("token")
let payload = jwtDecode(token)

// payload.exp should contain the expiration epoch set upon creation
if (payload.exp > Math.round(Date.now() / 1000)) {
  alert("Your token has expired!")
}

If you do not have an expiration field but have an “issued-at” (iat) field, the following logic will also suffice for checking if it has been 30 minutes since it was issued:

const TIME_DELTA = 30 * 60 * 1000; // convert 30 minutes to epoch time 
if (payload.iat + TIME_DELTA <= Math.round(Date.now() / 1000)) {
  alert("Your token was issued more than 30 minutes ago!")
}

Leave a comment