5

I'm using the highly popular jsonwebtoken package for node. Signing and verifying are typically performed synchronously, but async options are also provided.

I thought that the operations involved are neither data-bound nor computationally expensive, so there is no risk of burdening the main/user thread. I don't see a perf benefit.

So why would such operations be performed asynchronously - what is the benefit?

lonix
  • 14,255
  • 23
  • 85
  • 176
  • There is benefit for async call. Sometime it takes little more time and it may be possible that you hit the request before generating the JWT. I have already faced a similar issue and it was resolved by using async calls to generate the JWT – Nipun Chawla Feb 11 '19 at 11:14
  • @NipunChawla That's interesting... what do you mean hit the request? – lonix Feb 11 '19 at 11:15
  • 1
    @Ionix I was calling a http request using JWT token for authentication. But many of the requests were failing because the corresponding JWTs were not being generated, causing the requests to return 401 – Nipun Chawla Feb 11 '19 at 11:20
  • @NipunChawla Interesting... – lonix Feb 11 '19 at 11:25

1 Answers1

6

Looking over the package source code the only reason for the async callback (when verifying a token) seems to be when the secret/public key is provided in an async manner:

if(typeof secretOrPublicKey === 'function') {
  if(!callback) {
    return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback'));
  }

  getSecret = secretOrPublicKey;
}

https://github.com/auth0/node-jsonwebtoken/blob/da8f55c3c7b4dd0bfc07a2df228500fdd050242a/verify.js#L73

Andrei Tătar
  • 7,872
  • 19
  • 37
  • Am I correct that there is no perf benefit? From what I recall all node's crypto functions are sync, and this library I assume uses those crypto functions anyway. – lonix Feb 11 '19 at 11:16
  • 1
    You are correct.... the sign/verify code in jwa package (that it uses) seems to all be synchronous. Even the crypto methods used (https://nodejs.org/api/crypto.html) are all synchronous. There's no async variant to them. – Andrei Tătar Feb 11 '19 at 11:18
  • Thanks for confirming – lonix Feb 11 '19 at 11:26