HTTP trailer set without chunked transfer encoding
Production Risk
Causes the response to fail; trailers are rarely needed but must be used correctly.
Thrown when response.addTrailers() is called but the response does not use chunked transfer encoding. HTTP trailers (headers sent after the body) are only valid in chunked responses. If the Content-Length header was set explicitly, chunked encoding is disabled and trailers cannot be used.
- 1Calling res.addTrailers() on a response that has an explicit Content-Length header
- 2The response body was set in a way that disabled chunked encoding
- 3Misunderstanding that trailers require Transfer-Encoding: chunked
Triggered when addTrailers() is called on an HTTP response that is not using chunked transfer encoding.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Length': '5' });
res.write('hello');
res.addTrailers({ 'X-Checksum': 'abc' }); // throws
res.end();
}).listen(3000);expected output
Error [ERR_HTTP_TRAILER_INVALID]: Trailers are invalid with this transfer encoding
Fix
Remove Content-Length and use chunked encoding
WHEN When you need to send trailers
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Trailer': 'X-Checksum' });
res.write('hello');
res.addTrailers({ 'X-Checksum': 'abc123' });
res.end();
}).listen(3000);Why this works
Omitting Content-Length allows chunked encoding, which is required for HTTP trailers.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Length': '5' });
res.write('hello');
res.addTrailers({ 'X-Checksum': 'abc' }); // throws
res.end(); // this triggers ERR_HTTP_TRAILER_INVALIDtry {
// operation that may throw ERR_HTTP_TRAILER_INVALID
riskyOperation()
} catch (err) {
if (err.code === 'ERR_HTTP_TRAILER_INVALID') {
console.error('ERR_HTTP_TRAILER_INVALID:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_http_trailer_invalid(...args) {
// validate args here
return performOperation(...args)
}✕ Set Content-Length and also call addTrailers()
Content-Length disables chunked encoding, making trailers invalid per the HTTP spec.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev