@zakyyudha/http-context-middleware
Version:
HTTP context middleware using Node.js AsyncLocalStorage
92 lines (65 loc) โข 2.52 kB
Markdown
[](https://www.npmjs.com/package/@zakyyudha/http-context-middleware)
[](https://www.typescriptlang.org/)
[](https://opensource.org/licenses/MIT)
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
## Usage
### With Express.js
```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 null
- `HttpContext.get(key)` - Gets a value from the context
- `HttpContext.set(key, value)` - Sets a value in the context
- `HttpContext.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)
## Future Plans
- Support for more frameworks: Koa, Fastify, Hapi, etc.
- Typescript support
- Context persistence across async boundaries
- Integration with logging libraries
## License
MIT