node.jstypescriptjwt

Error when trying to Promisify JWT in Typescript


I am trying to promisify jwt verify in typescript, but I am getting this error.

"Expected 1 argument, but got 2.ts(2554)"

Sync version is working fine.

How to fix it?

import util from 'util';
const promisify = util.promisify;

const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET as string);
console.log(decoded);

Solution

  • Glancing at the types for jsonwebtoken and the documentation for verify that should have worked. But we don't live in a perfect world. You can always promisify the function yourself:

    const jwtVerifyPromisified = (token, secret) => {
        return new Promise((resolve, reject) => {
            jwt.verify(token, secret, {}, (err, payload) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(payload);
                }
            });
        });
    }
    

    You'll have to add some annotations but you get the idea.