cls-middleware provides a simple middleware for Connect and Restify (and by extension, Express) to integrate continuation-local storage (CLS) contexts into request handling. It binds each incoming request's execution flow to a dedicated CLS namespace, allowing developers to store and retrieve request-scoped data without explicit parameter passing across function calls. This package relies on the older `continuation-local-storage` library, which itself uses deprecated Node.js internal APIs or earlier experimental `async_hooks` implementations. The current stable version is 1.1.0, published in 2014, indicating it is no longer actively maintained. For modern Node.js environments (v14.5.0+), the built-in `AsyncLocalStorage` is the recommended and more performant solution for managing asynchronous context.
npm install cls-middlewareVerified import paths — ran on the pinned version, not inferred.
Demonstrates setting up `cls-middleware` with Express to establish a request-scoped CLS context and retrieve data within an asynchronous operation.
Migrate to `cls-hooked` (for older Node.js if `AsyncLocalStorage` is unavailable) or preferably Node.js's native `AsyncLocalStorage` for versions 14.5.0 and above.
Adopt Node.js's built-in `async_hooks.AsyncLocalStorage` (Node.js 14.5.0+) or community alternatives like `cls-hooked` for robust continuation-local storage.
Explicitly bind functions that might lose context using `ns.bind()` or wrap entire operations within `ns.run()`. For modern `AsyncLocalStorage`, consider `AsyncLocalStorage.bind()` or ensure middlewares are ordered correctly, usually with CLS middleware first.
Ensure `cls-middleware` is applied early in your Express/Connect middleware stack, ideally before any other middleware that needs access to the CLS context. For complex routing setups, manually applying it to specific routes might be necessary.
Ensure `app.use(clsify(ns))` is correctly configured and executed, and that the code trying to access CLS is within the execution flow of a request handled by the middleware. Verify the namespace is correctly created.
Identify the asynchronous operation causing the context loss. Use `ns.bind(callback)` to explicitly attach the current context to a callback, or `ns.run(callback)` to execute code within a new or existing context. Consider using `AsyncLocalStorage.snapshot()` or `AsyncLocalStorage.bind()` with modern Node.js APIs.