Skip to main content

@nest-boot/request-context

Classes

RequestContext

Defined in: request-context.ts:83

RequestContext provides a way to store and access request-scoped data throughout the lifecycle of a request using AsyncLocalStorage.

This is useful for storing data like the current user, request ID, database transactions, and other request-specific information that needs to be accessed across different parts of the application.

Examples

import { RequestContext } from '@nest-boot/request-context';

// Get the current request ID
const requestId = RequestContext.id;

// Store a value in the context
RequestContext.set('userId', 123);

// Retrieve a value from the context
const userId = RequestContext.get<number>('userId');
await RequestContext.run(
new RequestContext({ type: 'job' }),
async (ctx) => {
ctx.set('jobId', 'abc123');
await processJob();
}
);
await RequestContext.child(async (childCtx) => {
// Child context inherits values from parent
// but can have its own values that don't affect parent
childCtx.set('tempValue', 'only in child');
});

Constructors

Constructor
new RequestContext(options): RequestContext;

Defined in: request-context.ts:132

Creates a new RequestContext instance.

Parameters
ParameterTypeDescription
optionsRequestContextCreateOptionsConfiguration options for the context
Returns

RequestContext

Example
const ctx = new RequestContext({
id: 'custom-id',
type: 'http',
});

Properties

id
readonly id: string;

Defined in: request-context.ts:88

Unique identifier for this request context. Automatically generated as a UUID if not provided.

parent?
readonly optional parent: RequestContext;

Defined in: request-context.ts:99

Parent context, if this is a child context. Values not found in this context will be looked up in the parent.

type
readonly type: string;

Defined in: request-context.ts:93

The type of this context (e.g., 'http', 'graphql', 'repl', 'job').

Accessors

id
Get Signature
get static id(): string;

Defined in: request-context.ts:277

Gets the ID of the current request context.

Throws

Error if no request context is active

Example
console.log(`Processing request ${RequestContext.id}`);
Returns

string

The unique identifier of the current context

Methods

get()
get<T>(token): T | undefined;

Defined in: request-context.ts:154

Gets a value from the context by its token. If not found in this context, looks up the parent context.

Type Parameters
Type ParameterDescription
TThe expected type of the value
Parameters
ParameterTypeDescription
tokenstring | symbol | Function | Type<T>The key to look up (string, symbol, function, or class)
Returns

T | undefined

The value if found, otherwise undefined

Example
const ctx = RequestContext.current();
const user = ctx.get<User>('currentUser');
const service = ctx.get(MyService);
getOrSet()
getOrSet<T>(typeOrToken, value): T;

Defined in: request-context.ts:190

Gets a value from the context, or sets it if not present.

Type Parameters
Type ParameterDescription
TThe type of the value
Parameters
ParameterTypeDescription
typeOrTokenstring | symbol | Type<T>The key to look up or store under
valueTThe value to set if not already present
Returns

T

The existing value or the newly set value

Example
const ctx = RequestContext.current();
const cache = ctx.getOrSet('cache', new Map());
set()
set<T>(typeOrToken, value): void;

Defined in: request-context.ts:172

Sets a value in the context.

Type Parameters
Type ParameterDescription
TThe type of the value
Parameters
ParameterTypeDescription
typeOrTokenstring | symbol | Type<T>The key to store the value under
valueTThe value to store
Returns

void

Example
const ctx = RequestContext.current();
ctx.set('userId', 123);
ctx.set(UserService, userServiceInstance);
child()
static child<T>(callback): Promise<T>;

Defined in: request-context.ts:382

Creates and runs a child context that inherits from the current context. Child contexts can read values from parent contexts but modifications are isolated to the child.

Type Parameters
Type ParameterDescription
TThe return type of the callback
Parameters
ParameterTypeDescription
callback(ctx) => T | Promise<T>The function to execute within the child context
Returns

Promise<T>

A promise resolving to the callback's return value

Throws

Error if no request context is active

Example
// In parent context
RequestContext.set('userId', 123);

await RequestContext.child(async (childCtx) => {
// Can read parent values
const userId = childCtx.get('userId'); // 123

// Child-only values don't affect parent
childCtx.set('tempData', 'child only');
});

// Parent context unchanged
RequestContext.get('tempData'); // undefined
current()
static current(): RequestContext;

Defined in: request-context.ts:293

Gets the current request context.

Returns

RequestContext

The current RequestContext instance

Throws

Error if no request context is active

Example
const ctx = RequestContext.current();
console.log(ctx.type); // 'http'
get()
static get<T>(key): T | undefined;

Defined in: request-context.ts:217

Gets a value from the current context by its key. Static method that accesses the current context automatically.

Type Parameters
Type ParameterDescription
TThe expected type of the value
Parameters
ParameterTypeDescription
keystring | symbol | Function | Type<T>The key to look up
Returns

T | undefined

The value if found, otherwise undefined

Throws

Error if no request context is active

Example
const userId = RequestContext.get<number>('userId');
getOrSet()
static getOrSet<T>(key, value): T;

Defined in: request-context.ts:260

Gets a value from the current context, or sets it if not present. Static method that accesses the current context automatically.

Type Parameters
Type ParameterDescription
TThe type of the value
Parameters
ParameterTypeDescription
keystring | symbol | Type<T>The key to look up or store under
valueTThe value to set if not already present
Returns

T

The existing value or the newly set value

Throws

Error if no request context is active

Example
const cache = RequestContext.getOrSet('cache', new Map());
isActive()
static isActive(): boolean;

Defined in: request-context.ts:315

Checks if a request context is currently active.

Returns

boolean

true if a context is active, false otherwise

Example
if (RequestContext.isActive()) {
const userId = RequestContext.get('userId');
}
registerMiddleware()
static registerMiddleware(
name,
middleware,
dependencies?): void;

Defined in: request-context.ts:430

Registers a middleware to be executed when running a request context. Middlewares are executed in dependency order.

Parameters
ParameterTypeDescription
namestringUnique name for the middleware
middlewareRequestContextMiddlewareThe middleware function to register
dependencies?string[]Names of middlewares that must run before this one
Returns

void

Example
RequestContext.registerMiddleware(
'auth',
async (ctx, next) => {
ctx.set('user', await loadUser());
return next();
}
);

// Middleware with dependencies
RequestContext.registerMiddleware(
'permissions',
async (ctx, next) => {
const user = ctx.get('user');
ctx.set('permissions', await loadPermissions(user));
return next();
},
['auth'] // Runs after 'auth' middleware
);
run()
static run<T>(ctx, callback): Promise<T>;

Defined in: request-context.ts:339

Runs a callback within a request context. All registered middlewares are executed before the callback.

Type Parameters
Type ParameterDescription
TThe return type of the callback
Parameters
ParameterTypeDescription
ctxRequestContextThe request context to run within
callback(ctx) => T | Promise<T>The function to execute within the context
Returns

Promise<T>

A promise resolving to the callback's return value

Example
const result = await RequestContext.run(
new RequestContext({ type: 'job' }),
async (ctx) => {
ctx.set('jobId', 'abc123');
return await processJob();
}
);
set()
static set<T>(key, value): void;

Defined in: request-context.ts:237

Sets a value in the current context. Static method that accesses the current context automatically.

Type Parameters
Type ParameterDescription
TThe type of the value
Parameters
ParameterTypeDescription
keystring | symbol | Type<T>The key to store the value under
valueTThe value to store
Returns

void

Throws

Error if no request context is active

Example
RequestContext.set('userId', 123);

RequestContextInterceptor

Defined in: request-context.interceptor.ts:35

NestJS interceptor that creates request context for HTTP and GraphQL requests.

This interceptor serves as a fallback for cases where the middleware doesn't run (e.g., GraphQL resolvers). It:

  • Creates a new RequestContext if one doesn't already exist
  • Uses the x-request-id header as the context ID if provided
  • Supports both HTTP and GraphQL execution contexts

The interceptor is automatically registered by RequestContextModule.

Example

The interceptor is typically used automatically, but can be applied manually:

import { Controller, UseInterceptors } from '@nestjs/common';
import { RequestContextInterceptor } from '@nest-boot/request-context';

@Controller()
@UseInterceptors(RequestContextInterceptor)
export class MyController {}

Implements

  • NestInterceptor

Constructors

Constructor
new RequestContextInterceptor(): RequestContextInterceptor;
Returns

RequestContextInterceptor

Methods

intercept()
intercept<T>(executionContext, next): Observable<T>;

Defined in: request-context.interceptor.ts:44

Intercepts the request and wraps execution in a request context.

Type Parameters
Type ParameterDescription
TThe type of the response
Parameters
ParameterTypeDescription
executionContextExecutionContextThe NestJS execution context
nextCallHandler<T>The call handler for the next interceptor or handler
Returns

Observable<T>

An observable of the response

Implementation of
NestInterceptor.intercept

RequestContextMiddleware

Defined in: request-context.middleware.ts:31

Express middleware that creates and manages request context for HTTP requests.

This middleware:

  • Creates a new RequestContext for each incoming HTTP request
  • Uses the x-request-id header as the context ID if provided
  • Stores the Express request and response objects in the context
  • Maintains the context throughout the request lifecycle

The middleware is automatically applied by RequestContextModule to all routes.

Example

import { RequestContext, REQUEST, RESPONSE } from '@nest-boot/request-context';
import { Request, Response } from 'express';

const req = RequestContext.get<Request>(REQUEST);
const res = RequestContext.get<Response>(RESPONSE);

Implements

  • NestMiddleware

Constructors

Constructor
new RequestContextMiddleware(): RequestContextMiddleware;
Returns

RequestContextMiddleware

Methods

use()
use(
req,
res,
next): Promise<void>;

Defined in: request-context.middleware.ts:39

Processes an incoming HTTP request and establishes request context.

Parameters
ParameterTypeDescription
reqRequestThe Express request object
resResponseThe Express response object
nextNextFunctionThe next middleware function
Returns

Promise<void>

Implementation of
NestMiddleware.use

RequestContextModule

Defined in: request-context.module.ts:56

NestJS module that provides request context functionality.

This module automatically sets up request context for HTTP requests using both middleware (for Express) and interceptor (for GraphQL). It stores the request and response objects in the context and makes them available throughout the request lifecycle.

The module is global, so it only needs to be imported once in the root module.

Examples

import { Module } from '@nestjs/common';
import { RequestContextModule } from '@nest-boot/request-context';

@Module({
imports: [RequestContextModule],
})
export class AppModule {}
import { Injectable } from '@nestjs/common';
import { RequestContext, REQUEST } from '@nest-boot/request-context';
import { Request } from 'express';

@Injectable()
export class MyService {
getCurrentUser() {
const req = RequestContext.get<Request>(REQUEST);
return req?.user;
}
}

Interfaces

RequestContextCreateOptions

Defined in: request-context.ts:22

Options for creating a new RequestContext instance.

Properties

id?
optional id: string;

Defined in: request-context.ts:27

Unique identifier for the request context. If not provided, a random UUID will be generated.

parent?
optional parent: RequestContext;

Defined in: request-context.ts:38

Parent context for creating nested/child contexts. Child contexts can access values from parent contexts.

type
type: string;

Defined in: request-context.ts:32

The type of context (e.g., 'http', 'graphql', 'repl', 'job').

Variables

REQUEST

const REQUEST: "REQUEST" = "REQUEST";

Defined in: request-context.constants.ts:12

Token for storing the HTTP request object in the request context.

Example

import { REQUEST } from '@nest-boot/request-context';
import { Request } from 'express';

const req = RequestContext.get<Request>(REQUEST);

RESPONSE

const RESPONSE: "RESPONSE" = "RESPONSE";

Defined in: request-context.constants.ts:25

Token for storing the HTTP response object in the request context.

Example

import { RESPONSE } from '@nest-boot/request-context';
import { Response } from 'express';

const res = RequestContext.get<Response>(RESPONSE);

Functions

CreateRequestContext()

function CreateRequestContext<T, P>(fn): (_target, _propertyKey, descriptor) => PropertyDescriptor;

Defined in: create-request-context.decorator.ts:64

Method decorator that wraps the method execution in a new request context.

This is useful for creating request contexts for background jobs, event handlers, or any other code that runs outside of HTTP request handling.

Type Parameters

Type ParameterDescription
T extends objectThe class type containing the method
P extends string | number | symbolThe property key of the method

Parameters

ParameterTypeDescription
fn(instance, ...args) => RequestContextA function that creates the RequestContext, receiving the class instance and method arguments

Returns

A method decorator

(
_target,
_propertyKey,
descriptor): PropertyDescriptor;
Parameters
ParameterType
_targetT
_propertyKeyP
descriptorPropertyDescriptor
Returns

PropertyDescriptor

Examples

import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';

class JobProcessor {
@CreateRequestContext((instance, jobData) =>
new RequestContext({ type: 'job', id: jobData.id })
)
async processJob(jobData: { id: string; payload: any }) {
// This code runs within a request context
console.log(`Processing job ${RequestContext.id}`);
// ...
}
}
import { Injectable } from '@nestjs/common';
import { CreateRequestContext, RequestContext } from '@nest-boot/request-context';

@Injectable()
class EventHandler {
@CreateRequestContext((instance, event) =>
new RequestContext({
type: 'event',
id: event.correlationId,
})
)
async handleEvent(event: { correlationId: string; data: any }) {
// Access context within the handler
RequestContext.set('eventType', event.data.type);
await this.processEvent(event);
}

private async processEvent(event: any) {
// Context is still available here
const eventType = RequestContext.get('eventType');
}
}

repl()

function repl(module): Promise<REPLServer>;

Defined in: repl.ts:56

Starts a REPL (Read-Eval-Print Loop) session with request context support.

This function creates a NestJS application context and starts an interactive REPL session where all commands run within a request context. This is useful for debugging and testing services that depend on request context.

The REPL session:

  • Runs within a request context of type 'repl'
  • Has access to all NestJS providers
  • Maintains context across async operations

Parameters

ParameterTypeDescription
moduleType<any> | DynamicModuleThe NestJS module (class or DynamicModule) to create the context from

Returns

Promise<REPLServer>

A promise that resolves to the REPL server instance

Examples

// repl.ts
import { repl } from '@nest-boot/request-context';
import { AppModule } from './app.module';

async function bootstrap() {
await repl(AppModule);
}

bootstrap();
npx ts-node -r tsconfig-paths/register repl.ts
// In the REPL session:
> const userService = get(UserService)
> await userService.findAll()
> RequestContext.id // Access current context ID