nodejs/node · error · RequestContentLengthMismatchError

UND_ERR_REQ_CONTENT_LENGTH_MISMATCH

UND_ERR_REQ_CONTENT_LENGTH_MISMATCH

Error message

Request body length does not match content-length header

What it means

Thrown by writeBlob() in client-h2.js (HTTP/2) as RequestContentLengthMismatchError. Same logic as the H1 path: when the body is a Blob, undici compares the declared content-length to body.size before writing; on mismatch it refuses to send a request whose frame data would contradict the header.

Source

Thrown at deps/undici/src/lib/dispatcher/client-h2.js:1660

          socket[kReset] = true
        }

        client[kResume]()
      }
    }
  )

  util.addListener(pipe, 'data', onPipeData)

  function onPipeData (chunk) {
    request.onBodySent(chunk)
  }
}

async function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
  try {
    if (contentLength != null && contentLength !== body.size) {
      throw new RequestContentLengthMismatchError()
    }

    const buffer = Buffer.from(await body.arrayBuffer())

    h2stream.cork()
    h2stream.write(buffer)
    h2stream.uncork()
    h2stream.end()

    request.onBodySent(buffer)
    request.onRequestSent()

    if (!expectsPayload) {
      socket[kReset] = true
    }

    client[kResume]()
  } catch (err) {

View on GitHub (pinned to 1b2de5e052)

Solutions

  1. Omit the content-length header for Blob bodies — undici derives it from body.size.
  2. If you set it manually, guarantee it equals blob.size byte-for-byte.
  3. Recompute the length from the same buffer referenced by the Blob.

Example fix

// before
await client.request({ method: 'POST', path: '/', body: blob, headers: { 'content-length': '100' } })
// after
await client.request({ method: 'POST', path: '/', body: blob })
Defensive patterns

Strategy: validation

Validate before calling

function h2BlobRequest(client, path, blob, headers = {}) {
  delete headers['content-length']
  return client.request({ method: 'POST', path, body: blob, headers })
}

Type guard

const lengthMatchesBlob = (headers, blob) => headers['content-length'] == null || Number(headers['content-length']) === blob.size

Try / catch

try { await client.request(req) } catch (e) { if (e.code === 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH') { delete req.headers['content-length']; /* retry */ } else throw e }

Prevention

When it happens

Trigger: An HTTP/2 request (Client constructed with allowH2 and target speaking h2) with body: Blob and a content-length header that does not equal blob.size.

Common situations: Same as the H1 case: hard-coded/cached content-length, a proxy rewriting the header, or a Blob rebuilt after the length was measured; only matters when the connection negotiates HTTP/2.

Related errors


AI-assisted analysis of nodejs/node@1b2de5e052 (2026-08-13). Data as JSON: /api/errors/02bb3e98acc20bd6. Report an issue: GitHub.