Improve fastify.jwt.verify by either making errors easier to handle via callback, or returning a promise.
- Dominant language
- JavaScript
- Stars
- 586
- Forks
- 120
- PR merge metrics
- No merged PRs in 30d
Description
### Prerequisites
- [X] I have written a descriptive issue title
- [X] 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
```js
// 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
}
}
```
Contributor guide
Assessment
This issue has not been assessed yet.