Nest js JWT module: verify vs verifyAsync

202 Views Asked by At

Nest js has its own library for using jwt tokens. https://www.npmjs.com/package/@nestjs/jwt . I am confused when to use verify and verifyAsync methods, because in documentation is said that one is used for async operations and another for not async, and that's it. I assume that one of the case for using verifyAsync is when the token is getting asynchronously or we want to make a DB request inside .then(...) block of verifyAsync, but anyway these 2 methods are unclear for me.
Question: Could someone help with a proper exaplanation and also with some examples for each option?

1

There are 1 best solutions below

0
Maxim Baykalov On

verifyAsync is the more natural choice due to its promise-based nature. This keeps your code consistent with the asynchronous flow and non-blocking behavior.

On the other hand, if you're in a context where the code execution is synchronous and you don't need to perform additional asynchronous operations immediately after verification, verify might be simpler and more straightforward to use.

Both methods are valid and useful; the decision is largely about coding style and the specific requirements of the operation you're performing.

  • use verifyAsync when you want to avoid blocking the execution thread while waiting for the verification process to complete, taking advantage of JavaScript's event loop and non-blocking I/O model.

  • use verify when you prefer or it's acceptable to block the execution thread until the verification is complete.