Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

538
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda