Context Storage
Get c without passing it around, with getContext() from @senrijs/senri/context-storage
import { } from "@senrijs/senri";
import { , } from "@senrijs/senri/context-storage";
const = ();
.(()); // before other middleware
// get the c of the request being handled without passing it (even after await)
function () {
return ()...("x-user");
}
.("/me", () => () ?? "anonymous");It uses AsyncLocalStorage (node:async_hooks).
Where it works
- In middleware after
contextStorage(), handlers,onError,app.notFoundand streams - In middleware before
contextStorage()and outside requests (at startup and so on),getContext()throws (code: "no_context") andtryGetContext()returnsundefined
Timers started in a handler still see that request's c after the response (a property of AsyncLocalStorage). Do not keep using it there.
Runtimes
| Runtime | Works |
|---|---|
| Bun, Deno, Node.js | As is |
| Cloudflare Workers | Add the nodejs_als (or nodejs_compat) compatibility flag to the wrangler config |
| Browser (Service Worker) | No (there is no node:async_hooks). Pass c as an argument |
On Workers with an old compatibility date and no flag, the Worker fails to start with No such module "node:async_hooks". If you bundle without wrangler, leave node:* imports unbundled.
{
"compatibility_flags": ["nodejs_als"]
}