Get and set request-scoped context anywhere
npm install @deviousm/express-http-context




npm install --save express-http-context
npm install --save express-http-context@<1.0.0)
js
var express = require('express');
var httpContext = require('express-http-context');
var app = express();
// Use any third party middleware that does not need access to the context here, e.g.
// app.use(some3rdParty.middleware);
app.use(httpContext.middleware);
// all code from here on has access to the same context for each request
`
Set values based on the incoming request:
` js
// Example authorization middleware
app.use((req, res, next) => {
userService.getUser(req.get('Authorization'), (err, result) => {
if (err) {
next(err);
} else {
httpContext.set('user', result.user)
next();
}
});
});
`
Get them from code that doesn't have access to the express req object:
` js
var httpContext = require('express-http-context');
// Somewhere deep in the Todo Service
function createTodoItem(title, content, callback) {
var user = httpContext.get('user');
db.insert({ title, content, userId: user.id }, callback);
}
`
You can access cls namespace directly as (it may be useful if you want to apply some patch to it, for example https://github.com/TimBeyer/cls-bluebird):
` js
var ns = require('express-http-context').ns;
`
Troubleshooting
To avoid weird behavior with express:
1. Make sure you require express-http-context` in the first row of your app. Some popular packages use async which breaks CLS.