Package Exports
- express-http-context
- express-http-context/browser.js
- express-http-context/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (express-http-context) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Express HTTP Context
Get and set request-scoped context anywhere. This package is an unopinionated, zero-dependency, Express-idiomatic implementation of Node AsyncLocalStorage. 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 i express-http-context
Use the context middleware before the first middleware or handler that needs to have access to the context.
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:
// 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:
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 });
}
Legacy versions
- For Node <7:
npm install --save express-http-context@0
- For Node >=8 <12:
npm install --save express-http-context@1
Contributors
- Steve Konves (@skonves)
- Amiram Korach (@amiram)
- Yoni Rabinovitch (@yonirab)
- DontRelaX (@dontrelax)
- William Durand (@willdurand)
- Kristopher Morris (@beeduck)
Interesting in contributing? Take a look at the Contributing Guidlines