Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get token expiration with `jsonwebtoken` using typescript

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"
  }
}
like image 855
aryzing Avatar asked Nov 27 '17 10:11

aryzing


People also ask

How can I get JWT token expiration date?

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.

How do you check if JWT token is expired react?

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.


1 Answers

I think import * as jwt from 'jsonwebtoken'; should work as expected.

like image 196
Elias Avatar answered Sep 30 '22 10:09

Elias