tsndr / cloudflare-worker-router

A super lightweight router (1.0K) with middleware support and ZERO dependencies for Cloudflare Workers.
MIT License
220 stars 30 forks source link

When have global handlers, env seems not work #27

Closed lljxx1 closed 1 year ago

lljxx1 commented 1 year ago

router.use({ req, res, next }) => {
    if (!req.query.api_key) {
        req.body = {
            error: "key missing"
        }
        return;
    }
    next()
});

router.get("/check", async ({ env, req, res }) => {
    console.log(env.KV)
    console.log(await env.KV.get("test"))
})

When remove this, It's worked


//router.use(authMiddleware);

router.get("/check", async ({ env, req, res }) => {
  // worked
   console.log(await env.KV.get("test"))
})
tsndr commented 1 year ago

Are you calling next() in your authMiddleware?

Example:

router.use(({ req, res, next }) => {
    res.headers.set('X-Global-Middlewares', 'true')
    next()
})
tsndr commented 1 year ago

Also in your exammple you need to await env.KV.get("test") since it returns a promise.

lljxx1 commented 1 year ago

Are you calling next() in your authMiddleware?

Example:

router.use(({ req, res, next }) => {
    res.headers.set('X-Global-Middlewares', 'true')
    next()
})

yeah, I did

lljxx1 commented 1 year ago

Also in your exammple you need to await env.KV.get("test") since it returns a promise.

yes. I have used await in my code. sorry for the demo

lljxx1 commented 1 year ago
router.use({ req, res, next }) => {
    if (!req.query.api_key) {
        req.body = {
            error: "key missing"
        }
        return;
    }
    next()
});

router.get("/check", async ({ env, req, res }) => {
    console.log(env.KV)
    console.log(await env.KV.get("test"))
})
lljxx1 commented 1 year ago

env.KV is not undefined. just call get and will return nothing. after a lot of bugging, if I comment router.use part. it will work.

lljxx1 commented 1 year ago

@tsndr hey, have checked this issue by any chance? I still believe there have some problems here

tsndr commented 1 year ago

I'm finalizing v3.0.0 right now, which is a partial rewrite and does things a little differently, should fix this issue.

You can take a look here, if you like, then you can try it out:

npm i -D @tsndr/cloudflare-worker-router@pre