Context Propagation
Vestig provides powerful context propagation using AsyncLocalStorage, ensuring your logging context flows through your entire request lifecycle without manual passing.
Overview
Context propagation solves a fundamental problem: how do you attach metadata (like request IDs, user info) to all logs within a request without passing context through every function?
How It Works
Vestig uses AsyncLocalStorage (available in Node.js, Bun, and Deno) to maintain context across async boundaries:
Basic Usage
Setting Context
Reading Context
Nested Context
Context can be nested, with inner contexts merging with outer:
Correlation Context
Vestig provides a specialized correlation context for request tracing:
Custom Correlation IDs
Context with Child Loggers
Child loggers inherit context from the current scope:
Context with Spans
Spans automatically include the current context:
HTTP Request Context
Express.js
Next.js
With @vestig/next, context is automatically set up:
Browser Context
In browsers (where AsyncLocalStorage isn't available), Vestig uses a fallback:
Note: Browser context doesn't persist across async operations the same way. For full async context in browsers, explicitly pass context or use the VestigProvider.
With VestigProvider (React)
Context Cleanup
Context is automatically cleaned up when the callback completes:
Performance Considerations
AsyncLocalStorage has minimal overhead:
- ~0.01ms per context access
- No memory leaks (context cleaned up automatically)
- Works with thousands of concurrent requests
However, avoid storing large objects in context:
API Reference
Functions
| Function | Description |
|---|---|
withContext(ctx, fn) |
Run function with context, returns function result |
withContextAsync(ctx, fn) |
Alias for withContext with async function |
getContext() |
Get current context object |
createCorrelationContext(opts) |
Create correlation context with auto IDs |
Types
Best Practices
- Set context at request entry - middleware, route handler entry
- Keep context small - IDs and metadata, not full objects
- Use correlation IDs - for tracing across services
- Don't mutate context - create new contexts for changes
- Use child loggers - for per-module logging with context inheritance