{"record":{"id":"e2f04bfaae9ed5b7","repo":"denoland/deno","slug":"err-http-content-length-mismatch","errorCode":"ERR_HTTP_CONTENT_LENGTH_MISMATCH","errorMessage":"Response body's content-length of ${this[kBytesWritten]} byte(s) does not match the content-length of ${this._contentLength} byte(s) set in header","messagePattern":"Response body's content-length of (.+?) byte\\(s\\) does not match the content-length of (.+?) byte\\(s\\) set in header","errorType":"error_code","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"ext/node/polyfills/_http_outgoing.ts","lineNumber":615,"sourceCode":"        return this;\n      } else if (!this._header) {\n        if (this.socket) {\n          this.socket.cork();\n        }\n\n        this._contentLength = 0;\n        this._implicitHeader();\n      }\n\n      if (typeof callback === \"function\") {\n        this.once(\"finish\", callback);\n      }\n\n      if (\n        _checkStrictContentLength(this) &&\n        this[kBytesWritten] !== this._contentLength\n      ) {\n        throw new ERR_HTTP_CONTENT_LENGTH_MISMATCH(\n          this[kBytesWritten],\n          this._contentLength,\n        );\n      }\n\n      const finish = FunctionPrototypeBind(onFinish, undefined, this);\n\n      if (this._hasBody && this.chunkedEncoding) {\n        this._send(\"0\\r\\n\" + this._trailer + \"\\r\\n\", \"latin1\", finish);\n      } else if (!this._headerSent || this.writableLength || chunk) {\n        this._send(\"\", \"latin1\", finish);\n      } else {\n        (globalThis as any).process.nextTick(finish);\n      }\n\n      if (this.socket) {\n        // Fully uncork connection on end().\n        this.socket._writableState.corked = 1;","sourceCodeStart":597,"sourceCodeEnd":633,"githubUrl":"https://github.com/denoland/deno/blob/9ad36f7a2cce60488e6ec52283efb32efddaf93a/ext/node/polyfills/_http_outgoing.ts#L597-L633","documentation":"Thrown by OutgoingMessage.prototype.end() when strictContentLength is enabled and the number of body bytes actually written (this[kBytesWritten]) does not equal the content-length advertised in the header (this._contentLength). The check (_checkStrictContentLength) only applies when a content-length is set, the message has a body, is not chunked, and the content-length header was not removed. It exists to prevent sending responses whose declared length lies about the actual body size.","triggerScenarios":"res.strictContentLength = true (or the server sets it), then res.setHeader('content-length', N), write some bytes, and res.end() with a total != N. Example: setHeader('content-length', 10); res.write('hello'); res.end() -> 5 != 10.","commonSituations":"Manually setting content-length and then streaming a body whose size drifts (compression, encoding changes, transforms); computing length with .length instead of Buffer.byteLength for multi-byte strings; enabling strictContentLength (a Node >= 18 flag/property adopted by Deno's polyfill) on code that previously relied on lenient behavior; writing Buffer vs string and mixing up byte vs char counts.","solutions":["Compute the length with Buffer.byteLength(body, encoding) (or buf.byteLength) from the exact value you will write/end with, and set that as content-length.","Drop the manual content-length header and let the runtime pick the length (end(body) on a fresh response) or use chunked transfer encoding.","If the mismatch is intentional during migration/testing, set msg.strictContentLength = false to restore lenient Node default behavior.","Audit middleware (compression, byte counting) that rewrites the body after the header was sized."],"exampleFix":"// before\nres.setHeader('content-length', 10); // guessed\nres.write('héllo'); // 6 bytes, not 5\nres.end();\n\n// after\nconst body = 'héllo';\nres.setHeader('content-length', Buffer.byteLength(body));\nres.end(body);","handlingStrategy":"validation","validationCode":"// before ending, confirm the byte totals agree when strictness is on\nconst written = Number(res.getHeader('content-length'));\nif (res.strictContentLength && written !== null && bodyLength !== written) {\n  res.removeHeader('content-length'); // fall back to chunked\n}\nres.end(body);","typeGuard":null,"tryCatchPattern":"try {\n  res.end(body);\n} catch (err) {\n  if (err.code === 'ERR_HTTP_CONTENT_LENGTH_MISMATCH') {\n    // header already flushed: close connection so client sees a clean truncation\n    res.socket?.destroy();\n  } else throw err;\n}","preventionTips":["Always derive content-length from the exact bytes you pass to end(): Buffer.byteLength(str, encoding) or buf.byteLength.","Never set content-length manually on streams whose length can change; use chunked encoding instead.","Enable strictContentLength in tests to catch length bugs before production does."],"tags":["http","node-compat","content-length","stream"],"backgroundTag":"content-length-mismatch","analyzedSha":"9ad36f7a2cce60488e6ec52283efb32efddaf93a","analyzedAt":"2026-08-20T13:07:44.778Z","contentChangedAt":"2026-08-20T13:07:44.778Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}