Home > database >  How to properly extract payload from nestjs/jwt token?
How to properly extract payload from nestjs/jwt token?

Time:02-20

I ran into a problem with decrypting a token in a project, I want to extract data from the incoming token, compare it with the data from the database, and then perform certain actions. The problem is that when I get the payload from "jwtService.decode()", I can't access the "decodedJwt.email" field, nest complains that "decodedJwt" is not an object. But if you return typeof "decodedJwt" then the answer is a string. However, I cannot access the "email" field in the code itself. If I return "decodedJwt" in this function, then in postman I will get the very necessary object with the necessary fields, including the same "email" field. What's my mistake?

Reply from nest: Property 'email' does not exist on type 'string | { [key: string]: any; }'. Property "email" does not exist on type "string".ts(2339)

async refreshTokenByOldToken(authHeader: string) {
  const decodedJwt = this.jwtService.decode(authHeader.split(' ')[1])
  return decodedJwt.email
}

CodePudding user response:

You need to cast the type. Tell explicitly what type it is.

type PayloadType = {
  email: string;
}

async refreshTokenByOldToken(authHeader: string) {
  const decodedJwt = this.jwtService.decode(authHeader.split(' ')[1]) as PayloadType;
  return decodedJwt.email
}

You can reference PayloadType other places as well for example in your service instead of string | { [key: string]: any; } you can have string | PayloadType.

examples of type casting

CodePudding user response:

because your decodedJwt string is different data type. You access email information two cases;

  1. If you nestjs-jwt package
const decoded: JwtPayload = this.jwtService.decode(yourAccessToken);

const email = decoded.email;

OR

  1. Base 64 Converting

    const base64Payload = authHeader.split(" ")[1];    
    const payloadBuffer = Buffer.from(base64Payload, "base64");
    const updatedJwtPayload: JwtPayload = JSON.parse(payloadBuffer.toString()) as JwtPayload;
    
    const email = updatedJwtPayload.email;
    
  • Related