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.
Previous
What is NestJS's approach to multi-tenancy?
Next
How do you optimize NestJS application performance for high traffic?
More NestJS Questions
View all →- Advanced What is the CQRS pattern and how does NestJS support it?
- Advanced How do you implement gRPC in NestJS?
- Advanced What is the NestJS Interceptor execution order and how do multiple interceptors interact?
- Advanced How does NestJS handle graceful shutdown?
- Advanced What is custom provider syntax in NestJS (useClass, useValue, useFactory)?