{"id":19235655,"url":"https://github.com/paripsky/node-context-storage","last_synced_at":"2026-02-19T01:30:47.525Z","repository":{"id":146383898,"uuid":"617629640","full_name":"paripsky/node-context-storage","owner":"paripsky","description":null,"archived":false,"fork":false,"pushed_at":"2023-03-23T21:51:49.000Z","size":12,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-10-25T12:48:48.318Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/paripsky.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-03-22T19:32:13.000Z","updated_at":"2025-02-13T15:09:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"8135148f-3800-4f58-84e7-1286b046e2db","html_url":"https://github.com/paripsky/node-context-storage","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/paripsky/node-context-storage","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paripsky%2Fnode-context-storage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paripsky%2Fnode-context-storage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paripsky%2Fnode-context-storage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paripsky%2Fnode-context-storage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/paripsky","download_url":"https://codeload.github.com/paripsky/node-context-storage/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/paripsky%2Fnode-context-storage/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29600749,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-19T00:59:38.239Z","status":"ssl_error","status_checked_at":"2026-02-19T00:59:36.936Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-09T16:17:44.134Z","updated_at":"2026-02-19T01:30:47.502Z","avatar_url":"https://github.com/paripsky.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Node Context Storage\n\nA simple utility for managing a context across asynchronous boundaries. It uses\nNode.js's built-in `AsyncLocalStorage` module to allow context to be accessed\nacross multiple async functions without the need to explicitly pass it as a\nparameter.\n\n## Installation\n\nTo install, simply run:\n\nnpm:\n\n```bash\nnpm install node-context-storage\n```\n\npnpm:\n\n```bash\npnpm add node-context-storage\n```\n\n## Usage\n\nThe library exports the function `createContext`, which can be used to create a\nnew context. Here's an example of how you might use it:\n\n```ts\nimport { createContext } from \"node-context-storage\";\n\ntype MyContext = {\n  userId: string;\n  isAdmin: boolean;\n};\n\nconst context = createContext();\n\ncontext.run({ context: { userId: \"123\", isAdmin: true } }, async () =\u003e {\n  // This async function has access to the context\n  console.log(context.get()); // { userId: '123', isAdmin: true }\n\n  await someOtherAsyncFunction();\n\n  console.log(context.get()); // { userId: '123', isAdmin: true }\n});\n```\n\nThe `run` method takes an initial storage object, which can be used to set up\nthe initial state of the context. The `get`, `set`, and `exists` methods can be\nused to access and modify the context within the async function.\n\n## Express Middleware\n\nThe `createContextMiddleware` function is a built-in middleware for Express that\nallows you to automatically set up the context for every request. Here's an\nexample of how you might use it:\n\n```ts\nimport express from \"express\";\nimport { createContext, createContextMiddleware } from \"node-context-storage\";\n\ntype MyContext = {\n  userId: string;\n  isAdmin: boolean;\n};\n\nconst context = createContext();\n\nconst contextMiddleware = createContextMiddleware\u003cContext\u003e(context);\n\nconst app = express();\n\napp.use((req, res, next) =\u003e\n  contextMiddleware({ userId: \"123\", isAdmin: false }, req, res, next)\n);\n\napp.use((req, res, next) =\u003e {\n  context.set({ isAdmin: true });\n});\n\napp.get(\"/api/my-route\", (req, res) =\u003e {\n  // This async function has access to the context\n  console.log(context.get()); // { userId: '123', isAdmin: true }\n\n  // ...\n});\n```\n\nThe `createContextMiddleware` function takes a `ContextAPI` object as an\nargument and returns a custom Express middleware function that accept an initial\nstate for the current context (the express request) as it's first parameter.\nWhich essentialy uses context.run() and calls next() inside it under the hood.\n\nYou can then access the context within your route handlers using the `get`\nmethod of the `ContextAPI` object. Here's an example:\n\n```ts\napp.get(\"/api/my-route\", async (req, res) =\u003e {\n  const userId = req.params.userId;\n\n  // Set the userId in the context\n  context.set({ userId });\n\n  // ...\n\n  // Get the current context\n  const currentContext = context.get();\n\n  // ...\n});\n```\n\nNote that because the context is set up using `AsyncLocalStorage`, the context\nis automatically destroyed when the async function completes, ensuring that\nthere are no memory leaks.\n\n## API\n\n### `createContext(): ContextAPI`\n\nCreates a new context with the specified type parameter. Returns an object with\nthe following methods:\n\n- `getStore(): Storage`: Returns the current storage object for the context.\n  Throws an error if called outside of an async function where the context has\n  not been set up.\n- `get(): Context`: Returns the current context object. Throws an error if\n  called outside of an async function where the context has not been set up.\n- `set(context: Partial): void`: Merges the given partial context object into\n  the current context object.\n- `exists(): boolean`: Returns true if the context has been set up within the\n  current async function, false otherwise.\n- `run(initialStorage: Storage, cb: Function): Promise`: Runs the given async\n  function with the provided initial storage object. The async function will\n  have access to the context via the `get`, `set`, and `exists` methods.\n\n### `ContextAPI`\n\nThe type of the object returned by `createContext`.\n\n```ts\ntype ContextAPI\u003cContext\u003e = {\n  type Storage = {\n    context: Context;\n  };\n\n  getStore(): Storage;\n  get(): Context;\n  set(context: Partial\u003cContext\u003e): void;\n  exists(): boolean;\n  run(initialStorage: Storage, cb: Function): Promise\u003cvoid\u003e;\n};\n```\n\n## License\n\nThis library is released under the\n[MIT License](https://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparipsky%2Fnode-context-storage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparipsky%2Fnode-context-storage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparipsky%2Fnode-context-storage/lists"}