HTTP context middleware using Node.js AsyncLocalStorage
npm install @zakyyudha/http-context-middleware


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
``bash`
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
`javascript
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 middlewareincludeReqRes`: 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