How to access and manage request context
mainThe request context (providing .get(), .set(), and .getStore()) is available in three ways:
- Via the library singleton: Import
requestContextdirectly. This singleton retains the same request-scoped values as the decorators. - Via the request object: Access
req.requestContextwithin handlers or hooks. - Via decorators: Access
fastify.requestContexton the app instance, orthis.requestContextwithin route handlers (when using standard function syntax).
Use .set(key, value) to store data and .get(key) to retrieve it. Use .getStore() to retrieve the entire store object.
const { fastifyRequestContext, requestContext } = require('@fastify/request-context')
const fastify = require('fastify');
const app = fastify();
app.register(fastifyRequestContext);
app.get('/', (req, reply) => {
// 1. Using the library singleton
const user = requestContext.get('user');
// 2. Using the request decorator
const store = req.requestContext.getStore();
// 3. Using the app instance decorator
const appUser = app.requestContext.get('user');
reply.send({ user, store });
});