Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript jwt.verify cannot access data

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

like image 849
C Taque Avatar asked Jun 07 '18 07:06

C Taque


2 Answers

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
});
like image 157
Nico Van Belle Avatar answered Sep 30 '22 18:09

Nico Van Belle


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:

  1. The casting is done at compile time, not runtime
  2. Creating an interface has the added benefit that you keep your type definition in one place. This is especially useful if you want to add a field of that particular type to an existing object. An example of this is adding the token as a field on object of the express.Request type.
like image 29
Radu Diță Avatar answered Sep 30 '22 19:09

Radu Diță