Search code examples
javascriptjwtobject-literal

expiresIn not working in jsonwebtoken.sign() even with object literal


Here is my code, as you can see, I am using an object literal as suggested in the jsonwebtoken library help, but the result is always the same

  const TOKEN = {
    JWT: JWT.sign({
      iat: Date.now(),
      data: {
        username: USER.name,
        userLevel: USER.level,
        userId: USER._id,
        limit: USER.limit,
        has2FA: USER.has2FA
      }
    }, SECRET_KEY,
    { expiresIn: 60 * 60 * 12 }
    )
  }

As you can see, this code returns both the iat and exp with just a few minutes and seconds of difference instead of the 12 hours that I want.

Any ideas on why is this happening?

enter image description here


Edit: I am using jsonwebtoken and Dayjs to display the time.


Solution

  • The problem seems to be related to the fact that you are specifying iat in milliseconds whereas it's expected to be in seconds. So either do

    iat: Date.now()/1000,
    

    or completely remove that property because that's the default value anyway.