Course contentsShow
← Node.js
Lesson 1057 of 1,9809. Authentication and Identity ManagementFree lesson

Building Identity Context Decorators

Use decorators to inject user data into business logic automatically.

In this lesson, you will learn how to use TypeScript decorators to automatically inject authenticated user context into your business logic methods, reducing boilerplate and preventing identity-related errors.

The Problem of Manual Context Passing

In many Node.js applications, you likely find yourself passing a user object or request context through every layer of your service. This is not only tedious but also error-prone; forgetting to pass the context can lead to unauthorized data access or missing audit logs. Decorators offer a declarative way to solve this by "decorating" your service methods to ensure they always have access to the current identity.

Implementing an Identity Decorator

By using a decorator, we can intercept a method call, ensure the identity context exists, and inject it as a parameter without the controller needing to manually fetch or pass it.

Here is a simplified example of how you might structure an @InjectUser decorator:

function InjectUser(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    // Assuming context is stored in a globally accessible store (like AsyncLocalStorage)
    const user = IdentityStore.getCurrentUser();
    
    if (!user) {
      throw new Error("Unauthorized: Identity context missing.");
    }

    // Inject the user into the method arguments
    return originalMethod.apply(this, [user, ...args]);
  };
}

class UserService {
  @InjectUser
  deleteAccount(user: User, reason: string) {
    console.log(`Deleting account for ${user.id} because: ${reason}`);
  }
}

Why Use This Approach?

Using decorators effectively abstracts the identity plumbing away from your business rules. Your deleteAccount method no longer cares how the user was authenticated or where the object came from; it simply declares that it requires a user to perform its task. This makes your services cleaner, easier to unit test (as you can simply pass a mock user), and ensures that identity validation is consistently applied across your entire application architecture.

Key Takeaway: Identity context decorators enforce security by design, ensuring that user data is injected predictably and automatically, eliminating manual passing of sensitive identity objects through your service layers.