0-deps async context management for Node.js
- Zero dependencies
- Lightweight wrappers around AsyncLocalStorage
- Full TypeScript support
- Works in CommonJS and ES Module environments
Using yarn:
yarn add conode
Using npm:
yarn add conode
Quick start
import { createContext } from 'conode';
interface RequestContext { userId: string }
const reqCtx = createContext<RequestContext>();
async function handleRequest() {
console.log(reqCtx.getContext()?.userId);
}
await reqCtx.contextualize({ userId: 'abc123' }, handleRequest);
// Logs: 'abc123'
Functional approach
import { createContext } from '../index';
const auth = createContext();
const action = () => {
const jwt = auth.getContext();
console.log(jwt);
};
auth.contextualize(jwt, action);
Class approach with decorator
import { contextualize, Contextable } from '../index';
const action = () => {
const service = Service.getContext();
console.log(service.getSomething());
};
class Service extends Contextable() {
@contextualize
async run() {
await action();
}
getSomething() {
return 'something';
}
}
const service = new Service();
service.run();
License Apache-2.0 Copyright (c) 2022-present Ivan Zakharchanka