{"id":13724938,"url":"https://github.com/fastify/fastify-request-context","last_synced_at":"2025-05-15T07:02:59.393Z","repository":{"id":37958811,"uuid":"268605977","full_name":"fastify/fastify-request-context","owner":"fastify","description":"Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)","archived":false,"fork":false,"pushed_at":"2025-05-01T16:43:32.000Z","size":238,"stargazers_count":177,"open_issues_count":2,"forks_count":19,"subscribers_count":16,"default_branch":"main","last_synced_at":"2025-05-01T17:49:09.449Z","etag":null,"topics":["async-storage","fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/request-context","language":"JavaScript","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/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2020-06-01T18:52:12.000Z","updated_at":"2025-05-01T16:43:29.000Z","dependencies_parsed_at":"2023-10-01T18:54:54.981Z","dependency_job_id":"ee5de47f-38b3-4f75-88fb-ddf13d6f01ff","html_url":"https://github.com/fastify/fastify-request-context","commit_stats":{"total_commits":211,"total_committers":19,"mean_commits":"11.105263157894736","dds":0.5260663507109005,"last_synced_commit":"0d99c6fbfa0183900037802f4ce5acb7ec2c4ca5"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-request-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-request-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-request-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-request-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-request-context/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254291961,"owners_count":22046424,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["async-storage","fastify","fastify-plugin"],"created_at":"2024-08-03T01:02:07.426Z","updated_at":"2025-05-15T07:02:59.387Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/request-context\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![CI](https://github.com/fastify/fastify-request-context/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-request-context/actions/workflows/ci.yml)\n\nRequest-scoped storage support, based on [AsyncLocalStorage](https://nodejs.org/api/async_context.html#asynchronous-context-tracking).\n\nInspired by work done in [fastify-http-context](https://github.com/thorough-developer/fastify-http-context).\n\nThis plugin introduces thread-local request-scoped HTTP context, where any variables set within the scope of a single HTTP call will not be overwritten by simultaneous calls to the API\nnor will variables remain available once a request is completed.\n\nFrequent use-cases are persisting request-aware logger instances and user authorization information.\n\n\n\n## Install\n```\nnpm i @fastify/request-context\n```\n\n### Compatibility\n| Plugin version | Fastify version |\n| ---------------|-----------------|\n| `\u003e=6.x`        | `^5.x`          |\n| `\u003e=4.x \u003c6.x`   | `^4.x`          |\n| `\u003e=2.x \u003c4.x`   | `^3.x`          |\n| `^1.x`         | `^2.x`          |\n| `^1.x`         | `^1.x`          |\n\n\nPlease note that if a Fastify version is out of support, then so are the corresponding versions of this plugin\nin the table above.\nSee [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.\n\n## Getting started\n\nSet up the plugin:\n\n```js\nconst { fastifyRequestContext } = require('@fastify/request-context')\nconst fastify = require('fastify');\n\nfastify.register(fastifyRequestContext);\n```\n\nOr customize hook and default store values:\n\n```js\nconst { fastifyRequestContext } = require('@fastify/request-context')\nconst fastify = require('fastify');\n\nfastify.register(fastifyRequestContext, {\n  hook: 'preValidation',\n  defaultStoreValues: {\n    user: { id: 'system' }\n  }\n});\n```\n\nDefault store values can be set through a function as well:\n\n```js\nconst { fastifyRequestContext } = require('@fastify/request-context')\nconst fastify = require('fastify');\n\nfastify.register(fastifyRequestContext, {\n  defaultStoreValues: request =\u003e ({\n    log: request.log.child({ foo: 123 })\n  })\n});\n```\n\nThis plugin accepts options `hook` and `defaultStoreValues`, `createAsyncResource`.\n\n* `hook` allows you to specify to which lifecycle hook should request context initialization be bound. Note that you need to initialize it on the earliest lifecycle stage that you intend to use it in, or earlier. Default value is `onRequest`.\n* `defaultStoreValues` / `defaultStoreValues(req: FastifyRequest)` sets initial values for the store (that can be later overwritten during request execution if needed). Can be set to either an object or a function that returns an object. The function will be sent the request object for the new context. This is an optional parameter.\n* `createAsyncResource` can specify a factory function that creates an extended `AsyncResource` object.\n\nFrom there you can set a context in another hook, route, or method that is within scope.\n\nRequest context (with methods `get` and `set`) is exposed by library itself, but is also available as decorator on `fastify.requestContext` app instance as well as on `req` request instance.\n\nFor instance:\n\n```js\nconst { fastifyRequestContext, requestContext } = require('@fastify/request-context')\nconst fastify = require('fastify');\n\nconst app = fastify({ logger: true })\napp.register(fastifyRequestContext, {\n  defaultStoreValues: {\n    user: { id: 'system' }\n  },\n  createAsyncResource: (req, context) =\u003e new MyCustomAsyncResource('custom-resource-type', req.id, context.user.id)\n});\n\napp.addHook('onRequest', (req, reply, done) =\u003e {\n  // Overwrite the defaults.\n  // This is completely equivalent to using app.requestContext or just requestContext\n  req.requestContext.set('user', { id: 'helloUser' });\n  done();\n});\n\n// this should now get `helloUser` instead of the default `system`\napp.get('/', (req, reply) =\u003e {\n  // requestContext singleton exposed by the library retains same request-scoped values that were set using `req.requestContext`\n  const user = requestContext.get('user');\n\n  // read the whole store\n  const store = req.requestContext.getStore();\n  reply.code(200).send( { store });\n});\n\napp.get('/decorator', function (req, reply) {\n  // requestContext singleton exposed as decorator in the fastify instance and can be retrieved:\n  const user = this.requestContext.get('user'); // using `this` thanks to the handler function binding\n  const theSameUser = app.requestContext.get('user'); // directly using the `app` instance\n  reply.code(200).send( { user });\n});\n\napp.listen({ port: 3000 }, (err, address) =\u003e {\n  if (err) throw err\n  app.log.info(`server listening on ${address}`)\n});\n\nreturn app.ready()\n```\n\n## TypeScript\n\nIn TypeScript you are expected to augment the module to type your context:\n\n```ts\nimport {requestContext} from '@fastify/request-context'\n\ndeclare module '@fastify/request-context' {\n  interface RequestContextData {\n    foo: string\n  }\n}\n\n// Type is \"string\" (if \"strictNullChecks: true\" in your tsconfig it will be \"string | undefined\")\nconst foo = requestContext.get('foo')\n// Causes a type violation as 'bar' is not a key on RequestContextData\nconst bar = requestContext.get('bar')\n```\n\nIf you have `\"strictNullChecks\": true` (or have `\"strict\": true`, which sets `\"strictNullChecks\": true`) in your TypeScript configuration, you will notice that the type of the returned value can still be `undefined` even though the `RequestContextData` interface has a specific type. For a discussion about how to work around this and the pros/cons of doing so, please read [this issue (#93)](https://github.com/fastify/fastify-request-context/issues/93).\n\n## Usage outside of a request\n\nIf functions depend on requestContext but are not called in a request, i.e. in tests or workers, they can be wrapped in the asyncLocalStorage instance of requestContext:\n\n```\nimport { asyncLocalStorage } from '@fastify/request-context';\n\nit('should set request context', () =\u003e {\n  asyncLocalStorage.run({}, async () =\u003e {\n    requestContext.set('userId', 'some-fake-user-id');\n    someCodeThatUsesRequestContext(); // requestContext.get('userId') will work\n  })\n})\n```\n\n## License\n\nLicensed under [MIT](./LICENSE).\n\n[npm-image]: https://img.shields.io/npm/v/@fastify/request-context.svg\n[npm-url]: https://npmjs.com/package/@fastify/request-context\n[downloads-image]: https://img.shields.io/npm/dm/fastify-request-context.svg\n[downloads-url]: https://npmjs.org/package/@fastify/request-context\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-request-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-request-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-request-context/lists"}