I'm trying to use JWT with nodejs. My problem is that I can't read the data from the JWT verify function. I'm using it like this :
//encode when logging in
const token = jwt.sign(
{ user: user },
'secret'
);
// decode when fetching the user from token
const decoded = jwt.verify(req.body.jwtToken, 'secret');
return res.send({
user: decoded.user // <-- error here
});
Here are the typings for the verify method:
export declare function verify(
token: string,
secretOrPublicKey: string | Buffer,
): object | string;
linter Error is :
Property user does not exists on typeof "object|string".
How am I supposed to get the data from the decoded token?
Link to the documentation of the library
When using Typescript, you have to remember everything is typed as in e.g. Java or C#.
object
is a superclass that has no knowledge of the property user
.
While this code is valid in javascript (you are looking at javascript documentation), it is not in typescript.
To fix this error, cast the decoded token using any
.
return res.send({
user: (<any>decoded).user
});
You need to cast the decoded token. Although casting to any will work, you'll also lose type checking on that variable.
A more robust approach is to declare an interface that captures the structure of your decoded token and cast using it.
// token.ts
export interface TokenInterface {
user: {
email: string;
name: string;
userId: number;
};
}
and then you can cast using
decoded as TokenInterface
or more exactly in your case
return res.send({
user: (decoded as TokenInterface).user
});
Notes:
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