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



Install: npm i express-http-context
Use the context middleware before the first middleware or handler that needs to have access to the context.
`` js
import express from 'express';
import * as httpContext from 'express-http-context';
const app = express();
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 authentication middleware
app.use(async (req, res, next) => {
try {
// Get user from data on request
const bearer = req.get('Authorization');
const user = await userService.getUser(bearer);
// Add user to the request-scoped context
httpContext.set('user', user);
return next();
} catch (err) {
return next(err);
}
});
`
Get them from code that doesn't have access to the express req object:
` js
import * as httpContext from 'express-http-context';
// Somewhere deep in the Todo Service
async function createTodoItem(title, content) {
// Get the user from the request-scoped context
const user = httpContext.get('user');
await db.insert({ title, content, userId: user.id });
}
`
* For Node <7: npm install --save express-http-context@0npm install --save express-http-context@1`
* For Node >=8 <12:
Interesting in contributing? Take a look at the Contributing Guidlines