What is request context in NestJS and why do you need it?
Request context is the data that belongs to one incoming request and that code far from the controller needs to read. Typical examples are a correlation ID for log lines, the authenticated principal, the tenant identifier, the user's locale, and the active database transaction. A repository method three calls deep may need the tenant ID to scope a query. A logger inside a utility function may need the correlation ID. Passing these values as arguments through every layer, known as parameter drilling, clutters signatures and breaks whenever a new field is added.
Backend and platform engineers usually hit this problem when they build cross-cutting infrastructure such as structured logging, authorization checks, multi-tenant data isolation, or a unit-of-work transaction pattern. NestJS offers two ways to make this data available implicitly:
- Request-scoped providers tie context to the dependency injection container. Nest creates a new provider instance for each request, along with every provider that depends on it.
- AsyncLocalStorage (ALS) ties context to the async execution chain. Providers stay singletons, and a store follows the request through promises and callbacks.
Request-scoped DI AsyncLocalStorage
----------------- -----------------
HTTP req ──► Middleware als.run(store, next)
│ │
Guard │ store: { reqId,
│ │ user,
Controller ◄── new instance/req │ tenant,
│ │ tx }
ServiceA ◄── new instance/req (singleton)│◄── reads store
│ │
ServiceB ◄── new instance/req (singleton)│◄── reads store
│ │
Repository ◄── new instance/req (singleton)└◄── reads store
REQUEST-SCOPED PROVIDERS ASYNCLOCALSTORAGE
(lifetime = DI container) (lifetime = async chain)
HTTP req HTTP req
│ │
┌─▼──────────┐ ┌─▼──────────┐
│ Middleware │ singleton │ Middleware │──run()──┐
└─┬──────────┘ └─┬──────────┘ ┌─────▼──────┐
┌─▼──────────┐ ┌─▼──────────┐ │ ALS store │
│ Guard │ singleton │ Guard │──►│ ────────── │
└─┬──────────┘ └─┬──────────┘ │ reqId │
┌─▼──────────┐ ┌─▼──────────┐ │ user │
│ Controller │◄─ new per req │ Controller │──►│ tenant │
└─┬──────────┘ └─┬──────────┘ │ locale │
┌─▼──────────┐ ┌─▼──────────┐ │ tx │
│ ServiceA │◄─ new per req │ ServiceA │──►│ │
└─┬──────────┘ └─┬──────────┘ │ one object │
┌─▼──────────┐ ┌─▼──────────┐ │ per async │
│ Repository │◄─ new per req │ Repository │──►│ chain │
└─┬──────────┘ └─┬──────────┘ │ │
┌─▼──────────┐ ┌─▼──────────┐ │ getStore() │
│ CtxService │◄─ Scope.REQUEST │ CtxService │──►│ │
└────────────┘ └────────────┘ └────────────┘
re-created per request; scope providers stay singletons;
bubbles up to every dependent context follows the awaits
The same request handled two ways: on the left, a Scope.REQUEST provider makes Nest re-create every dependent in the chain for each request, while on the right every component stays a singleton and reads one ALS store that als.run() attaches to the request's async execution chain.
Who should use AsyncLocalStorage or request-scoped providers?
This comparison is aimed at engineers who build or maintain shared infrastructure in a NestJS codebase:
- Backend engineers on multi-tenant services who need the tenant ID in repositories, caches and outbound clients without adding a
tenantIdparameter to every method. - Platform and observability engineers who want every log line, metric label and audit record to carry a correlation ID, including log lines emitted from code that has no access to the request.
- Teams implementing a unit-of-work or transaction-per-request pattern who need repositories to pick up the active transaction implicitly.
- Teams whose services run outside HTTP, such as queue consumers, scheduled jobs and microservice handlers, and who want the same service code to work in every entry point.
- Teams that already use
Scope.REQUESTand are seeing unexpected scope bubbling, problems with gateways or Passport strategies, or per-request construction cost they did not plan for.
If your application is small, has few layers, and only the controller needs request data, you may not need either mechanism. Explicit parameters or custom parameter decorators, covered under alternatives at the end, may be enough.
How does it work? The two mechanisms in brief
The two approaches solve the same problem at different layers of the stack.
Request-scoped providers work inside Nest's injector. For each incoming request, Nest creates a context ID. When it resolves a request-scoped provider, it looks up or builds an instance keyed by that context ID, and it does the same for every provider that depends on it. The result is a per-request sub-tree of instances. When the request finishes, nothing references that sub-tree any more and it is garbage collected. The context lives in the objects: each instance holds the request or values derived from it.
AsyncLocalStorage works inside the Node.js runtime. When you call als.run(store, callback), Node makes store the current value for that execution. When code inside the callback creates an async continuation, such as a promise reaction, a timer or an I/O callback, Node records the current store with it and restores it when the continuation runs. getStore() reads whatever value is current. The internal implementation has changed across Node releases, but the public contract of run() and getStore() is the same. The context lives in the execution chain. Objects stay shared, and each request's chain carries its own store.
The practical consequences follow from where the context lives. Injector-based context only exists where Nest creates a context ID, which is normally the HTTP request lifecycle. Runtime-based context exists wherever you call run(), which can be any entry point. The sections below cover each mechanism in detail.
How do request-scoped providers work, and what do they cost?
With @Injectable({ scope: Scope.REQUEST }), Nest creates a fresh instance of the provider for every incoming request and discards it when the request completes. Injecting the REQUEST token from @nestjs/core has the same effect: a provider that needs the request object cannot be a singleton, so Nest makes it request-scoped.
Scope also moves up the injection chain. If TenantService is request-scoped, any provider that injects it must also be rebuilt per request, because a singleton cannot hold a reference to an object that changes every request. OrdersService injects TenantService and declares no scope, yet it becomes request-scoped. So does OrdersController, which injects OrdersService. The default looks like a singleton, and nothing at compile time or startup warns you about the change. One scoped dependency deep in the graph can make most of a feature module run per-request construction.
The costs follow from that:
- Allocation and GC. Every scoped provider and every dependent is constructed on each request and later collected. Constructors that do real work, such as building clients or parsing config, repeat that work on the hot path.
- No request outside HTTP. Cron jobs, queue consumers and bootstrap code have no inbound HTTP request. Microservice handlers do not receive the HTTP request object either. Anything that injects
REQUESTgets nothing useful there unless you construct a context yourself. - Components that must be singletons. WebSocket gateways and Passport strategies cannot depend on request-scoped providers.
- Third-party integrations. Libraries that cache provider instances, register listeners at startup, or assume a singleton lifecycle can fail or behave inconsistently when one of their dependencies is scoped.
import { Controller, Get, Inject, Injectable, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
// Explicitly request-scoped: a new instance is built for every request.
@Injectable({ scope: Scope.REQUEST })
export class TenantService {
constructor(@Inject(REQUEST) private readonly request: Request) {}
getTenantId(): string | undefined {
// Placeholder header name; read per request.
return this.request.headers['x-tenant-id'] as string | undefined;
}
}
// No scope declared, so this looks like a singleton.
// Because it injects TenantService, Nest rebuilds it per request too.
@Injectable()
export class OrdersService {
constructor(private readonly tenant: TenantService) {}
listOrders() {
return { tenantId: this.tenant.getTenantId(), orders: [] };
}
}
// Also becomes request-scoped: it depends on OrdersService.
// Nest gives no warning at compile time or at startup.
@Controller('orders')
export class OrdersController {
constructor(private readonly orders: OrdersService) {}
@Get()
list() {
return this.orders.listOrders();
}
}
Only TenantService declares Scope.REQUEST, yet OrdersService and OrdersController are also built fresh on every request because scope moves up the injection chain.
How does AsyncLocalStorage work in NestJS?
AsyncLocalStorage, exported from node:async_hooks, ties a value to an asynchronous execution chain instead of to an object graph. Calling als.run(store, callback) makes store the active value for callback and for every async continuation it starts, including awaited promises, timers and callbacks. Anywhere inside that chain, als.getStore() returns the same object. Outside it, getStore() returns undefined.
The minimal NestJS pattern uses a middleware that generates or reads a request ID and calls als.run({ requestId }, () => next()). Guards, interceptors, controllers and services all execute inside that callback's continuation, so a singleton service can read als.getStore()?.requestId without being request-scoped. The DI graph is unchanged: each provider is created once, and the per-request value travels with the async chain.
Prefer run() over enterWith(). enterWith(store) sets the store for the rest of the current synchronous execution and for every async operation created after it, and it has no closing boundary. If it is called from shared code, such as a connection callback or a reused handler, the store can leak into work that has nothing to do with the original request. run() limits the context to the callback.
Wrap raw access in one typed context service, such as a RequestContext with a requestId getter. Consumers then declare it in their constructors, which makes the dependency visible, easy to mock in tests, and gives you one place to decide whether a missing store throws an error or returns a default.
All child tasks share the same store object. Two Promise.all branches that write to the same field will race. Set values once at the boundary and treat them as immutable, or give each mutable field a single owner that is the only code allowed to write it.
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import { Injectable, NestMiddleware } from '@nestjs/common';
import type { NextFunction, Request, Response } from 'express';
interface Store { readonly requestId: string }
// One module-level instance, shared by the middleware and the context service.
const als = new AsyncLocalStorage<Store>();
// Register in AppModule.configure() via consumer.apply(RequestContextMiddleware).
@Injectable()
export class RequestContextMiddleware implements NestMiddleware {
use(req: Request, _res: Response, next: NextFunction) {
const requestId = req.header('x-request-id') ?? randomUUID();
// run() bounds the store to this request's async chain; freeze keeps it immutable.
als.run(Object.freeze({ requestId }), () => next());
}
}
// The only place that touches `als` directly. Consumers inject it like any provider.
@Injectable()
export class RequestContext {
get requestId(): string {
const store = als.getStore();
if (!store) throw new Error('RequestContext read outside a request');
return store.requestId;
}
}
// A singleton (default scope) that still sees the per-request value.
@Injectable()
export class OrdersService {
constructor(private readonly ctx: RequestContext) {}
async findAll() {
await new Promise((resolve) => setTimeout(resolve, 10));
return { requestId: this.ctx.requestId, orders: [] }; // same ID after the await
}
}
A middleware wraps next() in als.run() with a frozen store holding the request ID, and a typed RequestContext service lets a singleton OrdersService read that ID after an await.
Should you use nestjs-cls or write your own AsyncLocalStorage wrapper?
nestjs-cls is a third-party library that wraps AsyncLocalStorage in Nest-native pieces: a module you register once and an injectable ClsService with get and set methods. It can start the context from middleware, a guard, or an interceptor, and it also lets you open a context explicitly for entry points that never pass through HTTP, such as message handlers or scheduled tasks.
The mount point matters because of Nest's request lifecycle. Middleware runs before guards and interceptors. If an auth guard needs to write the user ID, or read a tenant ID that was set earlier, the context has to exist by then, so middleware is usually the right choice. Then check that every route and transport actually goes through that middleware. Microservice transports and some excluded or globally prefixed routes can bypass it. When that happens, get returns undefined without throwing, which makes the gap easy to miss.
Conceptually, you register ClsModule.forRoot in the root module as global, with middleware mounting enabled and a setup hook that copies the request ID from a header. Any service then injects ClsService and calls get('requestId'). Option names change between releases, so confirm them against the library's documentation.
The library gives you a tested lifecycle integration. Your own wrapper is roughly 50 lines that you fully understand, plus the edge cases you will discover over time. Whichever you pick, confirm that it supports your Nest version and HTTP adapter. Express and Fastify handle middleware differently, so don't assume that behavior on one carries over to the other.
// app.module.ts: conceptual setup. Confirm option names against the nestjs-cls docs for your version.
import { Module, Injectable } from '@nestjs/common';
import { ClsModule, ClsService } from 'nestjs-cls';
import { randomUUID } from 'node:crypto';
@Injectable()
export class AuditService {
constructor(private readonly cls: ClsService) {}
record(action: string) {
// Returns undefined (no throw) if this call path never entered a context.
const requestId = this.cls.get('requestId');
console.log(JSON.stringify({ requestId, action }));
}
}
@Module({
imports: [
ClsModule.forRoot({
// Make ClsService injectable everywhere without re-importing the module.
global: true,
middleware: {
// Start the context in middleware so guards and interceptors can use it.
mount: true,
// Copy the incoming request ID, or generate one if the header is missing.
setup: (cls, req) => {
const header = req.headers['x-request-id'];
cls.set('requestId', typeof header === 'string' ? header : randomUUID());
},
},
}),
],
providers: [AuditService],
})
export class AppModule {}
A conceptual nestjs-cls setup that mounts the context in middleware, stores a request ID from a header, and reads it from an ordinary singleton service. Check the exact option names against the library's documentation.
How do you propagate context to queues, cron jobs and transactions?
Middleware only runs for HTTP requests, so anything that starts outside the HTTP pipeline has no context unless you create one. Queue consumers, scheduled tasks and microservice message handlers should each open their own run() at the entry point. Seed it with whatever the job carries: a correlation ID from the message headers, a tenant ID from the payload, or a generated ID for a cron tick. Downstream services then read context the same way they do during a request and don't need to know how they were invoked. Request-scoped providers have no equivalent here. Outside the request lifecycle there is no request to scope to, so those services either fail to resolve or need a separate code path.
Transactions work the same way. Open the transaction, store its entity manager or client handle in context, and run the unit of work inside that scope. Repositories check context for an active handle and fall back to the default connection when there isn't one, so you don't have to thread a manager argument through every method. The request-scoped alternative builds a new repository graph per request just to inject one handle. That adds overhead to every call, even the ones that never open a transaction.
Context breaks when a callback leaves the async chain. This happens with some connection pools that reuse a resource created under another request, with event emitters that fire listeners from wherever emit was called, with custom thenables, and with older callback-based libraries. You'll see one of two symptoms: values that are intermittently undefined, or worse, context leaked from a different request. Fix these deliberately. Wrap the callback with AsyncResource.bind when you register it, or explicitly re-enter run() with the values you captured beforehand.
When should you still use request-scoped or durable providers?
Request scope still makes sense when the instance itself must differ, not just the data flowing through it. Per-tenant database connections, per-tenant API clients with their own credentials, and configuration objects resolved from a tenant registry all fit this case. AsyncLocalStorage can carry the tenant ID, but something still has to hold one connection pool per tenant. Nest's injector can do that for you.
The default cost of request scope is that Nest rebuilds the whole dependent sub-tree on every request. Durable providers avoid this. You register a ContextIdStrategy through ContextIdFactory.apply(), and in its attach method you derive a tenant key from the request, for example a validated x-tenant-id header. You keep a map from tenant key to a ContextId created once with ContextIdFactory.create(). The resolver you return gives back that shared ID when info.isTreeDurable is true, and the per-request ID otherwise. Any provider declared with scope: Scope.REQUEST, durable: true is then built once per tenant and reused. You can also return a payload, which replaces the raw request under the REQUEST token.
The pitfalls are real:
- Untrusted keys. If the tenant key comes straight from a client header, any caller can select another tenant's connection. Derive it from authenticated data.
- Fallback keys. Defaulting a missing header to a shared key such as
"default"silently merges tenants. - Leftover state. Durable instances persist across requests for the same tenant, so never store per-request data on them.
- Unbounded growth. The tenant map has no eviction unless you add one.
How can it save engineering time?
The time savings come from removing recurring work, not from the initial setup, which is small for either approach.
- Adding a context field is a one-place change. With parameter drilling, adding a locale or a tenant ID means editing every method signature between the entry point and the code that reads it, plus every call site and test that calls those methods. With ALS, you set the field at the boundary and read it where it is needed. The methods in between do not change.
- No debugging of scope bubbling. Because ALS leaves providers as singletons, you avoid the class of bugs where a deep
Scope.REQUESTdependency silently turns controllers and services request-scoped, breaks a gateway or Passport strategy, or adds construction cost on the hot path. That class of bug is hard to diagnose because nothing warns at startup. - One code path for every entry point. Services that read context through a single
RequestContextorClsServicework the same in HTTP handlers, queue consumers and cron jobs, once each entry point opens arun(). You do not maintain a request-scoped variant for HTTP and a separate variant for background work. - Uniform observability. A logger that reads the correlation ID from context tags every log line automatically. Engineers investigating an incident can filter logs by one ID across all layers, instead of finding the places where someone forgot to pass the ID down.
- Simpler transaction handling. Repositories pick up the active transaction from context, so adding a repository call to a unit of work does not require changing method signatures to accept a
managerargument.
Illustrative estimate: assume a service where a new context field must reach code five calls deep, and each intermediate layer has two methods to change plus their tests. That is assumed at roughly ten signatures and their call sites and tests touched with parameter drilling, versus one setter at the boundary and one read site with ALS. The actual numbers depend entirely on your codebase.
The savings have a cost. ALS dependencies are implicit, so you need the typed wrapper, a clear error for missing context, and the tests described below. Without those, time saved on plumbing can be lost to debugging values that are intermittently undefined.
How do you test request context, and which approach should you choose?
Testing each approach
For request-scoped providers, create a context ID with ContextIdFactory.create() in the testing module and resolve providers through moduleRef.resolve(Token, contextId). get() throws for scoped providers. If the code reads REQUEST, register a fake request with moduleRef.registerRequestByContextId().
For ALS code, wrap each test body in run() (or ClsService.run() with nestjs-cls) and set the store explicitly. Add a negative test that runs outside any context and asserts a clear error. This catches code that silently reads undefined from getStore(). Add one e2e test through the real middleware or interceptor chain, because unit tests cannot catch a guard that runs before the store exists.
Cost and trade-offs
ALS removes parameter drilling and the debugging of scope bubbling. It also lets one set of singleton services serve HTTP, queues and cron. The price is an implicit dependency that does not appear in constructors, and the risk of losing context.
Illustrative estimate: assume a request-scoped root that pulls 20 providers into request scope. Each request then pays for 20 instantiations plus garbage collection. ALS pays one store allocation plus async-hook bookkeeping. Measure the difference in your own app before acting on it.
| ALS / nestjs-cls | Request-scoped providers | |
|---|---|---|
| Lifetime binding | Async call chain | DI context ID |
| Non-HTTP support | Native via run() |
Manual context IDs |
| Performance | Constant per request | Scales with scoped graph size |
| Dependency visibility | Implicit | Explicit in constructors |
| Testing effort | Wrap tests, test context loss | Resolve with context ID |
| Typical use | User, trace and tenant IDs | Per-tenant connections (durable) |
Decision guide
- Use ALS or nestjs-cls for request data.
- Use durable providers when you need per-tenant instances.
- Avoid plain
Scope.REQUESTin hot paths. - Never store the same piece of data in both mechanisms.
Alternatives to consider
Explicit parameter passing
The simplest alternative is to pass a context object (user ID, tenant, correlation ID) as an argument through every call. Nothing is hidden, the data flow is visible in function signatures, and tests need no setup beyond constructing the object. The cost is signature churn: adding one field to the context can mean editing a dozen methods that only forward it. This works best in small services or in a domain layer you want to keep free of framework concerns. Some teams combine the two: ALS at the edges, explicit parameters inside the core.
Reading from the request object directly
Guards and interceptors can attach data to the request, and custom parameter decorators can pull it into controller handlers. This is idiomatic NestJS and needs no extra machinery. However, it stops at the controller. Once you call into services, you are back to passing values explicitly or injecting REQUEST, which puts you back in request scope.
Tracing context propagation
If you already run distributed tracing, its context API (OpenTelemetry's, for example) is itself built on async context tracking and can carry baggage across service boundaries. Using it for business data such as tenant IDs or permissions mixes two concerns. It also risks leaking internal values into outbound headers. Use it to correlate logs, not as your application context store.
Legacy async_hooks libraries
Older continuation-local-storage packages predate AsyncLocalStorage and wrap async_hooks directly. They are slower and less maintained, so avoid them in new code.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs asynclocalstorage, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.