W3C Traceparent Header Parser

Parse and validate a W3C traceparent header into version, trace id, span id and flags, rejecting malformed values.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
const HEX = { trace: 32, span: 16 };

export function parseTraceparent(value) {
  if (typeof value !== 'string') throw new TypeError('traceparent must be a string');
  const parts = value.trim().split('-');
  if (parts.length !== 4) throw new SyntaxError('traceparent must have 4 fields');
  const [version, traceId, spanId, flags] = parts;
  if (!/^[0-9a-f]{2}$/.test(version)) throw new SyntaxError('invalid version: ' + version);
  if (version === 'ff') throw new SyntaxError('version ff is invalid');
  if (!new RegExp('^[0-9a-f]{' + HEX.trace + '}$').test(traceId)) {
    throw new SyntaxError('invalid trace id: ' + traceId);
  }
  if (traceId === '0'.repeat(HEX.trace)) throw new SyntaxError('trace id must not be all zeros');
  if (!new RegExp('^[0-9a-f]{' + HEX.span + '}$').test(spanId)) {
    throw new SyntaxError('invalid span id: ' + spanId);
  }
  if (spanId === '0'.repeat(HEX.span)) throw new SyntaxError('span id must not be all zeros');
  if (!/^[0-9a-f]{2}$/.test(flags)) throw new SyntaxError('invalid flags: ' + flags);
  return { version, traceId, spanId, sampled: (parseInt(flags, 16) & 1) === 1 };
}

How it works

Count the function parseTraceparent as the entire surface area of W3C Traceparent Header Parser.

When the guard condition holds, TypeError and SyntaxError is thrown rather than a bogus value returned.

The result comes back as an object carrying version, traceId, spanId, flags.

What to watch for

  • The guard typeof value !== 'string' short-circuits the flow with an early throw when its condition holds.

Putting it to use

The main signature reads export function parseTraceparent(value)

The surface worth importing is parseTraceparent; the helpers around it are private to the snippet.

The call returns version, traceId, spanId, flags — destructure what you need at the call site.

Core lines

if (traceId === '0'.repeat(HEX.trace)) throw new SyntaxError('trace id must not be all zeros');
if (spanId === '0'.repeat(HEX.span)) throw new SyntaxError('span id must not be all zeros');
if (!/^[0-9a-f]{2}$/.test(version)) throw new SyntaxError('invalid version: ' + version);

Interactive Tools for This Topic

FAQ

Does `parseTraceparent` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
How does the code behave when input is bad?
Validation comes first — `TypeError` and `SyntaxError` marks the failure at `typeof value !== 'string'`, before any partial work happens.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `parseTraceparent` at load time.