Overview of NestJS CLS (Async Context)
mainNestJS CLS is a continuation-local storage module designed for NestJS applications. It is built on top of Node.js AsyncLocalStorage and allows you to store state and propagate it throughout callbacks, promise chains, and asynchronous durations (such as the lifetime of a web request). This is functionally similar to thread-local storage in other programming languages.
Common use cases include:
- Logging: Tracking Request IDs and other metadata.
- User Context: Keeping track of the current user throughout a request.
- Multi-tenancy: Making dynamic tenant database connections available globally.
- Security: Propagating authentication levels or roles.
- Database Transactions: Seamlessly propagating transactions across services using the
Transactionalplugin without manual parameter passing. - Context Access: Using request context in environments where standard NestJS
REQUEST-scoped providers are not supported (e.g., Passport strategies, Cron controllers, WebSocket gateways, or Queue consumers).