🦅 NestJS Advanced

What is the cls-hooked/nestjs-cls module and when should you use it?

Answer

nestjs-cls (Continuation Local Storage) provides request-scoped context without making providers REQUEST-scoped — avoiding the cascading scope problem. It uses Node.js AsyncLocalStorage to store context that is accessible anywhere in the call stack for the duration of a request, including deeply nested services. Example: store the current user once in middleware: cls.set('user', req.user). Any service can retrieve it: const user = cls.get<User>('user') — without it being passed through every function. This is ideal for: multi-tenant tenant ID propagation, correlation/trace IDs, audit logging (who performed this action?), and soft-delete (set deleted-by automatically). It avoids the performance overhead of REQUEST-scoped providers while achieving the same result.