Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

536
Views
How to properly extract payload from nestjs/jwt token?

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
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
    
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!