Reputation: 1449
I have module to check if the expiration date of token is already expired or not. so if ever the token is expired it will automatically the page will go to login again.
I already code it but their is error in my console and my page is loading anymore.
Uncaught InvalidTokenError {message: "Invalid token specified"}
List not working
This is my code:
if (localStorage.getItem("token") === null) {
let token_expired = localStorage.getItem('token');
let decoded = decode(token_expired, { header: true });
let decode_string = decoded["exp"];
var current_time = Date.now() / 1000;
if(decode_string < current_time)
{
localStorage.clear();
}
}
Upvotes: 3
Views: 33923
Reputation: 406
I had to add .token to the token that I received from storage like this:
Get token from storage
Give that token to jwtDevode as a parameter and add .token at the end
Upvotes: 1
Reputation: 117
It might be a payload in Back-end it's just only a string, a number so it can't decode it out. I change back the payload in Back-end became an object and it worked.enter image description here
Upvotes: -1
Reputation: 300
As Isaac has suggested, your jwt has a bad format hence throws the error preventing further execution of code. I suggest putting your logic in a try catch block like this:
try {
//what you are doing..
if (localStorage.getItem('token') === null) {
let token_expired = localStorage.getItem('token')
let decoded = decode(token_expired, { header: true })
let decode_string = decoded['exp']
var current_time = Date.now() / 1000
if (decode_string < current_time) {
localStorage.clear()
}
}
} catch (e) {
localStorage.clear() //what you need to do incase the jwt is not valid
console.log(e) //for your own debugging
}
Upvotes: 0
Reputation: 297
I think that your token does not exist.
Go inside dev tools (ctrl +shift + i) then
Select Application
Inside the Application go to Storage then
Open Local Storage (double click on local storage) then
Clear local storage
Upvotes: 3
Reputation: 2166
I think you need to change the first condition, and use declarative names for variables.
const storedToken = localStorage.getItem("token");
if (storedToken){
let decodedData = decode(storedToken, { header: true });
let expirationDate = decodedData.exp;
var current_time = Date.now() / 1000;
if(expirationDate < current_time)
{
localStorage.removeItem("token");
}
}
Upvotes: 2