Commit 984728738b3 for nodejs

commit 984728738b37725df2efeb72410395a5cd82f666
Author: Sebastian Beltran <bjohansebas@gmail.com>
Date:   Sat Nov 28 11:16:37 2026 -0500

    http: add 'sendingHeaders' event for response header manipulation

    Signed-off-by: Sebastian Beltran <bjohansebas@gmail.com>
    Assisted-by: Codex
    PR-URL: https://github.com/nodejs/node/pull/63996
    Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/doc/api/http.md b/doc/api/http.md
index 42a7a59d69d..f3702f6997a 100644
--- a/doc/api/http.md
+++ b/doc/api/http.md
@@ -2099,6 +2099,63 @@ emitted when the last segment of the response headers and body have been
 handed off to the operating system for transmission over the network. It
 does not imply that the client has received anything yet.

+### Event: `'sendingHeaders'`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+Emitted synchronously, exactly once, immediately before the status line and
+response headers are serialized and sent to the client. The listener is called
+with `this` bound to the response.
+
+This is the moment at which the response is about to become committed: when the
+event fires, [`response.headersSent`][] is still `false`, so a listener may make
+final changes to the outgoing message. From inside the listener it is valid to:
+
+* read headers with [`response.getHeader()`][] / [`response.getHeaders()`][];
+* add, replace, or remove headers with [`response.setHeader()`][],
+  [`outgoingMessage.appendHeader()`][], and [`response.removeHeader()`][];
+* change [`response.statusCode`][] and [`response.statusMessage`][].
+
+The event is emitted regardless of how the headers are flushed: an explicit call
+to [`response.writeHead()`][], implicit headers triggered by the first
+[`response.write()`][] or [`response.end()`][], or [`response.flushHeaders()`][].
+Because it is a single emission point, multiple independent listeners (for
+example logging, session, and content-negotiation middleware) can each register
+without coordinating with one another. Listeners run in registration order.
+
+The listener runs synchronously and must not be an `async` function: work
+deferred past an `await` runs after the headers are already sent, so only
+changes made synchronously take effect.
+
+```js
+const server = http.createServer((req, res) => {
+  const startTime = Date.now();
+
+  res.on('sendingHeaders', function() {
+    // Set a header at the last possible moment, based on final state.
+    this.setHeader('X-Response-Time', `${Date.now() - startTime}ms`);
+    if (!this.getHeader('Content-Type')) {
+      this.setHeader('Content-Type', 'text/plain');
+    }
+  });
+
+  res.end('hello');
+});
+```
+
+A header passed inline to `response.writeHead()` is visible to the listener and
+can be modified there, including the array form:
+
+```js
+res.on('sendingHeaders', function() {
+  // 'X-Inline' was passed to writeHead() below; it can still be removed here.
+  this.removeHeader('X-Inline');
+});
+res.writeHead(200, ['X-Inline', 'value', 'Content-Type', 'text/plain']);
+```
+
 ### `response.addTrailers(headers)`

 <!-- YAML
@@ -5000,6 +5057,7 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
 [`net.Socket`]: net.md#class-netsocket
 [`net.createConnection()`]: net.md#netcreateconnectionoptions-connectlistener
 [`new URL()`]: url.md#new-urlinput-base
+[`outgoingMessage.appendHeader()`]: #outgoingmessageappendheadername-value
 [`outgoingMessage.setHeader(name, value)`]: #outgoingmessagesetheadername-value
 [`outgoingMessage.setHeaders()`]: #outgoingmessagesetheadersheaders
 [`outgoingMessage.socket`]: #outgoingmessagesocket
@@ -5017,9 +5075,15 @@ const agent2 = new http.Agent({ proxyEnv: process.env });
 [`request.writableFinished`]: #requestwritablefinished
 [`request.write(data, encoding)`]: #requestwritechunk-encoding-callback
 [`response.end()`]: #responseenddata-encoding-callback
+[`response.flushHeaders()`]: #responseflushheaders
 [`response.getHeader()`]: #responsegetheadername
+[`response.getHeaders()`]: #responsegetheaders
+[`response.headersSent`]: #responseheaderssent
+[`response.removeHeader()`]: #responseremoveheadername
 [`response.setHeader()`]: #responsesetheadername-value
 [`response.socket`]: #responsesocket
+[`response.statusCode`]: #responsestatuscode
+[`response.statusMessage`]: #responsestatusmessage
 [`response.strictContentLength`]: #responsestrictcontentlength
 [`response.writableEnded`]: #responsewritableended
 [`response.writableFinished`]: #responsewritablefinished
diff --git a/doc/api/http2.md b/doc/api/http2.md
index a3c1f1cbf02..ade269150da 100644
--- a/doc/api/http2.md
+++ b/doc/api/http2.md
@@ -4663,6 +4663,29 @@ does not imply that the client has received anything yet.

 After this event, no more events will be emitted on the response object.

+#### Event: `'sendingHeaders'`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+Emitted synchronously, exactly once, immediately before the response headers are
+serialized and the `HEADERS` frame is sent. The listener is called with `this`
+bound to the response, while `response.headersSent` is still `false`, so it may
+make final changes to the outgoing message: read or modify headers with
+[`response.setHeader()`][], `response.appendHeader()`, and
+`response.removeHeader()`, or change `response.statusCode`.
+
+The event is reached by every header-flushing path
+([`response.writeHead()`][], implicit headers from the first
+[`response.write()`][] or [`response.end()`][], and `response.flushHeaders()`),
+so independent middleware can each register a listener without coordinating.
+Listeners run in registration order and must be synchronous; changes deferred
+past an `await` run after the headers are already sent and have no effect.
+
+This is the HTTP/2 counterpart of the HTTP/1
+[`'sendingHeaders'`](http.md#event-sendingheaders) event.
+
 #### `response.addTrailers(headers)`

 <!-- YAML
diff --git a/lib/internal/http/server.js b/lib/internal/http/server.js
index fe870c47144..a7de292987b 100644
--- a/lib/internal/http/server.js
+++ b/lib/internal/http/server.js
@@ -23,6 +23,7 @@

 const {
   ArrayIsArray,
+  ArrayPrototypeSlice,
   Error,
   MathMin,
   NumberIsFinite,
@@ -118,6 +119,7 @@ const onResponseFinishChannel = dc.channel('http.server.response.finish');
 const kServerResponse = Symbol('ServerResponse');
 const kServerResponseStatistics = Symbol('ServerResponseStatistics');
 const kUpgradeStream = Symbol('UpgradeStream');
+const kSendingHeadersEmitted = Symbol('SendingHeadersEmitted');

 const kOptimizeEmptyRequests = Symbol('OptimizeEmptyRequestsOption');
 const kConnectionState = Symbol('ConnectionState');
@@ -227,6 +229,8 @@ function ServerResponse(req, options) {
   this.sendDate = true;
   this._sent100 = false;
   this._expect_continue = false;
+  // Guards the one-shot 'sendingHeaders' emit against re-entrancy.
+  this[kSendingHeadersEmitted] = false;

   if (req.httpVersionMajor < 1 || req.httpVersionMinor < 1) {
     this.useChunkedEncodingByDefault =
@@ -437,18 +441,22 @@ function writeHead(statusCode, reason, obj) {
   }


-  if (typeof reason === 'string') {
+  const hasExplicitReason = typeof reason === 'string';
+  if (hasExplicitReason) {
     // writeHead(statusCode, reasonPhrase[, headers])
     this.statusMessage = reason;
   } else {
     // writeHead(statusCode[, headers])
-    this.statusMessage ||= STATUS_CODES[statusCode] || 'unknown';
     obj ??= reason;
   }
   this.statusCode = statusCode;

+  // With a 'sendingHeaders' listener, always materialize kOutHeaders (including
+  // inline writeHead() headers) so the listener sees one mutable header view.
+  const hasHeadersListeners = this.listenerCount('sendingHeaders') > 0;
+
   let headers;
-  if (this[kOutHeaders]) {
+  if (this[kOutHeaders] || hasHeadersListeners) {
     // Slow-case: when progressive API and header fields are passed.
     let k;
     if (ArrayIsArray(obj)) {
@@ -467,15 +475,28 @@ function writeHead(statusCode, reason, obj) {

       for (let n = 0; n < obj.length; n += 2) {
         k = obj[n + 0];
-        if (k) this.appendHeader(k, obj[n + 1]);
+        if (!k) continue;
+        const value = obj[n + 1];
+        // Appending duplicate fields must not mutate caller-owned arrays.
+        this.appendHeader(k, ArrayIsArray(value) ? ArrayPrototypeSlice(value) : value);
       }
     } else if (obj) {
       const keys = ObjectKeys(obj);
+      // Preserve duplicate fields when only the listener requires headers to
+      // be cached. Existing cached headers retain their overwrite semantics.
+      const appendHeaders = !this[kOutHeaders];
       // Retain for(;;) loop for performance reasons
       // Refs: https://github.com/nodejs/node/pull/30958
       for (let i = 0; i < keys.length; i++) {
         k = keys[i];
-        if (k) this.setHeader(k, obj[k]);
+        if (!k) continue;
+        const value = obj[k];
+        if (appendHeaders) {
+          // Appending duplicate fields must not mutate caller-owned arrays.
+          this.appendHeader(k, ArrayIsArray(value) ? ArrayPrototypeSlice(value) : value);
+        } else {
+          this.setHeader(k, value);
+        }
       }
     }
     // Only progressive api is used
@@ -485,6 +506,39 @@ function writeHead(statusCode, reason, obj) {
     headers = obj;
   }

+  // Pre-serialization hook, reached by every path (writeHead(), implicit
+  // headers, flushHeaders()): listeners run synchronously right before the
+  // status line and headers are serialized and may still mutate them.
+  if (hasHeadersListeners && !this[kSendingHeadersEmitted]) {
+    // Clear an implicit empty reason so a listener can explicitly set one.
+    if (!hasExplicitReason && this.statusMessage === '') {
+      this.statusMessage = undefined;
+    }
+    this[kSendingHeadersEmitted] = true;
+    this.emit('sendingHeaders');
+
+    // A listener that flushed the headers itself re-entered writeHead(); the
+    // guard stops a re-emit, but serializing again would double the header
+    // block, so fail like a second writeHead() call.
+    if (this._header) {
+      throw new ERR_HTTP_HEADERS_SENT('write');
+    }
+
+    // Re-read state; `res.statusCode` isn't validated on assignment.
+    headers = this[kOutHeaders];
+    statusCode = this.statusCode | 0;
+    if (statusCode < 100 || statusCode > 999) {
+      throw new ERR_HTTP_INVALID_STATUS_CODE(statusCode);
+    }
+  }
+
+  // Default from the final status code, preserving empty reasons explicitly
+  // supplied to writeHead() or chosen after 'sendingHeaders' started.
+  if (!hasExplicitReason && !this.statusMessage &&
+      (this.statusMessage !== '' || !this[kSendingHeadersEmitted])) {
+    this.statusMessage = STATUS_CODES[statusCode] || 'unknown';
+  }
+
   let statusLine;
   if (this.statusMessage === STATUS_CODES[statusCode]) {
     // Default reason phrases contain no invalid characters and are shared
diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js
index 7b7054b072e..73a1ec98462 100644
--- a/lib/internal/http2/compat.js
+++ b/lib/internal/http2/compat.js
@@ -547,6 +547,7 @@ class Http2ServerResponse extends Stream {
       headRequest: false,
       sendDate: true,
       statusCode: HTTP_STATUS_OK,
+      sendingHeadersEmitted: false,
     };
     this[kHeaders] = { __proto__: null };
     this[kTrailers] = { __proto__: null };
@@ -902,6 +903,20 @@ class Http2ServerResponse extends Stream {
     }

     state.statusCode = statusCode;
+
+    // Pre-serialization hook mirroring the HTTP/1 'sendingHeaders' event:
+    // listeners run synchronously right before the HEADERS frame is sent.
+    if (this.listenerCount('sendingHeaders') > 0 &&
+        !state.sendingHeadersEmitted) {
+      state.sendingHeadersEmitted = true;
+      this.emit('sendingHeaders');
+
+      // A listener that flushed the headers itself re-entered writeHead(); the
+      // guard stops a re-emit, but sending the HEADERS frame again is invalid.
+      if (this[kStream].headersSent)
+        throw new ERR_HTTP2_HEADERS_SENT();
+    }
+
     this[kBeginSend]();

     return this;
diff --git a/test/parallel/test-http-sending-headers-array-reuse.js b/test/parallel/test-http-sending-headers-array-reuse.js
new file mode 100644
index 00000000000..526cedc6b62
--- /dev/null
+++ b/test/parallel/test-http-sending-headers-array-reuse.js
@@ -0,0 +1,53 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const http = require('http');
+
+for (const withListener of [false, true]) {
+  for (const withStoredHeaders of [false, true]) {
+    for (const frozen of [false, true]) {
+      const cookies = ['a=1'];
+      if (frozen) Object.freeze(cookies);
+      const headers = ['Set-Cookie', cookies, 'set-cookie', 'b=2'];
+      const expected = ['a=1', 'b=2'];
+      let remaining = 2;
+
+      // Reusing the same inline headers must not accumulate duplicate values
+      // across responses or require the caller's arrays to be mutable.
+      const server = http.createServer(common.mustCall((req, res) => {
+        if (withStoredHeaders) {
+          res.setHeader('Set-Cookie', ['old=1']);
+          res.setHeader('X-Stored', 'keep');
+        }
+        if (withListener) {
+          res.on('sendingHeaders', common.mustCall(function() {
+            assert.deepStrictEqual(this.getHeader('set-cookie'), expected);
+          }));
+        }
+        res.writeHead(200, headers);
+        res.end();
+        assert.deepStrictEqual(headers, [
+          'Set-Cookie', ['a=1'], 'set-cookie', 'b=2',
+        ]);
+      }, remaining));
+
+      function request() {
+        http.get({ port: server.address().port }, common.mustCall((res) => {
+          assert.deepStrictEqual(res.headers['set-cookie'], expected);
+          assert.strictEqual(res.headers['x-stored'],
+                             withStoredHeaders ? 'keep' : undefined);
+          res.resume().on('end', common.mustCall(() => {
+            if (--remaining > 0) {
+              request();
+            } else {
+              server.close();
+            }
+          }));
+        }));
+      }
+
+      server.listen(0, common.mustCall(request));
+    }
+  }
+}
diff --git a/test/parallel/test-http-sending-headers-duplicates.js b/test/parallel/test-http-sending-headers-duplicates.js
new file mode 100644
index 00000000000..f62b0df59d9
--- /dev/null
+++ b/test/parallel/test-http-sending-headers-duplicates.js
@@ -0,0 +1,47 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const http = require('http');
+
+for (const withListener of [false, true]) {
+  for (const withStoredHeaders of [false, true]) {
+    for (const arrayValues of [false, true]) {
+      const headers = {
+        'Set-Cookie': arrayValues ? ['a=1'] : 'a=1',
+        'set-cookie': arrayValues ? ['b=2'] : 'b=2',
+      };
+      // Inline headers override stored headers. Without stored headers, both
+      // differently cased fields are sent, even when a listener is present.
+      const expected = withStoredHeaders ? ['b=2'] : ['a=1', 'b=2'];
+      const server = http.createServer(common.mustCall((req, res) => {
+        if (withStoredHeaders) {
+          res.setHeader('Set-Cookie', 'old=1');
+          res.setHeader('X-Stored', 'keep');
+        }
+        if (withListener) {
+          res.on('sendingHeaders', common.mustCall(function() {
+            const cookies = this.getHeader('set-cookie');
+            assert.deepStrictEqual(
+              Array.isArray(cookies) ? cookies : [cookies], expected);
+          }));
+        }
+        res.writeHead(200, headers);
+        res.end();
+        assert.deepStrictEqual(headers, {
+          'Set-Cookie': arrayValues ? ['a=1'] : 'a=1',
+          'set-cookie': arrayValues ? ['b=2'] : 'b=2',
+        });
+      }));
+
+      server.listen(0, common.mustCall(() => {
+        http.get({ port: server.address().port }, common.mustCall((res) => {
+          assert.deepStrictEqual(res.headers['set-cookie'], expected);
+          assert.strictEqual(res.headers['x-stored'],
+                             withStoredHeaders ? 'keep' : undefined);
+          res.resume().on('end', common.mustCall(() => server.close()));
+        }));
+      }));
+    }
+  }
+}
diff --git a/test/parallel/test-http-sending-headers-empty-status-message.js b/test/parallel/test-http-sending-headers-empty-status-message.js
new file mode 100644
index 00000000000..6a46ab8c242
--- /dev/null
+++ b/test/parallel/test-http-sending-headers-empty-status-message.js
@@ -0,0 +1,72 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const http = require('http');
+
+for (const initialMessage of [undefined, '', 'Before']) {
+  for (const method of ['writeHead', 'write', 'end', 'flushHeaders']) {
+    const server = http.createServer(common.mustCall((req, res) => {
+      res.statusMessage = initialMessage;
+      res.once('sendingHeaders', common.mustCall(function() {
+        this.statusCode = 503;
+        this.statusMessage = '';
+      }));
+
+      switch (method) {
+        case 'writeHead':
+          res.writeHead(200);
+          break;
+        case 'write':
+          res.write('body');
+          break;
+        case 'flushHeaders':
+          res.flushHeaders();
+          break;
+      }
+      res.end();
+      assert.strictEqual(res.statusMessage, '');
+    }));
+
+    server.listen(0, common.mustCall(() => {
+      http.get({ port: server.address().port }, common.mustCall((res) => {
+        assert.strictEqual(res.statusCode, 503);
+        assert.strictEqual(res.statusMessage, '');
+        res.resume().on('end', common.mustCall(() => server.close()));
+      }));
+    }));
+  }
+}
+
+// An unchanged implicit reason still defaults to the final status code.
+for (const initialMessage of [undefined, null, false, 0, '']) {
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.statusMessage = initialMessage;
+    res.once('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+    }));
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 503);
+      assert.strictEqual(res.statusMessage, 'Service Unavailable');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// The nested writeHead() must also preserve an empty reason chosen by the
+// listener, while the outer call still rejects flushing from inside the hook.
+{
+  const res = new http.ServerResponse({
+    method: 'GET', httpVersionMajor: 1, httpVersionMinor: 1,
+  });
+  res.once('sendingHeaders', common.mustCall(function() {
+    this.statusMessage = '';
+    this.flushHeaders();
+  }));
+  assert.throws(() => res.writeHead(200), { code: 'ERR_HTTP_HEADERS_SENT' });
+  assert.strictEqual(res.statusMessage, '');
+}
diff --git a/test/parallel/test-http-sending-headers.js b/test/parallel/test-http-sending-headers.js
new file mode 100644
index 00000000000..948949a3ff0
--- /dev/null
+++ b/test/parallel/test-http-sending-headers.js
@@ -0,0 +1,261 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('assert');
+const http = require('http');
+
+// 1) Fires once, before serialization, for an implicit-header response (end()).
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    let fired = 0;
+    res.on('sendingHeaders', common.mustCall(function() {
+      fired++;
+      // Headers not yet sent, still mutable.
+      assert.strictEqual(this.headersSent, false);
+      this.setHeader('X-Added-In-Hook', 'yes');
+    }));
+    res.end('body');
+    // Synchronous: hook has already run by the time end() returns.
+    assert.strictEqual(fired, 1);
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.headers['x-added-in-hook'], 'yes');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 2) Listener may change the status code, and it is reflected on the wire.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+      this.statusMessage = 'Service Unavailable';
+    }));
+    res.writeHead(200);
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 503);
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 3) Listener sees and can remove headers passed INLINE to writeHead(),
+//    including the array form.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      assert.strictEqual(this.getHeader('X-Inline'), 'a');
+      this.removeHeader('X-Inline');
+      this.setHeader('X-From-Hook', 'b');
+    }));
+    res.writeHead(200, ['X-Inline', 'a', 'Content-Type', 'text/plain']);
+    res.end('ok');
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.headers['x-inline'], undefined);
+      assert.strictEqual(res.headers['x-from-hook'], 'b');
+      assert.strictEqual(res.headers['content-type'], 'text/plain');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 4) Multiple listeners all run (FIFO, EventEmitter semantics).
+{
+  const order = [];
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(() => order.push(1)));
+    res.on('sendingHeaders', common.mustCall(() => order.push(2)));
+    res.end();
+    assert.deepStrictEqual(order, [1, 2]);
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 5) flushHeaders() also triggers the hook exactly once.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.setHeader('X-Flushed', '1');
+    }));
+    res.flushHeaders();
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.headers['x-flushed'], '1');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 6) The hook is synchronous: only changes made before an `await` take effect.
+//    Work deferred past `await` runs after the headers are sent, so a later
+//    setHeader() throws and a statusCode change is not reflected on the wire.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(async function() {
+      this.setHeader('X-Sync', 'before');
+      await null;
+      assert.strictEqual(this.headersSent, true);
+      this.statusCode = 503; // No effect: headers already sent.
+      assert.throws(() => this.setHeader('X-Async', 'after'), {
+        code: 'ERR_HTTP_HEADERS_SENT',
+      });
+      server.close();
+    }));
+    res.end('hello');
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 200);
+      assert.strictEqual(res.headers['x-sync'], 'before');
+      assert.strictEqual(res.headers['x-async'], undefined);
+      res.resume();
+    }));
+  }));
+}
+
+// 7) A listener that flushes the headers itself re-enters writeHead(). The emit
+//    is guarded so the event still fires exactly once (common.mustCall below),
+//    and the illegal self-flush surfaces as ERR_HTTP_HEADERS_SENT rather than a
+//    stack overflow.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.flushHeaders();
+    }));
+    assert.throws(() => res.end('hello'), { code: 'ERR_HTTP_HEADERS_SENT' });
+    res.destroy();
+    server.close();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const req = http.get({ port: server.address().port });
+    req.on('response', (res) => res.resume());
+    req.on('error', () => {}); // The reset from destroy() is expected
+  }));
+}
+
+// 8) A listener that changes only the status code gets the reason phrase that
+//    matches the final code (not the one defaulted from the original code).
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503; // statusMessage intentionally left unset
+    }));
+    res.writeHead(200);
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 503);
+      assert.strictEqual(res.statusMessage, 'Service Unavailable');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 9) An explicit empty reason phrase is preserved (the deferred status-line
+//    default must not overwrite it), and the listener sees the empty phrase.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      assert.strictEqual(this.statusMessage, '');
+    }));
+    res.writeHead(200, '');
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 200);
+      assert.strictEqual(res.statusMessage, '');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 10) A listener may set a reason phrase that happens to equal a status-code
+//     default while changing the code; the explicit choice is kept (the derived
+//     phrase is only applied when none was set, detected via `=== undefined`).
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+      this.statusMessage = 'OK'; // Explicit, equals the 200 default
+    }));
+    res.writeHead(200);
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 503);
+      assert.strictEqual(res.statusMessage, 'OK');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 11) A listener that sets its own reason phrase keeps it, even when it also
+//     changes the status code (the refresh only touches the auto-derived one).
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+      this.statusMessage = 'Custom Reason';
+    }));
+    res.writeHead(200);
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    http.get({ port: server.address().port }, common.mustCall((res) => {
+      assert.strictEqual(res.statusCode, 503);
+      assert.strictEqual(res.statusMessage, 'Custom Reason');
+      res.resume().on('end', common.mustCall(() => server.close()));
+    }));
+  }));
+}
+
+// 12) A listener that changes the status code and flushes the headers itself
+//     re-enters writeHead(); the reason phrase is derived on that path too, so
+//     it matches the final code (not a stale one). The illegal self-flush still
+//     throws ERR_HTTP_HEADERS_SENT.
+{
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+      this.flushHeaders();
+    }));
+    assert.throws(() => res.end('x'), { code: 'ERR_HTTP_HEADERS_SENT' });
+    // The re-entrant writeHead() derived the reason phrase for the final code.
+    assert.strictEqual(res.statusMessage, 'Service Unavailable');
+    res.destroy();
+    server.close();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const req = http.get({ port: server.address().port });
+    req.on('response', (res) => res.resume());
+    req.on('error', () => {}); // The reset from destroy() is expected
+  }));
+}
diff --git a/test/parallel/test-http-status-message.js b/test/parallel/test-http-status-message.js
index 6023e3c984e..d55108fcb86 100644
--- a/test/parallel/test-http-status-message.js
+++ b/test/parallel/test-http-status-message.js
@@ -56,3 +56,23 @@ function test() {
     s.close();
   }));
 }
+
+for (const falsy of [null, 0, false, '']) {
+  const server = http.createServer(common.mustCall((req, res) => {
+    res.statusMessage = falsy;
+    res.end('');
+  }));
+
+  server.listen(0, common.mustCall(function() {
+    const client = net.connect(this.address().port, () => {
+      client.write('GET / HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
+    });
+    const bufs = [];
+    client.on('data', (chunk) => bufs.push(chunk));
+    client.on('end', common.mustCall(() => {
+      const head = Buffer.concat(bufs).toString('latin1').split('\r\n')[0];
+      assert.strictEqual(head, 'HTTP/1.1 200 OK');
+      server.close();
+    }));
+  }));
+}
diff --git a/test/parallel/test-http2-compat-serverresponse-sending-headers.js b/test/parallel/test-http2-compat-serverresponse-sending-headers.js
new file mode 100644
index 00000000000..8da06595373
--- /dev/null
+++ b/test/parallel/test-http2-compat-serverresponse-sending-headers.js
@@ -0,0 +1,199 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+  common.skip('missing crypto');
+const assert = require('assert');
+const http2 = require('http2');
+
+// The 'sendingHeaders' event on the HTTP/2 compatibility ServerResponse mirrors
+// the one on the HTTP/1 ServerResponse: it is emitted synchronously, exactly
+// once, immediately before the HEADERS frame is sent, and a listener may still
+// mutate headers and the status code.
+
+// 1) Fires once, before serialization, for an implicit-header response (end()).
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    let fired = 0;
+    res.on('sendingHeaders', common.mustCall(function() {
+      fired++;
+      // Headers not yet sent, still mutable.
+      assert.strictEqual(this.headersSent, false);
+      this.setHeader('X-Added-In-Hook', 'yes');
+    }));
+    res.end('body');
+    // Synchronous: hook has already run by the time end() returns.
+    assert.strictEqual(fired, 1);
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.on('response', common.mustCall((headers) => {
+      assert.strictEqual(headers['x-added-in-hook'], 'yes');
+    }));
+    req.resume();
+    req.on('end', common.mustCall(() => {
+      client.close();
+      server.close();
+    }));
+    req.end();
+  }));
+}
+
+// 2) Listener may change the status code, and it is reflected on the wire.
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.statusCode = 503;
+    }));
+    res.writeHead(200);
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.on('response', common.mustCall((headers) => {
+      assert.strictEqual(headers[':status'], 503);
+    }));
+    req.resume();
+    req.on('end', common.mustCall(() => {
+      client.close();
+      server.close();
+    }));
+    req.end();
+  }));
+}
+
+// 3) Listener sees and can remove headers passed INLINE to writeHead(),
+//    including the array form.
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      assert.strictEqual(this.getHeader('X-Inline'), 'a');
+      this.removeHeader('X-Inline');
+      this.setHeader('X-From-Hook', 'b');
+    }));
+    res.writeHead(200, ['X-Inline', 'a', 'Content-Type', 'text/plain']);
+    res.end('ok');
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.on('response', common.mustCall((headers) => {
+      assert.strictEqual(headers['x-inline'], undefined);
+      assert.strictEqual(headers['x-from-hook'], 'b');
+      assert.strictEqual(headers['content-type'], 'text/plain');
+    }));
+    req.resume();
+    req.on('end', common.mustCall(() => {
+      client.close();
+      server.close();
+    }));
+    req.end();
+  }));
+}
+
+// 4) Multiple listeners all run (FIFO, EventEmitter semantics).
+{
+  const order = [];
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(() => order.push(1)));
+    res.on('sendingHeaders', common.mustCall(() => order.push(2)));
+    res.end();
+    assert.deepStrictEqual(order, [1, 2]);
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.resume();
+    req.on('end', common.mustCall(() => {
+      client.close();
+      server.close();
+    }));
+    req.end();
+  }));
+}
+
+// 5) flushHeaders() also triggers the hook exactly once.
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.setHeader('X-Flushed', '1');
+    }));
+    res.flushHeaders();
+    res.end();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.on('response', common.mustCall((headers) => {
+      assert.strictEqual(headers['x-flushed'], '1');
+    }));
+    req.resume();
+    req.on('end', common.mustCall(() => {
+      client.close();
+      server.close();
+    }));
+    req.end();
+  }));
+}
+
+// 6) The hook is synchronous: only changes made before an `await` take effect.
+//    Work deferred past `await` runs after the headers are sent, so a later
+//    setHeader() throws and a statusCode change is not reflected on the wire.
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(async function() {
+      this.setHeader('X-Sync', 'before');
+      await null;
+      assert.strictEqual(this.headersSent, true);
+      this.statusCode = 503; // No effect: headers already sent.
+      assert.throws(() => this.setHeader('X-Async', 'after'), {
+        code: 'ERR_HTTP2_HEADERS_SENT',
+      });
+      server.close();
+    }));
+    res.end('hello');
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.on('response', common.mustCall((headers) => {
+      assert.strictEqual(headers[':status'], 200);
+      assert.strictEqual(headers['x-sync'], 'before');
+      assert.strictEqual(headers['x-async'], undefined);
+    }));
+    req.resume();
+    req.on('end', common.mustCall(() => client.close()));
+    req.end();
+  }));
+}
+
+// Re-entrancy: a listener that flushes the headers itself re-enters writeHead().
+// The emit is guarded so the event fires exactly once (common.mustCall), and the
+// illegal self-flush surfaces as ERR_HTTP2_HEADERS_SENT rather than recursing.
+{
+  const server = http2.createServer(common.mustCall((req, res) => {
+    res.on('sendingHeaders', common.mustCall(function() {
+      this.flushHeaders();
+    }));
+    assert.throws(() => res.end('hello'), { code: 'ERR_HTTP2_HEADERS_SENT' });
+    res.destroy();
+    server.close();
+  }));
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request();
+    req.resume();
+    req.on('error', () => {}); // The stream reset from destroy() is expected
+    req.on('close', () => client.close());
+    req.end();
+  }));
+}