Gathering detailed insights and metrics for @fastify/request-context
Gathering detailed insights and metrics for @fastify/request-context
Gathering detailed insights and metrics for @fastify/request-context
Gathering detailed insights and metrics for @fastify/request-context
fastify-request-context
`fastify-request-context@2.3.0` has been deprecated. Please use `@fastify/request-context@3.0.0` instead.
@lokalise/fastify-extras
Opinionated set of fastify plugins, commonly used in Lokalise
@universal-middleware/fastify
fastify adapter for universal middlewares
@lokalise/context-fastify-plugins
This library exposes several fastify plugins that rely on @fastify/request-context (ALS) to work.
Request-scoped storage support, based on Asynchronous Local Storage (with fallback to cls-hooked)
npm install @fastify/request-context
Typescript
Module System
Node Version
NPM Version
JavaScript (95.17%)
TypeScript (4.83%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
NOASSERTION License
184 Stars
241 Commits
20 Forks
16 Watchers
3 Branches
35 Contributors
Updated on Jul 01, 2025
Latest Version
6.2.0
Package Id
@fastify/request-context@6.2.0
Unpacked Size
14.14 kB
Size
5.10 kB
File Count
5
NPM Version
10.9.0
Node Version
22.12.0
Published on
Apr 22, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
Request-scoped storage support, based on AsyncLocalStorage.
Inspired by work done in fastify-http-context.
This 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 nor will variables remain available once a request is completed.
Frequent use-cases are persisting request-aware logger instances and user authorization information.
npm i @fastify/request-context
Plugin version | Fastify version |
---|---|
>=6.x | ^5.x |
>=4.x <6.x | ^4.x |
>=2.x <4.x | ^3.x |
^1.x | ^2.x |
^1.x | ^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin in the table above. See Fastify's LTS policy for more details.
Set up the plugin:
1const { fastifyRequestContext } = require('@fastify/request-context') 2const fastify = require('fastify'); 3 4fastify.register(fastifyRequestContext);
Or customize hook and default store values:
1const { fastifyRequestContext } = require('@fastify/request-context') 2const fastify = require('fastify'); 3 4fastify.register(fastifyRequestContext, { 5 hook: 'preValidation', 6 defaultStoreValues: { 7 user: { id: 'system' } 8 } 9});
Default store values can be set through a function as well:
1const { fastifyRequestContext } = require('@fastify/request-context') 2const fastify = require('fastify'); 3 4fastify.register(fastifyRequestContext, { 5 defaultStoreValues: request => ({ 6 log: request.log.child({ foo: 123 }) 7 }) 8});
This plugin accepts options hook
and defaultStoreValues
, createAsyncResource
.
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
.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.createAsyncResource
can specify a factory function that creates an extended AsyncResource
object.From there you can set a context in another hook, route, or method that is within scope.
Request 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.
For instance:
1const { fastifyRequestContext, requestContext } = require('@fastify/request-context') 2const fastify = require('fastify'); 3 4const app = fastify({ logger: true }) 5app.register(fastifyRequestContext, { 6 defaultStoreValues: { 7 user: { id: 'system' } 8 }, 9 createAsyncResource: (req, context) => new MyCustomAsyncResource('custom-resource-type', req.id, context.user.id) 10}); 11 12app.addHook('onRequest', (req, reply, done) => { 13 // Overwrite the defaults. 14 // This is completely equivalent to using app.requestContext or just requestContext 15 req.requestContext.set('user', { id: 'helloUser' }); 16 done(); 17}); 18 19// this should now get `helloUser` instead of the default `system` 20app.get('/', (req, reply) => { 21 // requestContext singleton exposed by the library retains same request-scoped values that were set using `req.requestContext` 22 const user = requestContext.get('user'); 23 24 // read the whole store 25 const store = req.requestContext.getStore(); 26 reply.code(200).send( { store }); 27}); 28 29app.get('/decorator', function (req, reply) { 30 // requestContext singleton exposed as decorator in the fastify instance and can be retrieved: 31 const user = this.requestContext.get('user'); // using `this` thanks to the handler function binding 32 const theSameUser = app.requestContext.get('user'); // directly using the `app` instance 33 reply.code(200).send( { user }); 34}); 35 36app.listen({ port: 3000 }, (err, address) => { 37 if (err) throw err 38 app.log.info(`server listening on ${address}`) 39}); 40 41return app.ready()
In TypeScript you are expected to augment the module to type your context:
1import {requestContext} from '@fastify/request-context' 2 3declare module '@fastify/request-context' { 4 interface RequestContextData { 5 foo: string 6 } 7} 8 9// Type is "string" (if "strictNullChecks: true" in your tsconfig it will be "string | undefined") 10const foo = requestContext.get('foo') 11// Causes a type violation as 'bar' is not a key on RequestContextData 12const bar = requestContext.get('bar')
If 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).
If 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:
import { asyncLocalStorage } from '@fastify/request-context';
it('should set request context', () => {
asyncLocalStorage.run({}, async () => {
requestContext.set('userId', 'some-fake-user-id');
someCodeThatUsesRequestContext(); // requestContext.get('userId') will work
})
})
Licensed under MIT.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
license file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 8
Details
Reason
4 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 4
Reason
Found 6/27 approved changesets -- score normalized to 2
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2025-07-14
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More