Skip to content

jwt.verify is not async based on callback #984

Open

Description

@jazelly

Description

jwt.verify(token, secretOrPublicKey, [options, callback])
(Asynchronous) If a callback is supplied, function acts asynchronously. The callback is called with the decoded payload if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will be called with the error.
(Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.

Based on the doc, if a callback is supplied, function acts asynchronously. However, it is still a sync operation, considering the following example

jwt.verify(
  'token',
  'secret',
  () => {
    console.log(1);
  }
)
console.log(0);
// 1
// 0

I would expect it's 1 after 0 if it does async operation.

By looking at the implementation, looks like whether or not jwt.verify does async operation is purely based on the behaviour in secretOrPublicKey when it's provided as a function.

return getSecret(header, function(err, secretOrPublicKey) {

Activity

  1. nikwen commented on Jan 31, 2025

    @nikwen

    By looking at the implementation, looks like whether or not jwt.verify does async operation is purely based on the behaviour in secretOrPublicKey when it's provided as a function.

    Related: #566 (comment)

  2. djedu28 commented on Jun 29, 2025

    @djedu28

    @jazelly

    jwt.verify(
      'token',
      'secret',
      () => {
        console.log(1);
      }
    )
    console.log(0);
    // 1
    // 0

    use promisify

    import { promisify } from 'node:util';
    
    await promisify(jwt.verify)(token, "secret")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions