honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
16.93k stars 470 forks source link

Idea: Use `AsyncLocalStorage` for context #1219

Closed jokull closed 11 months ago

jokull commented 1 year ago

Could be opt in.

https://developers.cloudflare.com/workers/runtime-apis/nodejs/asynclocalstorage/

If the Hono context object would be an AsyncLocalStorage you could retrieve whatever is inside it without passing c around. If you have a function somewhere and you want to, for example, elegantly handle a failure but log the error to Sentry, you would have to pass c potentially very deep down into you stack.

Mahamed-Belkheir commented 11 months ago

Can't you do this with a middleware already?

const ctxStore = new AsyncLocalStorage<Context>();

app.use((ctx, next) => {
   ctxStore.run(ctx, next);
})

or something similar

jokull commented 11 months ago

Let me try. I'll re-open if needed.

banjo commented 11 months ago

Any news on this?

I tried the example but it gave this error:

Error: Context is not finalized. You may forget returning Response object or `await next()`
LorisSigrist commented 3 weeks ago

Also tried it + a few variations and got the same error. Being able to provide a "context" for a request via AsyncLocalStorage would be very useful for using ParaglideJS with Hono.

Can this be reopened?

yusukebe commented 3 weeks ago

Using AsyncLocalStorge is a good idea. You can see the example middleware using it:

https://github.com/yusukebe/async-local-storage-middleware

Either way, we generally do not need it since we have a context.