What is nestjs-cls?
The 'nestjs-cls' package provides a way to manage context-local storage in NestJS applications. It allows you to store and retrieve data that is scoped to the current request, making it useful for tasks like logging, tracing, and managing user sessions.
What are nestjs-cls's main functionalities?
Context Management
This feature allows you to set and get values within the context of a request. The 'ClsService' is used to manage context-local storage, making it easy to store and retrieve data that is specific to the current request.
const { ClsService } = require('nestjs-cls');
@Injectable()
export class MyService {
constructor(private readonly cls: ClsService) {}
doSomething() {
this.cls.set('key', 'value');
const value = this.cls.get('key');
console.log(value); // Outputs: 'value'
}
}
Middleware Integration
This feature demonstrates how to integrate 'ClsMiddleware' into your NestJS application. By applying this middleware, you ensure that context-local storage is available for all routes, making it easy to manage request-specific data throughout your application.
const { ClsMiddleware } = require('nestjs-cls');
@Module({
providers: [ClsMiddleware],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(ClsMiddleware)
.forRoutes('*');
}
}
Async Context Management
This feature shows how to manage context-local storage in asynchronous operations. The 'run' method of 'ClsService' ensures that the context is preserved across asynchronous boundaries, allowing you to set and get values within async functions.
const { ClsService } = require('nestjs-cls');
@Injectable()
export class MyService {
constructor(private readonly cls: ClsService) {}
async doSomethingAsync() {
await this.cls.run(async () => {
this.cls.set('key', 'value');
const value = this.cls.get('key');
console.log(value); // Outputs: 'value'
});
}
}
Other packages similar to nestjs-cls
cls-hooked
The 'cls-hooked' package provides a way to manage context-local storage using Node.js async_hooks. It is a lower-level library compared to 'nestjs-cls' and requires more manual setup, but it offers similar functionality for managing request-specific data.
async-local-storage
The 'async-local-storage' package is another library for managing context-local storage in Node.js applications. It provides a simple API for storing and retrieving data that is scoped to the current request, similar to 'nestjs-cls', but without the NestJS-specific integrations.
continuation-local-storage
The 'continuation-local-storage' package offers context-local storage using the continuation-local-storage API. It is an older library and has been largely replaced by 'cls-hooked', but it still provides similar functionality for managing request-specific data.
NestJS CLS (Async Context)
A continuation-local storage module compatible with NestJS' dependency injection based on AsyncLocalStorage.
Notice: The documentation has been moved to a dedicated website.
Continuation-local storage allows to store state and propagate it throughout callbacks and promise chains. It allows storing data throughout the lifetime of a web request or any other asynchronous duration. It is similar to thread-local storage in other languages.
Some common use cases that this library enables include:
- Tracking the Request ID and other metadata for logging purposes
- Keeping track of the user throughout the whole request
- Making the dynamic Tenant database connection available everywhere in multi-tenant apps
- Propagating the authentication level or role to restrict access to resources
- Seamlessly propagating database transaction across services without breaking encapsulation and isolation by explicitly passing it around (Now available with the Transactional plugin)
- Using "request" context in cases where actual REQUEST-scoped providers are not supported (passport strategies, cron controllers, websocket gateways, ...)
Most of these are to some extent solvable using REQUEST-scoped providers or passing the context as a parameter, but these solutions are often clunky and come with a whole lot of other issues.
Documentation
Contributing
Contributing to a community project is always welcome, please see the Contributing guide :)