A lightweight, framework-agnostic middleware for managing HTTP context across Node.js applications using AsyncLocalStorage.
- 🌐 Access request context from anywhere in your codebase
- 🔄 Thread-safe for concurrent requests
- 🧩 Framework-agnostic (adapters available for Express, more coming soon)
- 📋 TypeScript support with full type definitions
- 🔍 Request tracking with automatic IDs and timing
- 🧪 Well-tested
npm install @zakyyudha/http-context-middleware
- Framework-agnostic context management
- Built-in adapters for Express (with more to come)
- Request tracking with unique request IDs
- Request timing out of the box
- Simple API for getting and setting context values
const express = require('express');
const { HttpContext, adapters } = require('@zakyyudha/http-context-middleware');
const app = express();
// Apply the middleware
app.use(adapters.express());
// Use context in other middleware
app.use((req, res, next) => {
// Store values in context
HttpContext.set('user', { id: 1, name: 'John' });
next();
});
app.get('/', (req, res) => {
// Retrieve values from context
const requestId = HttpContext.get('requestId');
const user = HttpContext.get('user');
res.json({
message: 'Hello World',
requestId,
user,
});
});
app.listen(3000);
HttpContext.getContext()
- Returns the entire context object or nullHttpContext.get(key)
- Gets a value from the contextHttpContext.set(key, value)
- Sets a value in the contextHttpContext.runWithContext(context, callback)
- Runs a function with a given context
adapters.express(options)
- Creates Express middleware- Options:
includeReqRes
: Whether to include req/res objects in context (default: false)
- Options:
- Support for more frameworks: Koa, Fastify, Hapi, etc.
- Typescript support
- Context persistence across async boundaries
- Integration with logging libraries
MIT