Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Created November 4, 2025 16:12
Show Gist options
  • Save christophemarois/342e4fd48b97c0d804cfcbd4904a4958 to your computer and use it in GitHub Desktop.
Save christophemarois/342e4fd48b97c0d804cfcbd4904a4958 to your computer and use it in GitHub Desktop.
Context for node/bun
import { AsyncLocalStorage } from "node:async_hooks";
function createCtx<T>(name: string, defaultValue?: T) {
const ctx = new AsyncLocalStorage<T>({ name });
const set = (x: T) => ctx.enterWith(x);
const maybeGet = () => ctx.getStore();
const get = (): T => {
const val = maybeGet();
if (val === undefined) {
throw new Error(`Missing required context value for ${name}`);
}
return val;
};
if (defaultValue !== undefined) {
ctx.enterWith(defaultValue);
}
return { ctx, get, maybeGet, set };
}
type Logger = { info: (msg: string) => unknown };
const logger = createCtx<Logger>("LoggerCtx", {
info(msg) {
console.log(msg);
},
});
logger.get().info("hi1");
logger.ctx.run({
info(msg) {
console.log("inside runner " + msg);
},
}, () => {
logger.get().info("hi2");
});
logger.get().info("hi3");
// Prints out:
// hi1
// inside runner hi2
// hi3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment