Course contentsShow
← Node.js
Lesson 537 of 1,9806. Networking and HTTP FundamentalsFree lesson

Trailer Headers in HTTP/1.1

Utilize trailer headers to append metadata after chunked response bodies are sent.

In this lesson, you will learn how to use trailer headers to send metadata after the main body of an HTTP/1.1 response has already been delivered.

The Concept of Trailers

Normally, all HTTP headers must be sent before the response body begins. However, when you use Transfer-Encoding: chunked, the server sends the data in small, sequential pieces. Because the server might not know the final value of a specific piece of metadata (like a calculated checksum or a digital signature) until the very last byte of data is processed, HTTP/1.1 allows for Trailer headers.

Think of trailers as "post-scripts" for your HTTP response. They allow you to append header fields at the very end of the chunked stream, after the data chunks have finished but before the connection closes.

How It Works in Practice

To notify the client that trailers are coming, you must include a special header in your initial response: Trailer. This header lists the names of the fields that will appear at the end.

Imagine you are generating a large report and calculating a hash as you stream it:

// Initial headers
response.writeHead(200, {
  'Content-Type': 'text/plain',
  'Transfer-Encoding': 'chunked',
  'Trailer': 'Content-MD5' // Tell the client to expect this trailer
});

// Send your data chunks here...

// Finally, add the trailer
response.addTrailers({ 'Content-MD5': '789abc...' });
response.end();

Why Use Them?

Trailers are highly useful for "on-the-fly" processing. By waiting to send these headers until the end of the stream, you avoid the need to buffer the entire response in memory just to calculate a total size or a checksum upfront.

It is important to note that not all HTTP clients are configured to parse trailers by default, as they require the receiver to keep the response "open" until the final chunk is verified. When implementing this, ensure your client-side logic is prepared to buffer and inspect these specific trailing fields after the response body has been received.

Key Takeaway: Trailer headers allow you to append metadata to the end of a chunked HTTP/1.1 response, enabling the inclusion of data that can only be computed after the entire response body has been processed.