Express HTTP Context with async_hooks
This package is forked from express-http-context. It is using cls-hooked which is a fork of continuation-local-storage that uses async_hooks API, so context is preserved even over async/await in node 8+. If you're using node version < 8, just use the original express-http-context.
Get and set request-scoped context anywhere. This is just an unopinionated, idiomatic ExpressJS implementation of continuation-local-storage. It's a great place to store user state, claims from a JWT, request/correlation IDs, and any other request-scoped data.
How to use it
Install: npm install --save express-cls-hooked
Use the middleware. The earlier the better; you won't have access to the context from any middleware "used" before this one.
var express = ;var httpContext = ;var app = ;app;// all code from here on has access to the same context for each request
Set values based on the incomming request:
// Example authorization middlewareapp;
Get them from code that doesn't have access to the express req
object:
var httpContext = ;// Somewhere deep in the Todo Service{var user = httpContext;db;}
Troubleshooting
To avoid weird behavior with express:
- Make sure you require
express-cls-hooked
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 registerexpress-cls-hooked
's middleware.
See Issue #4 for more context. If you find any other weird behaviors, please feel free to open an issue.