markusahlstrand/cloudworker-router

Unable to use middleware

Closed this issue · 6 comments

I'm trying to add authentication middleware to a route, the same way I use it on Express.

    router.get('/e', async (ctx) => {
        ctx.body = 'Hello World2';
        ctx.status = 200;
    }); 

    router.get('/a', userAuthCheck, async (ctx) => {
        ctx.body = 'Hello World2';
        ctx.status = 200;
    });

The userAuthCheck has code that validates a user's credentials and gets their user ID and some other information which I use later in the code. When I include the middleware, I get 404 however without it everything is fine.

Even if I get 404, I can console log in the middleware and see it so clearly the code is being reached.

I was wondering whether I'm doing it wrong or if it's just not supported this way?

Thanks again!

Hi @LeCodeCo,

The middlewares work more similar to koa-router where this syntax (I think...) isn't supported. Instead you define the middleware like this:

    router.get('/e', async (ctx) => {
        ctx.body = 'Hello World2';
        ctx.status = 200;
    }); 

   router.use(userAuthCheck);

    router.get('/a', async (ctx) => {
        ctx.body = 'Hello World2';
        ctx.status = 200;
    });

The routes are executed in the order they are added, so the userAuthCheck will be executed before the /a endpoint.

Does that answer your question?

Maybe we should add an example in the docs with a middleware.. Looks like there isn't one now.

Hey @markusahlstrand

Thanks for getting back to me so shortly again.

I've tried doing the way you've suggested now, and while I can console.log from my middleware, I still strangely get 404 on routes which use the middleware.

# /userAuthCheck.js
function userAuthCheck(ctx) {
    console.log("Test")
    return console.log("Test2")
}

module.exports = {
    userAuthCheck,
};
# /index.js
router.use(userAuthCheck);

router.get('/e', async (ctx) => {
    ctx.body = 'Hello World2';
    ctx.status = 200;
});
Test
Test2
[2020-07-16 17:26:19] GET example.com/e HTTP/1.1 404 Not Found

If I remove router.use(userAuthCheck); here, I see (200) Hello World2, but when I have it all I get back is (404). I'm using wrangler preview and also tried wrangler dev.

How does the middleware look like? The middlewares takes ctx and next as parameters and next needs to be called for the next handler to be invoked.

You can checkout the basic-auth middleware in the cloudworker-proxy (https://github.com/markusahlstrand/cloudworker-proxy/blob/master/src/handlers/basic-auth.js) project that I guess should be pretty similar to what you are doing?

By calling next, I've managed to sort the issue. That example from cloudworker-proxy was very helpful.

Thank you again and please excuse my lack of knowledge on the subject.

Great that it worked out for you. Then I'll go ahead and close this issue :)