How to correctly extend expiration of JWT token in NestJS?

65 Views Asked by At

I need to improve the JWT token logic to extend expiration each time, when I will call any REST API request. For this purpose, I was created a method to extend jwt expiration to next 60 seconds, each time, when the method is called:

  /**
   * Method to extend the token expiration
   * @param oldToken
   */
  extendTokenExpiration(oldToken: string) {
    const decoded = this.jwtService.decode(oldToken);
    decoded.exp = decoded.exp + 60;
    try {
      const newToken = this.jwtService.sign(decoded, {
        secret: jwtConstants.secret,
      });
      console.log('New token:', newToken);
      return newToken;
    } catch (e) {
      console.log('Error:', e);
    }
  }

Problem is, that still I will receive an following error:

 Error: Bad "options.expiresIn" option the payload already has an "exp" property.

If I will manually delete the decoded.exp prop and add expiresIn into the options, the error disappears, but expiration if this jwt token still stay the same (expiration is not extended).

Thanks a lot for an each help.

0

There are 0 best solutions below