diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 24aae1caca69d3..2849a68a5e9979 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -977,6 +977,10 @@ function connectionCorkNT(conn) { } OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { + if (this.finished) { + throw new ERR_HTTP_HEADERS_SENT('set trailing'); + } + this._trailer = ''; const keys = ObjectKeys(headers); const isArray = ArrayIsArray(headers); diff --git a/test/parallel/test-http-outgoing-proto.js b/test/parallel/test-http-outgoing-proto.js index 2d265c7ba64968..fa57bd28a8362c 100644 --- a/test/parallel/test-http-outgoing-proto.js +++ b/test/parallel/test-http-outgoing-proto.js @@ -129,6 +129,16 @@ assert.throws(() => { message: 'Invalid character in trailer content ["404"]' }); +assert.throws(() => { + const outgoingMessage = new OutgoingMessage(); + outgoingMessage.finished = true; + outgoingMessage.addTrailers({ 'x-foo': 'bar' }); +}, { + code: 'ERR_HTTP_HEADERS_SENT', + name: 'Error', + message: 'Cannot set trailing headers after they are sent to the client' +}); + { const outgoingMessage = new OutgoingMessage(); assert.strictEqual(outgoingMessage.destroyed, false);