Response body size does not match Content-Length header
Production Risk
Produces malformed HTTP responses that can truncate or corrupt data seen by clients.
Thrown when an HTTP response is finalised with res.end() but the number of bytes actually written does not match the value declared in the Content-Length header. This mismatch would produce an invalid HTTP response that confuses clients and intermediaries.
- 1Content-Length was calculated from the wrong string (e.g. character count vs byte count for multi-byte UTF-8)
- 2The response body was modified after Content-Length was set
- 3Dynamic content that grew or shrank between the header calculation and the write
Triggered at res.end() when the byte count of all written data differs from the Content-Length header.
const http = require('http');
http.createServer((req, res) => {
const body = 'héllo'; // 6 bytes in UTF-8, not 5
res.writeHead(200, { 'Content-Length': '5' }); // wrong
res.end(body);
}).listen(3000);expected output
Error [ERR_HTTP_CONTENT_LENGTH_MISMATCH]: Response body's content-length mismatch
Fix 1
Use Buffer.byteLength() to compute Content-Length
WHEN Always when setting Content-Length for string bodies
const body = 'héllo';
const len = Buffer.byteLength(body, 'utf8'); // 6
res.writeHead(200, { 'Content-Length': String(len) });
res.end(body);Why this works
Buffer.byteLength() counts encoded bytes, not Unicode code units, giving the correct byte length.
Fix 2
Omit Content-Length and let Node use chunked encoding
WHEN When the body size is not known in advance
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('héllo'); // chunked, no mismatch possibleWhy this works
Without Content-Length the HTTP stack uses Transfer-Encoding: chunked, which never mismatches.
const http = require('http');
http.createServer((req, res) => {
const body = 'héllo'; // 6 bytes in UTF-8, not 5
res.writeHead(200, { 'Content-Length': '5' }); // wrong
res.end(body);
}).listen(3000); // this triggers ERR_HTTP_CONTENT_LENGTH_MISMATCHtry {
// operation that may throw ERR_HTTP_CONTENT_LENGTH_MISMATCH
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_CONTENT_LENGTH_MISMATCH') {
console.error('ERR_HTTP_CONTENT_LENGTH_MISMATCH:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_content_length_mismatch(...args) {
// validate args here
return performOperation(...args)
}✕ Use string.length as the Content-Length for UTF-8 encoded text
String length counts characters, not bytes; multi-byte characters will produce a mismatch.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev