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)
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!
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);
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
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