{"id":17537,"library":"cls-middleware","title":"Connect & Restify CLS Middleware","description":"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.","status":"abandoned","version":"1.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/othiym23/cls-middleware","tags":["javascript","continuation-local-storage","express"],"install":[{"cmd":"npm install cls-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add cls-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add cls-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the core Continuation Local Storage functionality this middleware wraps.","package":"continuation-local-storage","optional":false},{"reason":"Implicit peer dependency; the package is designed as middleware for Express (or Connect/Restify) applications.","package":"express","optional":true}],"imports":[{"note":"This package is exclusively CommonJS and does not support ES Modules directly without a CommonJS wrapper or transpilation.","wrong":"import clsify from 'cls-middleware';","symbol":"clsify","correct":"const clsify = require('cls-middleware');"},{"note":"The underlying `continuation-local-storage` library is also CommonJS. It's used here to create the CLS namespace.","wrong":"import { createNamespace } from 'continuation-local-storage';","symbol":"cls.createNamespace","correct":"const cls = require('continuation-local-storage');\nconst ns = cls.createNamespace('my-namespace');"}],"quickstart":{"code":"const cls = require('continuation-local-storage');\nconst express = require('express');\nconst clsify = require('cls-middleware');\n\n// Create a CLS namespace for your application\nconst ns = cls.createNamespace('my-app-namespace');\n\nconst app = express();\n\n// Apply the cls-middleware to bind incoming requests to the CLS namespace\napp.use(clsify(ns));\n\napp.get('/users', function (req, res, next) {\n  // Set a request-scoped value\n  ns.set('userId', req.query.id || 'anonymous');\n\n  // Simulate an async operation where the context should persist\n  setTimeout(() => {\n    const currentUserId = ns.get('userId');\n    console.log(`Request ID: ${req.query.id || 'none'} - User ID from CLS: ${currentUserId}`);\n    res.send(`Hello, User ${currentUserId}!`);\n    next();\n  }, 100);\n});\n\n// Start the server\napp.listen(3000, () => {\n  console.log('Server listening on port 3000');\n});","lang":"javascript","description":"Demonstrates setting up `cls-middleware` with Express to establish a request-scoped CLS context and retrieve data within an asynchronous operation."},"warnings":[{"fix":"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.","message":"This package relies on `continuation-local-storage`, which utilizes older, potentially unstable or deprecated Node.js internal APIs (like `async-listener` or `AsyncWrap`). This can lead to unexpected behavior or compatibility issues with newer Node.js versions.","severity":"breaking","affected_versions":">=0.12"},{"fix":"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.","message":"The `cls-middleware` package and its core dependency `continuation-local-storage` are no longer actively maintained. The last release was in 2014, and the underlying CLS mechanism has been superseded by `AsyncLocalStorage` in Node.js core.","severity":"deprecated","affected_versions":">=1.0.0"},{"fix":"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.","message":"CLS context can be lost when integrating with certain third-party middlewares or libraries that do not properly propagate `AsyncResource` contexts, such as `multer` for file uploads or some custom promise-based middleware.","severity":"gotcha","affected_versions":"*"},{"fix":"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.","message":"Incorrect middleware ordering can prevent the CLS context from being established for certain routes or requests. If global prefixes or versioning are used, `cls-middleware` might not trigger on all routes.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"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.","cause":"Attempting to access a CLS namespace (`ns.get()`) when no active context is available, often because `cls-middleware` was not applied, or the code is running outside of a request context.","error":"TypeError: Cannot read property 'get' of undefined (or similar 'Cannot read property of null')"},{"fix":"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.","cause":"This error, or similar context loss issues, occur when code attempts to set a value in a CLS namespace after the asynchronous flow has exited the context established by the middleware, or if an intervening library broke the context chain.","error":"Error: Cannot set the key \"myKey\". No CLS context available, please make sure that a ClsMiddleware/Guard/Interceptor has set up the context, or wrap any calls that depend on CLS with \"ClsService#run\""}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}