Continuation Local Storage
The purpose with this module is to share contexts across async (and sync) calls. Contexts are accessed by keys and can be nested. It is an alternative to the deprecated domain. It is based on async_hooks that were introduced in node 8. Beware that that the async_hooks are still experimental in nodejs.
To avoid weird behavior with express
- Make sure you require
node-cls
in the first row of your app. Some popular packages use async which breaks CLS. - If you are using
body-parser
and context is getting lost, register it in express before you registernode-cls
's middleware.
Request handler
A typical scenario is when you need to share context in a request handler.
let http = ;let cls = ; let server = http server { let context = cls; contextresponse //End: 1 }
Async calls
Context is retained in async calls.
let cls = ; let context = cls;context; { let context = cls; console; //George}
Nesting
Contexts can be nested, even on the same key.
let cls = ; let context = cls;context; { await Promise; let context = cls; console; //undefined contextname = 'John Nested'; ;} { let context = cls; console; //John Nested}
Symbol as key
If you are a library author, use a Symbol as key to avoid conflicts with other libraries.
let cls = ;let key = Symbol; let context = cls;context; { let context = cls; console; //George}
Await instead of run
In node 12 and above you can start a context directly instead of wrapping it in the run function. The start function returns a promise. You can leave the current context by calling exit.
let cls = ; { let context = cls; contextname = 'George'; await contextstart; let context2 = cls; context2name = 'John Nested'; await context2start; console; //John Nested cls; console; //George cls; console; //undefined} ;