W3C Trace Context
Vestig implements the W3C Trace Context specification for distributed tracing across services. This enables seamless integration with OpenTelemetry and other tracing systems.
Overview
W3C Trace Context defines two HTTP headers for propagating trace information:
traceparent: Contains the trace ID, span ID, and trace flagstracestate: Contains vendor-specific trace data
Vestig provides utilities for both parsing incoming headers and creating outgoing headers.
Traceparent Header
The traceparent header format is:
Example: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
Parsing Traceparent
Creating Traceparent
Trace Flags
| Flag Value | Meaning |
|---|---|
0 |
Not sampled - trace may be discarded |
1 |
Sampled - trace should be recorded |
Tracestate Header
The tracestate header allows vendors to include additional trace context:
Parsing Tracestate
Creating Tracestate
Modifying Tracestate
Use the utility functions to safely modify tracestate:
Tracestate Limits
Per the W3C specification:
- Maximum 32 list members
- Key format:
[a-z][a-z0-9_\-\*/]{0,255}or[a-z0-9][a-z0-9_\-\*/]{0,240}@[a-z][a-z0-9_\-\*/]{0,13} - Value format: printable ASCII excluding
,and=
Vestig automatically validates and enforces these limits.
Integration with Spans
When creating spans, Vestig can automatically propagate trace context:
Propagating to Outgoing Requests
Next.js Integration
With @vestig/next, trace context is automatically handled in middleware:
OpenTelemetry Compatibility
Vestig's W3C Trace Context implementation is fully compatible with OpenTelemetry. You can:
- Receive traces from OTel-instrumented services
- Send traces to OTel-instrumented services
- Export to OTel collectors (coming in v0.8.0)
API Reference
Types
Functions
| Function | Description |
|---|---|
parseTraceparent(header) |
Parse traceparent header, returns TraceContext | null |
createTraceparent(context) |
Create traceparent header string |
parseTracestate(header) |
Parse tracestate header, returns Map<string, string> |
createTracestate(state) |
Create tracestate header string |
getTracestateValue(state, key) |
Get value from tracestate |
setTracestateValue(state, key, value) |
Set value in tracestate (returns new Map) |
deleteTracestateKey(state, key) |
Delete key from tracestate (returns new Map) |
generateTraceId() |
Generate random 32-char hex trace ID |
generateSpanId() |
Generate random 16-char hex span ID |
Best Practices
- Always propagate trace context in outgoing HTTP requests
- Check for existing context before creating new trace IDs
- Respect the sampled flag - don't record unsampled traces
- Keep tracestate values short - they add HTTP header overhead
- Use your vendor key in tracestate for your own metadata