What is express-http-context?
The express-http-context package provides a way to manage and access context data across the lifecycle of an HTTP request in an Express application. This is particularly useful for scenarios where you need to share data between middleware and route handlers without explicitly passing it around.
What are express-http-context's main functionalities?
Set and Get Context Data
This feature allows you to set and get context data within the lifecycle of an HTTP request. In this example, user data is set in the context in a middleware and then accessed in a route handler.
const express = require('express');
const httpContext = require('express-http-context');
const app = express();
app.use(httpContext.middleware);
app.use((req, res, next) => {
httpContext.set('user', { id: 1, name: 'John Doe' });
next();
});
app.get('/', (req, res) => {
const user = httpContext.get('user');
res.send(`Hello, ${user.name}`);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Namespace Isolation
This feature ensures that context data is isolated per request by binding the request and response objects to the context namespace. This is useful for tracking request-specific data like request IDs.
const express = require('express');
const httpContext = require('express-http-context');
const app = express();
app.use(httpContext.middleware);
app.use((req, res, next) => {
httpContext.ns.bindEmitter(req);
httpContext.ns.bindEmitter(res);
next();
});
app.use((req, res, next) => {
httpContext.set('requestId', req.headers['x-request-id']);
next();
});
app.get('/', (req, res) => {
const requestId = httpContext.get('requestId');
res.send(`Request ID: ${requestId}`);
});
app.listen(3000, () => console.log('Server running on port 3000'));
Other packages similar to express-http-context
cls-hooked
cls-hooked is a continuation-local storage package that provides a way to maintain context across asynchronous operations. It is more general-purpose compared to express-http-context and can be used outside of Express applications. However, it requires more setup to integrate with Express.
async-local-storage
async-local-storage is a built-in Node.js module that provides an API for maintaining context across asynchronous operations. It is similar to cls-hooked but is part of the Node.js core. It offers a more standardized approach but may require additional boilerplate to use effectively with Express.
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-http-context
Use the middleware. The earlier the better; you won't have access to the context from any middleware "used" before this one.
var express = require('express');
var httpContext = require('express-http-context');
var app = express();
app.use(httpContext.middleware);
Set values based on the incomming request:
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:
var httpContext = require('express-http-context');
function createTodoItem(title, content, callback) {
var user = httpContext.get('user');
db.insert({ title, content, userId: user.id }, callback);
}