hono icon indicating copy to clipboard operation
hono copied to clipboard

What exactly is Context get/set ?

Open dagnelies opened this issue 2 years ago • 2 comments

In the documentation https://honojs.dev/docs/api/context/#csetcget it is only written:

Set the value specified by the key with set and use it later with get.

With a brief example. However, it is not clear what this get/set actually does and how it works. Is it global state? Session based? Something else?

dagnelies avatar Oct 05 '22 15:10 dagnelies

Hey @dagnelies, thanks for opening this issue!

You're right, the documentation is pretty vague on this topic. We are working on a lot of the documentation to make it more descriptive and there's still a lot to get to, but we are happy to receive feedback on what is currently the least clear!

Context here is the context of the current request, and Context.set and Context.get allow you to get and set arbitrary key-value pairs that have a lifetime of the current request, in order to pass particular values between middleware, or pass values from middleware to route handlers.

I'll update the documentation for this soon, and in the meantime we can keep this issue open to track that documentation.

ThatOneBro avatar Oct 05 '22 17:10 ThatOneBro

I am using the context.set to store the authenticated userId, however when multiple requests are hitting the same worker instance, doing a context.get returns me the wrong userId. It looks like it might not be safe to store mutable data using the context according to https://community.cloudflare.com/t/concurrent-requests-unique-data/148919 and https://community.cloudflare.com/t/is-context-per-worker-execution-unique/127762/3. This means that what you stated above:

allow you to get and set arbitrary key-value pairs that have a lifetime of the current request

might actually not be accurate. Cloudflare already reuses the env object across requests if that hasn't changed (see https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#parameters). _vars is a Hono implementation and has private access. Is it possible that Cloudflare reuse of the context instance across requests is causing to return _vars values from a previous request? Edited I am the cause of my own problem. I was using a static class to keep the context which the post I linked above clearly states it's a no go. Please ignore this, context set/get works as expected.

Mexassi avatar Nov 25 '23 02:11 Mexassi