Request Context
Minimal Node.js library for managing per-request context and enhancing your logger automatically.
Features
- Scoped context per request using AsyncLocalStorage
- Pluggable logger (Pino, Winston, Console, etc.)
- Auto-injects traceId, userId, path into logs
- Framework agnostic - supports Express, Fastify, and native HTTP
- Clean, small, production-ready
Installation
npm install request-context
Usage
Express
import express from 'express';
import { expressMiddleware, logger } from 'request-context';
const app = express();
app.use(expressMiddleware({
requestIdHeader: 'x-request-id',
getUserId: req => req.user?.id,
getExtra: req => ({
ip: req.ip
})
}));
app.get('/', (req, res) => {
logger.info('Hello world!');
res.send('Hello!');
});
Fastify
import fastify from 'fastify';
import { fastifyMiddleware, logger } from 'request-context';
const app = fastify();
app.addHook('onRequest', fastifyMiddleware({
requestIdHeader: 'x-request-id',
getUserId: request => request.user?.id,
getExtra: request => ({
ip: request.ip
})
}));
app.get('/', (request, reply) => {
logger.info('Hello world!');
reply.send('Hello!');
});
Native HTTP Server
import http from 'http';
import { httpMiddleware, logger } from 'request-context';
const middleware = httpMiddleware({
requestIdHeader: 'x-request-id',
getUserId: req => req.user?.id,
getExtra: req => ({
ip: req.socket.remoteAddress
})
});
const server = http.createServer((req, res) => {
middleware(req, res, () => {
logger.info('Hello world!');
res.end('Hello!');
});
});
server.listen(3000);
Configuration Options
All middleware functions accept these options:
requestIdHeader (string): Header to use for request ID. Defaults to 'x-request-id'
getUserId (function): Function to extract user ID from request. Defaults to req.user?.id
getExtra (function): Function to extract additional context from request. Defaults to empty object
Logger Configuration
import pino from 'pino';
import { logger } from 'request-context';
logger.configure(pino());
logger.info('Hello world!');
Context Values
The following context values are automatically added to every request:
requestId: Unique ID for each request (from header or generated)
path: Request path
method: HTTP method
userId: User ID (if available)
- Any additional values from getExtra()
Examples
Check out the examples directory for complete working examples using:
- Express
- Fastify
- Native HTTP Server
Each example demonstrates:
- Middleware setup
- Logger configuration
- Request handling
- Error handling
- Context propagation
Publishing
A publish script is included to help with releasing new versions. The script handles:
- npm login
- version bumping
- publishing to npm
- git tagging
- pushing changes
To use it:
chmod +x publish.sh
./publish.sh <version_type>
The script will:
- Validate your working directory is clean
- Log you into npm if needed
- Run tests if they exist
- Bump the version
- Publish to npm
- Push changes and tags to git
License
MIT