ERR_HTTP_TRAILER_INVALID
Node.jsERRORNotableHTTPHIGH confidence

HTTP trailer set without chunked transfer encoding

Production Risk

Causes the response to fail; trailers are rarely needed but must be used correctly.

What this means

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.

Why it happens
  1. 1Calling res.addTrailers() on a response that has an explicit Content-Length header
  2. 2The response body was set in a way that disabled chunked encoding
  3. 3Misunderstanding that trailers require Transfer-Encoding: chunked
How to reproduce

Triggered when addTrailers() is called on an HTTP response that is not using chunked transfer encoding.

trigger — this will error
trigger — this will error
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

Remove Content-Length and use chunked encoding
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.

Code examples
Triggerjs
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_INVALID
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_http_trailer_invalid(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Set Content-Length and also call addTrailers()

Content-Length disables chunked encoding, making trailers invalid per the HTTP spec.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors