Accept Header Negotiation With Quality Values

Parse Accept headers with q-values and wildcards, then pick the best supported media type while honoring q=0 exclusions and server order.

JavascriptData Fetching

Code

javascriptsnippet
67 lines
export function parseAcceptHeader(header) {
  if (typeof header !== "string" || header.trim() === "") {
    return [{ type: "*", subtype: "*", q: 1, params: {}, order: 0 }];
  }
  const ranges = [];
  for (const [order, part] of header.split(",").entries()) {
    const segments = part.split(";").map((segment) => segment.trim());
    const mediaRange = segments.shift();
    if (!mediaRange) continue;
    const slash = mediaRange.indexOf("/");
    if (slash <= 0 || slash === mediaRange.length - 1) {
      throw new SyntaxError("invalid media range: " + mediaRange);
    }
    const type = mediaRange.slice(0, slash).toLowerCase();
    const subtype = mediaRange.slice(slash + 1).toLowerCase();
    const params = {};
    let q = 1;
    for (const segment of segments) {
      if (!segment) continue;
      const equals = segment.indexOf("=");
      if (equals <= 0) throw new SyntaxError("invalid parameter: " + segment);
      const name = segment.slice(0, equals).trim().toLowerCase();
      const raw = segment.slice(equals + 1).trim().replace(/^"|"$/g, "");
      if (name === "q") {
        q = Number(raw);
        if (!Number.isFinite(q) || q < 0 || q > 1) {
          throw new RangeError("invalid q value: " + raw);
        }
      } else {
        params[name] = raw;
      }
    }
    ranges.push({ type, subtype, q, params, order });
  }
  if (ranges.length === 0) throw new SyntaxError("Accept header has no media ranges");
  return ranges;
}

export function negotiateContentType(header, supported) {
  if (!Array.isArray(supported) || supported.length === 0) {
    throw new TypeError("supported must be a non-empty array");
  }
  const ranges = parseAcceptHeader(header);
  const candidates = [];
  for (const [order, mediaType] of supported.entries()) {
    const slash = mediaType.indexOf("/");
    if (slash <= 0) throw new TypeError("invalid supported media type: " + mediaType);
    const type = mediaType.slice(0, slash).toLowerCase();
    const subtype = mediaType.slice(slash + 1).toLowerCase();
    let best;
    for (const range of ranges) {
      const typeMatches = range.type === "*" || range.type === type;
      const subtypeMatches = range.subtype === "*" || range.subtype === subtype;
      if (!typeMatches || !subtypeMatches) continue;
      const specificity = (range.type === "*" ? 0 : 1) + (range.subtype === "*" ? 0 : 1);
      if (!best || specificity > best.specificity ||
        (specificity === best.specificity && range.order < best.order)) {
        best = { q: range.q, specificity, order: range.order };
      }
    }
    if (best && best.q > 0) {
      candidates.push({ mediaType, q: best.q, specificity: best.specificity, order });
    }
  }
  candidates.sort((a, b) => b.q - a.q || b.specificity - a.specificity || a.order - b.order);
  return candidates.length > 0 ? candidates[0].mediaType : null;
}

How the snippet works

Accept Header Negotiation With Quality Values keeps everything in the functions specificity, parseAcceptHeader and negotiateContentType.

The core work runs in nested loops — outer for (const [order, part] of header.split(",").entries()), inner for (const segment of segments). Invalid states are rejected up front: it throws SyntaxError, RangeError and TypeError instead of continuing with bad data.

It builds and returns a fresh value rather than reusing its inputs.

What to watch for

  • Once its condition holds, the guard !mediaRange stops that path early using continue.

Applying it

Entry signature: export function parseAcceptHeader(header)

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

Statements that matter

candidates.sort((a, b) => b.q - a.q || b.specificity - a.specificity || a.order - b.order);
if (ranges.length === 0) throw new SyntaxError("Accept header has no media ranges");
if (slash <= 0) throw new TypeError("invalid supported media type: " + mediaType);

Interactive Tools for This Topic

FAQ

Does `parseAcceptHeader` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
How does the snippet fail?
It throws `SyntaxError`, `RangeError` and `TypeError` before any real work runs, via the guard `!mediaRange` — handle it at the call site or let it propagate deliberately.
Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `specificity`, `parseAcceptHeader`, `negotiateContentType` at load time.