Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express pass parameter to async middleware

I have a synchronous middleware to authorize role. It's set up like this:

Route:

router.get("/test", [authorizeRole("tier1", "tier2")], function(req, res) {})

Middleware:

module.exports = function authorizeRoles(...role) {
    return (request, response, next) => {
        //authorize
    };
};

This is working. Now i want to change my middleware to make it async.

I can't figure out how to make the middleware async. I tried:

module.exports = async function authorizeRoles(...role) {
    return await (request, response, next) => {
        //authorize
    };
};

module.exports = async function authorizeRoles(...role) {
    return await async (request, response, next) => {
        //authorize
    };
};

But nothing works.

How can i make the middleware async?

like image 656
Tobol Avatar asked Sep 04 '26 13:09

Tobol


1 Answers

I'm not sure I completely understood your question. To use await you need to declare your function using the async keyword, so this should work

module.exports = function authorizeRoles(...role) {
    return async (request, response, next) => {
        // now you can use `await` here
    };
};
like image 89
ThomasThiebaud Avatar answered Sep 06 '26 15:09

ThomasThiebaud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!