npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@fastify/request-context

v5.1.0

Published

Request-scoped storage support, based on Asynchronous Local Storage, with fallback to cls-hooked for older Node versions

Downloads

366,048

Readme

@fastify/request-context

NPM Version NPM Downloads Build Status Coverage Status

Request-scoped storage support, based on Asynchronous Local Storage (which uses native Node.js ALS with fallback to cls-hooked for older Node.js versions)

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 won't 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.

Getting started

First install the package:

npm i @fastify/request-context

Next, set up the plugin:

const { fastifyRequestContextPlugin } = require('@fastify/request-context')
const fastify = require('fastify');

fastify.register(fastifyRequestContextPlugin);

Or customize hook and default store values:

const { fastifyRequestContextPlugin } = require('@fastify/request-context')
const fastify = require('fastify');

fastify.register(fastifyRequestContextPlugin, { 
  hook: 'preValidation',
  defaultStoreValues: {
    user: { id: 'system' } 
  }
});

Default store values can be set through a function as well:

const { fastifyRequestContextPlugin } = require('@fastify/request-context')
const fastify = require('fastify');

fastify.register(fastifyRequestContextPlugin, {
  defaultStoreValues: request => ({
    log: request.log.child({ foo: 123 })
  })
});

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:

const { fastifyRequestContextPlugin, requestContext } = require('@fastify/request-context')
const fastify = require('fastify');

const app = fastify({ logger: true })
app.register(fastifyRequestContextPlugin, { 
  defaultStoreValues: {
    user: { id: 'system' } 
  },
  createAsyncResource: (req, context) => new MyCustomAsyncResource('custom-resource-type', req.id, context.user.id)
});

app.addHook('onRequest', (req, reply, done) => {
  // Overwrite the defaults.
  // This is completely equivalent to using app.requestContext or just requestContext 
  req.requestContext.set('user', { id: 'helloUser' });
  done();
});

// this should now get `helloUser` instead of the default `system`
app.get('/', (req, reply) => {
  // requestContext singleton exposed by the library retains same request-scoped values that were set using `req.requestContext`
  const user = requestContext.get('user');
  reply.code(200).send( { user });
});

app.get('/decorator', function (req, reply) {
  // requestContext singleton exposed as decorator in the fastify instance and can be retrieved:
  const user = this.requestContext.get('user'); // using `this` thanks to the handler function binding
  const theSameUser = app.requestContext.get('user'); // directly using the `app` instance
  reply.code(200).send( { user });
});

app.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  app.log.info(`server listening on ${address}`)
});

return app.ready()

TypeScript

In TypeScript you are expected to augment the module to type your context:

import {requestContext} from '@fastify/request-context'

declare module '@fastify/request-context' {
  interface RequestContextData {
    foo: string
  }
}

// Type is "string" (if "strictNullChecks: true" in your tsconfig it will be "string | undefined")
const foo = requestContext.get('foo')
// Causes a type violation as 'bar' is not a key on RequestContextData
const 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).