I'm using jsonwebtoken
to decode a token, and I'm trying to get the expiration date. Typescript is throwing errors regarding the exp
property, and I'm not quite sure how to solve them:
import jwt from 'jsonwebtoken'
const tokenBase64 = 'ey...' /* some valid token */
const token = jwt.decode(tokenBase64)
const tokenExpirationDate = token.exp
// ^^^
// Property 'exp' does not exist on type 'string | object'. Property 'exp' does not exist on type 'string'.
I have installed @types/jsonwebtoken
, and looked for a token type to cast token
, but did not find any. Suggestions?
Using
.tsconfig:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"jsx": "Preserve",
"moduleResolution": "Node",
"module": "ESNext",
"sourceMap": true,
"removeComments": true,
"allowSyntheticDefaultImports": true,
"target": "ESNext"
}
}
You can use a lib(like jwt_decode) to decode your JWT token, where it's most likely contains an expiration timestamp that you can check(compare it with the current timestamp for this moment) and if it exceeded(expired) just delete it from local storage and redirect user to login page.
There are two ways to check if Token is expired or not. I will show you the implementations of both ways. – For 1, we check the token expiration every time the Route changes and call App component logout method. – For 2, we dispatch logout event to App component when response status tells us the token is expired.
I think import * as jwt from 'jsonwebtoken';
should work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With