Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript error with accessing jwt-decode object

Tags:

typescript

jwt

I have installed @types/jwt-decode and I'm having trouble getting this to work.

import jwtDecode from 'jwt-decode'

...
let decodedToken = jwtDecode(token);
console.log(decodedToken) // this works! I can see the full object
console.log(decodedToken.exp) // error Object is of type 'unknown'.ts(2571)
like image 975
Jamie Avatar asked Apr 14 '20 01:04

Jamie


3 Answers

The issue is jwtDecode is unaware of what is inside your token, as it could be anything. Because of this, it uses the type unknown to signify that result of the decoded JWT is, unknown.

To get around this you will need to create an interface describing what you expect to be in your JWT and tell jwtDecode to use it as the return type of the decoded token. You can do so like this:

interface MyToken {
  name: string;
  exp: number;
  // whatever else is in the JWT.
}

const decodedToken = jwtDecode<MyToken>(token);
console.log(decodedToken.exp); // works!
like image 53
domsim1 Avatar answered Nov 15 '22 10:11

domsim1


For v3.1.1, type definitions have been added recently.

import jwt_decode, { JwtPayload } from 'jwt-decode'

const decodedToken = jwt_decode<JwtPayload>(token)

Also added by @Martina in the comments section, parsing non-standard claims can be done also by extending a type on the JwtPayload interface for creating a custom jwt payload type such as:

type customJwtPayload = JwtPayload & { some_property: string };

and then,

const decodedToken = jwtDecode<customJwtPayload>(token);
like image 38
Gams Basallo Avatar answered Nov 15 '22 11:11

Gams Basallo


I have done this and worked for me.

yarn add jwt-decode
yarn add -D @types/jwt-decode 

And this is the function that has been implemented for checking the token:

import jwtDecode, { JetPayload } from 'jwt-decode'

const token = localStorage.getItem('token');
if (!token) return
const decodedToken: JwtPayload = jwtDecode(token);
if ((decodedToken?.exp as JwtPayload) < new Date().getTime()) {
  // code here
}

the snippet below is the one that worked for me, and remove the error when I was trying to validate decodedToken.exp

like image 29
Emad Baqeri Avatar answered Nov 15 '22 12:11

Emad Baqeri