Commit 6d426a04946 for nodejs

commit 6d426a04946ad3a477e41a7e5555b04270e3ee0c
Author: jakecastelli <38635403+jakecastelli@users.noreply.github.com>
Date:   Sun Nov 22 01:51:55 2026 +1030

    http2: add missing setHeaders

    Make it possible to invoke response.setHeaders() on the
    Http2ServerResponse object, matching the http.OutgoingMessage API.

    Fixes: https://github.com/nodejs/node/issues/51573
    Refs: https://github.com/nodejs/node/pull/51576
    Signed-off-by: jakecastelli <38635403+jakecastelli@users.noreply.github.com>
    Signed-off-by: Mikhail Leliakin <leliakin@canva.com>
    Co-authored-by: Mikhail Leliakin <leliakin@canva.com>
    Assisted-by: Cursor
    PR-URL: https://github.com/nodejs/node/pull/67597
    Reviewed-By: Jason Zhang <xzha4350@gmail.com>
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>

diff --git a/doc/api/http2.md b/doc/api/http2.md
index 2729820e5d8..03f971a0754 100644
--- a/doc/api/http2.md
+++ b/doc/api/http2.md
@@ -4911,6 +4911,45 @@ const server = http2.createServer((req, res) => {
 });
 ```

+#### `response.setHeaders(headers)`
+
+<!-- YAML
+added: REPLACEME
+-->
+
+* `headers` {Headers|Map}
+
+Sets multiple header values for implicit headers.
+`headers` must be an instance of [`Headers`][] or `Map`.
+If a header already exists in the to-be-sent headers,
+its value will be replaced.
+
+```js
+const headers = new Headers({ foo: 'bar' });
+response.setHeaders(headers);
+```
+
+or
+
+```js
+const headers = new Map([['foo', 'bar']]);
+response.setHeaders(headers);
+```
+
+When headers have been set with [`response.setHeaders()`][],
+they will be merged with any headers passed to [`response.writeHead()`][],
+with the headers passed to [`response.writeHead()`][] given precedence.
+
+```js
+// Returns content-type = text/plain
+const server = http2.createServer((req, res) => {
+  const headers = new Headers({ 'Content-Type': 'text/html' });
+  res.setHeaders(headers);
+  res.writeHead(200, { 'Content-Type': 'text/plain' });
+  res.end('ok');
+});
+```
+
 #### `response.setTimeout(msecs[, callback])`

 <!-- YAML
@@ -5334,6 +5373,7 @@ you need to implement any fall-back behavior yourself.
 [`Duplex`]: stream.md#class-streamduplex
 [`ERR_HTTP2_STREAM_ABORTED`]: errors.md#err_http2_stream_aborted
 [`ERR_HTTP2_STREAM_ERROR`]: errors.md#err_http2_stream_error
+[`Headers`]: globals.md#class-headers
 [`Http2ServerRequest`]: #class-http2http2serverrequest
 [`Http2ServerResponse`]: #class-http2http2serverresponse
 [`Http2Session` and Sockets]: #http2session-and-sockets
@@ -5362,6 +5402,7 @@ you need to implement any fall-back behavior yourself.
 [`request.socket`]: #requestsocket
 [`response.end()`]: #responseenddata-encoding-callback
 [`response.setHeader()`]: #responsesetheadername-value
+[`response.setHeaders()`]: #responsesetheadersheaders
 [`response.socket`]: #responsesocket
 [`response.writableEnded`]: #responsewritableended
 [`response.write()`]: #responsewritechunk-encoding-callback
diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js
index 23eb93c2d52..113a2af560b 100644
--- a/lib/internal/http2/compat.js
+++ b/lib/internal/http2/compat.js
@@ -39,6 +39,7 @@ const {
     ERR_HTTP2_NO_SOCKET_MANIPULATION,
     ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED,
     ERR_HTTP2_STATUS_INVALID,
+    ERR_INVALID_ARG_TYPE,
     ERR_INVALID_ARG_VALUE,
     ERR_INVALID_HTTP_TOKEN,
     ERR_STREAM_WRITE_AFTER_END,
@@ -687,6 +688,45 @@ class Http2ServerResponse extends Stream {
     this[kSetHeader](name, value);
   }

+  setHeaders(headers) {
+    if (this[kStream].headersSent)
+      throw new ERR_HTTP2_HEADERS_SENT();
+
+    if (
+      !headers ||
+      ArrayIsArray(headers) ||
+      typeof headers.keys !== 'function' ||
+      typeof headers.get !== 'function'
+    ) {
+      throw new ERR_INVALID_ARG_TYPE('headers', ['Headers', 'Map'], headers);
+    }
+
+    // Headers object joins multiple cookies with a comma when using
+    // the getter to retrieve the value,
+    // unless iterating over the headers directly.
+    // We also cannot safely split by comma.
+    // To avoid setHeader overwriting the previous value we push
+    // set-cookie values in array and set them all at once.
+    let cookies = null;
+
+    for (const { 0: key, 1: value } of headers) {
+      if (key === 'set-cookie') {
+        if (ArrayIsArray(value)) {
+          cookies ??= [];
+          cookies.push(...value);
+        } else {
+          cookies ??= [];
+          cookies.push(value);
+        }
+        continue;
+      }
+      this.setHeader(key, value);
+    }
+    if (cookies != null) {
+      this.setHeader('set-cookie', cookies);
+    }
+  }
+
   [kSetHeader](name, value) {
     name = name.trim().toLowerCase();
     assertValidHeader(name, value);
diff --git a/test/parallel/test-http2-server-set-headers.js b/test/parallel/test-http2-server-set-headers.js
new file mode 100644
index 00000000000..943e87c97d9
--- /dev/null
+++ b/test/parallel/test-http2-server-set-headers.js
@@ -0,0 +1,204 @@
+'use strict';
+
+const common = require('../common');
+if (!common.hasCrypto)
+  common.skip('missing crypto');
+const assert = require('assert');
+const http2 = require('http2');
+const body =
+  '<html><head></head><body><h1>this is some data</h2></body></html>';
+
+// Starts a server with the given request handler, sends one request and
+// calls onResponse with the response headers.
+function testResponse(onRequest, onResponse) {
+  const server = http2.createServer(onRequest);
+  server.on('error', common.mustNotCall());
+
+  server.listen(0, common.mustCall(() => {
+    const client = http2.connect(`http://localhost:${server.address().port}`);
+    const req = client.request({ ':path': '/' });
+    req.setEncoding('utf8');
+    req.on('response', onResponse);
+
+    let data = '';
+    req.on('data', (d) => data += d);
+    req.on('end', common.mustCall(() => {
+      assert.strictEqual(data, body);
+      server.close();
+      client.close();
+    }));
+    req.end();
+  }));
+}
+
+// Map, including a header name that is not lower case and a connection
+// header, which is dropped with a warning.
+{
+  const compatMsg = 'The provided connection header is not valid, ' +
+                    'the value will be dropped from the header and ' +
+                    'will never be in use.';
+  common.expectWarning('UnsupportedWarning', compatMsg);
+
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Map([
+      ['foobar', 'baz'],
+      ['X-POWERED-BY', 'node-test'],
+      ['connection', 'connection-test'],
+    ]));
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers[':status'], 200);
+    assert.strictEqual(headers.foobar, 'baz');
+    assert.strictEqual(headers['x-powered-by'], 'node-test');
+    assert.strictEqual(headers.connection, undefined);
+  }));
+}
+
+// Headers instance.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Headers({ foo: '1', bar: '2' }));
+    res.writeHead(200);
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers[':status'], 200);
+    assert.strictEqual(headers.foo, '1');
+    assert.strictEqual(headers.bar, '2');
+  }));
+}
+
+// An existing header is replaced.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeader('foo', '1');
+    res.setHeader('bar', '2');
+    res.setHeaders(new Headers({ foo: '3' }));
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers.foo, '3');
+    assert.strictEqual(headers.bar, '2');
+  }));
+}
+
+// Headers passed to writeHead() as an object take precedence.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Headers({ foo: '1', bar: '2' }));
+    res.writeHead(200, { foo: '3' });
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers[':status'], 200);
+    assert.strictEqual(headers.foo, '3');
+    assert.strictEqual(headers.bar, '2');
+  }));
+}
+
+// Headers passed to writeHead() as an array take precedence.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Headers({ foo: '1', bar: '2' }));
+    res.writeHead(200, ['foo', '3']);
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers[':status'], 200);
+    assert.strictEqual(headers.foo, '3');
+    assert.strictEqual(headers.bar, '2');
+  }));
+}
+
+// Multiple set-cookie values appended to a Headers instance.
+{
+  testResponse(common.mustCall((req, res) => {
+    const headers = new Headers();
+    headers.append('Set-Cookie', 'a=b');
+    headers.append('Set-Cookie', 'c=d');
+    res.setHeaders(headers);
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']);
+  }));
+}
+
+// Multiple set-cookie values as an array in a Map, with a name that is not
+// lower case.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Map([['Set-Cookie', ['a=b', 'c=d']]]));
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']);
+  }));
+}
+
+// Lower case set-cookie in a Map, as an array and as a single value.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Map([['set-cookie', ['a=b', 'c=d']]]));
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']);
+  }));
+
+  testResponse(common.mustCall((req, res) => {
+    res.setHeaders(new Map([['set-cookie', 'a=b']]));
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.deepStrictEqual(headers['set-cookie'], ['a=b']);
+  }));
+}
+
+// set-cookie values replace the ones set before.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.setHeader('set-cookie', ['x=y']);
+    const headers = new Headers();
+    headers.append('Set-Cookie', 'a=b');
+    headers.append('Set-Cookie', 'c=d');
+    res.setHeaders(headers);
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']);
+  }));
+}
+
+// Throws when the headers have already been sent.
+{
+  testResponse(common.mustCall((req, res) => {
+    res.writeHead(200);
+    assert.throws(() => {
+      res.setHeaders(new Headers({ foo: '1' }));
+    }, {
+      code: 'ERR_HTTP2_HEADERS_SENT',
+      name: 'Error',
+    });
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers.foo, undefined);
+  }));
+}
+
+// Throws when headers is neither a Headers instance nor a Map.
+{
+  testResponse(common.mustCall((req, res) => {
+    for (const headers of [
+      ['foo', '1'],
+      { foo: '1' },
+      null,
+      undefined,
+      'test',
+      1,
+      { keys() {} },
+      { get() {} },
+    ]) {
+      assert.throws(() => {
+        res.setHeaders(headers);
+      }, {
+        code: 'ERR_INVALID_ARG_TYPE',
+        name: 'TypeError',
+      });
+    }
+    res.end(body);
+  }), common.mustCall((headers) => {
+    assert.strictEqual(headers.foo, undefined);
+  }));
+}