Search code examples
node.jsasync-awaitexpress-jwt

Bind variables to async in expressjwt


I have a below scenario to pass a parameter from the calling function to the async function with the expressJWT.

module.exports = authorize;

function authorize(roles = ["test"]) {
    const secret = config.Secret;
    return expressJwt({ secret, isRevoked }).bind({ roles: roles});
}

async function isRevoked(req, payload, done, roles) {
console.log(roles) //undefined
}

Here, authorize function calling the async function isRevoked and there I want to pass the parameter roles.

Is this the right way to do it?


Solution

  • If you use an intermediary anonymous function to grab the callback parameters req, payload, and done, then you can pass them with the roles array to the defined function. The roles array will be available to the _isRevoked function because of closures.

    module.exports = authorize;
    
    function authorize(roles = ["test"]) {
        const secret = config.Secret;
        return expressJwt({ secret, isRevoked: (req, payload, done) => _isRevoked(req, payload, done, roles)});
    }
    
    async function _isRevoked(req, payload, done, roles) {
        console.log(roles) // ["test"]
    }