Course contentsShow
← Node.js
Lesson 697 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Request Context Propagation

Maintain user session identity throughout deep service calls without passing explicit parameters.

Request Context Propagation

In this lesson, you will learn how to maintain user identity across deep service layers without manually passing "user-id" parameters through every single function.

When you build complex applications using Service Layer Abstraction and Repository Patterns, a single web request often triggers a long chain of function calls. Imagine a user hits an endpoint; your controller calls a service, which calls a validator, which finally hits a database repository. If you need to know who is performing the action (e.g., for audit logs or authorization), passing a userId argument through every layer becomes messy and error-prone.

Request Context Propagation solves this by creating a "hidden" space associated with the current execution flow.

The Concept

Think of it like a sticky note attached to the current request that follows it everywhere, regardless of which module or service function is currently running. Instead of passing arguments explicitly, we use a mechanism (typically Node.js’s AsyncLocalStorage) to store the user identity at the start of the request. Any deep-level service can then "look up" that identity without needing it to be passed in as a parameter.

Simple Illustration

In a middleware, you capture the user's data and store it in the context. Later, in a deep database repository, you access it directly:

// Middleware: Setting the context
async function contextMiddleware(req, res, next) {
  const context = { userId: req.headers['x-user-id'] };
  // Attach user context to the active request flow
  await asyncLocalStorage.run(context, () => next());
}

// Deep Service: Retrieving the context
function updateDatabaseRecord(data) {
  const { userId } = asyncLocalStorage.getStore(); // No need to pass userId!
  return repository.save(userId, data);
}

By decoupling the "context" (who is doing this) from the "logic" (what is being done), your service functions remain clean. They focus on their domain task—like Domain Entity Modeling—rather than constantly carrying around metadata that isn't core to their business logic. This keeps your architecture decoupled and much easier to maintain as your project scales.

Key Takeaway: Request Context Propagation allows you to store and retrieve metadata like user identity globally within a single request’s execution flow, removing the need for noisy, repetitive parameter passing.