cls-hooked is a Node.js library that provides Continuation-Local Storage (CLS), a mechanism akin to thread-local storage but adapted for Node.js's asynchronous, callback-based execution model. It enables developers to maintain and implicitly pass contextual data across asynchronous operations without explicit parameter passing. The current stable version, 4.2.2, primarily targets Node.js versions `^4.7 || >=6.9 || >=7.3 || >=8.2.1`. Its key differentiator lies in its implementation, which leverages Node.js's internal, lower-level APIs: `AsyncWrap` for Node.js versions prior to v8 (an unofficial API), and the `async_hooks` API for Node.js v8.2.1 and newer (which is considered experimental). This approach distinguishes it from its predecessor, `node-continuation-local-storage`, which relied on the now-deprecated `async-listener`. The project's release cadence is largely influenced by the evolution and stability of these underlying Node.js APIs, aiming to provide a robust CLS implementation despite the experimental nature of its core dependencies.
npm install cls-hookedVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create and manage continuation-local storage contexts using `cls-hooked`'s `createNamespace`, `run`, `set`, and `get` methods, including persistence across asynchronous operations and nested contexts.
Consider upgrading to Node.js v8.2.1 or newer to utilize the `async_hooks` API. Be aware of the `async_hooks` API's experimental status.
Regularly update `cls-hooked` to its latest version to ensure compatibility with newer Node.js releases, especially those introducing changes to the `async_hooks` API.
Ensure your `cls-hooked` version is compatible with your Node.js version. Refer to `cls-hooked` release notes and `engines` field in `package.json` for specific compatibility information.
Upgrade to `cls-hooked` version 4.2.1 or newer to benefit from memory leak reductions and improvements.
If a namespace with the desired name might already exist, retrieve it using `const myNamespace = cls.getNamespace('my-app-session');` instead of `createNamespace`.Ensure that any code that needs to access or modify the CLS context is executed within a `namespace.run(function() { ... })` block, or by passing functions through `namespace.bind(func)` to propagate the context.First, verify that your Node.js version is explicitly supported by `cls-hooked`'s `engines` field. Second, ensure you are using the latest stable version of `cls-hooked` to benefit from any bug fixes related to `async_hooks` compatibility. If the problem persists, review complex or non-standard asynchronous flows in your application.