Skip to content

Improve fastify.jwt.verify by either making errors easier to handle via callback, or returning a promise.聽#294

Description

@autopulated

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

馃殌 Feature Proposal

Since it isn't possible to await this function (as opposed to calling the synchronous version), for async execution we have to use a callback, which makes handling both the callback-returned and thrown errors ugly.

So I think, either:

  • The JWT validation errors always be returned via the callback, and never thrown if the callback is passed
  • Or, just to make .verify and .sign await-able. The existing synchronous versions makes that difficult though.
  • Or, new .verifyAsync and .signAsync that returns a promise?

Motivation

For context, since eddsa signatures are relatively expensive to verify (at least, more expensive than signing), I'm assuming that it's generally good practise not to block the event loop / use synchronous node:crypto apis when verifying them, but maybe I have a misunderstanding here.

Maybe the synchronous API should just go away, and be replaced by an awaitable version returning a promise, I suggest calling it verifyAsync to avoid confusion with the current synchronous version.

Example

// error handling for current async .verify api:
async function myRoute(request, reply) {
    return new Promise((resolve, reject) => {
        try {
            fastify.jwt.verify(request.body.token, (err, decoded) => {
                if (err) {
                    // handle user-facing errors / internal errors  here 
                } else {
                    // ...
                }
            });
        } catch (e) {
            // handle user-facing errors / internal errors also here
        }
    });
}

// proposed api:
async function myRoute2(request, reply) {
    try {
        const decoded = await fastify.jwt.verifyAsync(request.body.token);
        // ...
    } catch (e) {
        // handle user-facing errors / internal errors here
    }
}

Activity

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions