1# HTTP/2 2 3<!-- YAML 4added: v8.4.0 5changes: 6 - version: 7 - v15.3.0 8 - v14.17.0 9 pr-url: https://github.com/nodejs/node/pull/36070 10 description: It is possible to abort a request with an AbortSignal. 11 - version: v15.0.0 12 pr-url: https://github.com/nodejs/node/pull/34664 13 description: Requests with the `host` header (with or without 14 `:authority`) can now be sent/received. 15 - version: v10.10.0 16 pr-url: https://github.com/nodejs/node/pull/22466 17 description: HTTP/2 is now Stable. Previously, it had been Experimental. 18--> 19 20<!--introduced_in=v8.4.0--> 21 22> Stability: 2 - Stable 23 24<!-- source_link=lib/http2.js --> 25 26The `node:http2` module provides an implementation of the [HTTP/2][] protocol. 27It can be accessed using: 28 29```js 30const http2 = require('node:http2'); 31``` 32 33## Determining if crypto support is unavailable 34 35It is possible for Node.js to be built without including support for the 36`node:crypto` module. In such cases, attempting to `import` from `node:http2` or 37calling `require('node:http2')` will result in an error being thrown. 38 39When using CommonJS, the error thrown can be caught using try/catch: 40 41```cjs 42let http2; 43try { 44 http2 = require('node:http2'); 45} catch (err) { 46 console.error('http2 support is disabled!'); 47} 48``` 49 50When using the lexical ESM `import` keyword, the error can only be 51caught if a handler for `process.on('uncaughtException')` is registered 52_before_ any attempt to load the module is made (using, for instance, 53a preload module). 54 55When using ESM, if there is a chance that the code may be run on a build 56of Node.js where crypto support is not enabled, consider using the 57[`import()`][] function instead of the lexical `import` keyword: 58 59```mjs 60let http2; 61try { 62 http2 = await import('node:http2'); 63} catch (err) { 64 console.error('http2 support is disabled!'); 65} 66``` 67 68## Core API 69 70The Core API provides a low-level interface designed specifically around 71support for HTTP/2 protocol features. It is specifically _not_ designed for 72compatibility with the existing [HTTP/1][] module API. However, 73the [Compatibility API][] is. 74 75The `http2` Core API is much more symmetric between client and server than the 76`http` API. For instance, most events, like `'error'`, `'connect'` and 77`'stream'`, can be emitted either by client-side code or server-side code. 78 79### Server-side example 80 81The following illustrates a simple HTTP/2 server using the Core API. 82Since there are no browsers known that support 83[unencrypted HTTP/2][HTTP/2 Unencrypted], the use of 84[`http2.createSecureServer()`][] is necessary when communicating 85with browser clients. 86 87```js 88const http2 = require('node:http2'); 89const fs = require('node:fs'); 90 91const server = http2.createSecureServer({ 92 key: fs.readFileSync('localhost-privkey.pem'), 93 cert: fs.readFileSync('localhost-cert.pem'), 94}); 95server.on('error', (err) => console.error(err)); 96 97server.on('stream', (stream, headers) => { 98 // stream is a Duplex 99 stream.respond({ 100 'content-type': 'text/html; charset=utf-8', 101 ':status': 200, 102 }); 103 stream.end('<h1>Hello World</h1>'); 104}); 105 106server.listen(8443); 107``` 108 109To generate the certificate and key for this example, run: 110 111```bash 112openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ 113 -keyout localhost-privkey.pem -out localhost-cert.pem 114``` 115 116### Client-side example 117 118The following illustrates an HTTP/2 client: 119 120```js 121const http2 = require('node:http2'); 122const fs = require('node:fs'); 123const client = http2.connect('https://localhost:8443', { 124 ca: fs.readFileSync('localhost-cert.pem'), 125}); 126client.on('error', (err) => console.error(err)); 127 128const req = client.request({ ':path': '/' }); 129 130req.on('response', (headers, flags) => { 131 for (const name in headers) { 132 console.log(`${name}: ${headers[name]}`); 133 } 134}); 135 136req.setEncoding('utf8'); 137let data = ''; 138req.on('data', (chunk) => { data += chunk; }); 139req.on('end', () => { 140 console.log(`\n${data}`); 141 client.close(); 142}); 143req.end(); 144``` 145 146### Class: `Http2Session` 147 148<!-- YAML 149added: v8.4.0 150--> 151 152* Extends: {EventEmitter} 153 154Instances of the `http2.Http2Session` class represent an active communications 155session between an HTTP/2 client and server. Instances of this class are _not_ 156intended to be constructed directly by user code. 157 158Each `Http2Session` instance will exhibit slightly different behaviors 159depending on whether it is operating as a server or a client. The 160`http2session.type` property can be used to determine the mode in which an 161`Http2Session` is operating. On the server side, user code should rarely 162have occasion to work with the `Http2Session` object directly, with most 163actions typically taken through interactions with either the `Http2Server` or 164`Http2Stream` objects. 165 166User code will not create `Http2Session` instances directly. Server-side 167`Http2Session` instances are created by the `Http2Server` instance when a 168new HTTP/2 connection is received. Client-side `Http2Session` instances are 169created using the `http2.connect()` method. 170 171#### `Http2Session` and sockets 172 173Every `Http2Session` instance is associated with exactly one [`net.Socket`][] or 174[`tls.TLSSocket`][] when it is created. When either the `Socket` or the 175`Http2Session` are destroyed, both will be destroyed. 176 177Because of the specific serialization and processing requirements imposed 178by the HTTP/2 protocol, it is not recommended for user code to read data from 179or write data to a `Socket` instance bound to a `Http2Session`. Doing so can 180put the HTTP/2 session into an indeterminate state causing the session and 181the socket to become unusable. 182 183Once a `Socket` has been bound to an `Http2Session`, user code should rely 184solely on the API of the `Http2Session`. 185 186#### Event: `'close'` 187 188<!-- YAML 189added: v8.4.0 190--> 191 192The `'close'` event is emitted once the `Http2Session` has been destroyed. Its 193listener does not expect any arguments. 194 195#### Event: `'connect'` 196 197<!-- YAML 198added: v8.4.0 199--> 200 201* `session` {Http2Session} 202* `socket` {net.Socket} 203 204The `'connect'` event is emitted once the `Http2Session` has been successfully 205connected to the remote peer and communication may begin. 206 207User code will typically not listen for this event directly. 208 209#### Event: `'error'` 210 211<!-- YAML 212added: v8.4.0 213--> 214 215* `error` {Error} 216 217The `'error'` event is emitted when an error occurs during the processing of 218an `Http2Session`. 219 220#### Event: `'frameError'` 221 222<!-- YAML 223added: v8.4.0 224--> 225 226* `type` {integer} The frame type. 227* `code` {integer} The error code. 228* `id` {integer} The stream id (or `0` if the frame isn't associated with a 229 stream). 230 231The `'frameError'` event is emitted when an error occurs while attempting to 232send a frame on the session. If the frame that could not be sent is associated 233with a specific `Http2Stream`, an attempt to emit a `'frameError'` event on the 234`Http2Stream` is made. 235 236If the `'frameError'` event is associated with a stream, the stream will be 237closed and destroyed immediately following the `'frameError'` event. If the 238event is not associated with a stream, the `Http2Session` will be shut down 239immediately following the `'frameError'` event. 240 241#### Event: `'goaway'` 242 243<!-- YAML 244added: v8.4.0 245--> 246 247* `errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame. 248* `lastStreamID` {number} The ID of the last stream the remote peer successfully 249 processed (or `0` if no ID is specified). 250* `opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` 251 frame, a `Buffer` instance will be passed containing that data. 252 253The `'goaway'` event is emitted when a `GOAWAY` frame is received. 254 255The `Http2Session` instance will be shut down automatically when the `'goaway'` 256event is emitted. 257 258#### Event: `'localSettings'` 259 260<!-- YAML 261added: v8.4.0 262--> 263 264* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. 265 266The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame 267has been received. 268 269When using `http2session.settings()` to submit new settings, the modified 270settings do not take effect until the `'localSettings'` event is emitted. 271 272```js 273session.settings({ enablePush: false }); 274 275session.on('localSettings', (settings) => { 276 /* Use the new settings */ 277}); 278``` 279 280#### Event: `'ping'` 281 282<!-- YAML 283added: v10.12.0 284--> 285 286* `payload` {Buffer} The `PING` frame 8-byte payload 287 288The `'ping'` event is emitted whenever a `PING` frame is received from the 289connected peer. 290 291#### Event: `'remoteSettings'` 292 293<!-- YAML 294added: v8.4.0 295--> 296 297* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. 298 299The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received 300from the connected peer. 301 302```js 303session.on('remoteSettings', (settings) => { 304 /* Use the new settings */ 305}); 306``` 307 308#### Event: `'stream'` 309 310<!-- YAML 311added: v8.4.0 312--> 313 314* `stream` {Http2Stream} A reference to the stream 315* `headers` {HTTP/2 Headers Object} An object describing the headers 316* `flags` {number} The associated numeric flags 317* `rawHeaders` {Array} An array containing the raw header names followed by 318 their respective values. 319 320The `'stream'` event is emitted when a new `Http2Stream` is created. 321 322```js 323const http2 = require('node:http2'); 324session.on('stream', (stream, headers, flags) => { 325 const method = headers[':method']; 326 const path = headers[':path']; 327 // ... 328 stream.respond({ 329 ':status': 200, 330 'content-type': 'text/plain; charset=utf-8', 331 }); 332 stream.write('hello '); 333 stream.end('world'); 334}); 335``` 336 337On the server side, user code will typically not listen for this event directly, 338and would instead register a handler for the `'stream'` event emitted by the 339`net.Server` or `tls.Server` instances returned by `http2.createServer()` and 340`http2.createSecureServer()`, respectively, as in the example below: 341 342```js 343const http2 = require('node:http2'); 344 345// Create an unencrypted HTTP/2 server 346const server = http2.createServer(); 347 348server.on('stream', (stream, headers) => { 349 stream.respond({ 350 'content-type': 'text/html; charset=utf-8', 351 ':status': 200, 352 }); 353 stream.on('error', (error) => console.error(error)); 354 stream.end('<h1>Hello World</h1>'); 355}); 356 357server.listen(8000); 358``` 359 360Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, 361a network error will destroy each individual stream and must be handled on the 362stream level, as shown above. 363 364#### Event: `'timeout'` 365 366<!-- YAML 367added: v8.4.0 368--> 369 370After the `http2session.setTimeout()` method is used to set the timeout period 371for this `Http2Session`, the `'timeout'` event is emitted if there is no 372activity on the `Http2Session` after the configured number of milliseconds. 373Its listener does not expect any arguments. 374 375```js 376session.setTimeout(2000); 377session.on('timeout', () => { /* .. */ }); 378``` 379 380#### `http2session.alpnProtocol` 381 382<!-- YAML 383added: v9.4.0 384--> 385 386* {string|undefined} 387 388Value will be `undefined` if the `Http2Session` is not yet connected to a 389socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or 390will return the value of the connected `TLSSocket`'s own `alpnProtocol` 391property. 392 393#### `http2session.close([callback])` 394 395<!-- YAML 396added: v9.4.0 397--> 398 399* `callback` {Function} 400 401Gracefully closes the `Http2Session`, allowing any existing streams to 402complete on their own and preventing new `Http2Stream` instances from being 403created. Once closed, `http2session.destroy()` _might_ be called if there 404are no open `Http2Stream` instances. 405 406If specified, the `callback` function is registered as a handler for the 407`'close'` event. 408 409#### `http2session.closed` 410 411<!-- YAML 412added: v9.4.0 413--> 414 415* {boolean} 416 417Will be `true` if this `Http2Session` instance has been closed, otherwise 418`false`. 419 420#### `http2session.connecting` 421 422<!-- YAML 423added: v10.0.0 424--> 425 426* {boolean} 427 428Will be `true` if this `Http2Session` instance is still connecting, will be set 429to `false` before emitting `connect` event and/or calling the `http2.connect` 430callback. 431 432#### `http2session.destroy([error][, code])` 433 434<!-- YAML 435added: v8.4.0 436--> 437 438* `error` {Error} An `Error` object if the `Http2Session` is being destroyed 439 due to an error. 440* `code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame. 441 If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, 442 otherwise defaults to `NO_ERROR`. 443 444Immediately terminates the `Http2Session` and the associated `net.Socket` or 445`tls.TLSSocket`. 446 447Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` 448is not undefined, an `'error'` event will be emitted immediately before the 449`'close'` event. 450 451If there are any remaining open `Http2Streams` associated with the 452`Http2Session`, those will also be destroyed. 453 454#### `http2session.destroyed` 455 456<!-- YAML 457added: v8.4.0 458--> 459 460* {boolean} 461 462Will be `true` if this `Http2Session` instance has been destroyed and must no 463longer be used, otherwise `false`. 464 465#### `http2session.encrypted` 466 467<!-- YAML 468added: v9.4.0 469--> 470 471* {boolean|undefined} 472 473Value is `undefined` if the `Http2Session` session socket has not yet been 474connected, `true` if the `Http2Session` is connected with a `TLSSocket`, 475and `false` if the `Http2Session` is connected to any other kind of socket 476or stream. 477 478#### `http2session.goaway([code[, lastStreamID[, opaqueData]]])` 479 480<!-- YAML 481added: v9.4.0 482--> 483 484* `code` {number} An HTTP/2 error code 485* `lastStreamID` {number} The numeric ID of the last processed `Http2Stream` 486* `opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView` 487 instance containing additional data to be carried within the `GOAWAY` frame. 488 489Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the 490`Http2Session`. 491 492#### `http2session.localSettings` 493 494<!-- YAML 495added: v8.4.0 496--> 497 498* {HTTP/2 Settings Object} 499 500A prototype-less object describing the current local settings of this 501`Http2Session`. The local settings are local to _this_ `Http2Session` instance. 502 503#### `http2session.originSet` 504 505<!-- YAML 506added: v9.4.0 507--> 508 509* {string\[]|undefined} 510 511If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property 512will return an `Array` of origins for which the `Http2Session` may be 513considered authoritative. 514 515The `originSet` property is only available when using a secure TLS connection. 516 517#### `http2session.pendingSettingsAck` 518 519<!-- YAML 520added: v8.4.0 521--> 522 523* {boolean} 524 525Indicates whether the `Http2Session` is currently waiting for acknowledgment of 526a sent `SETTINGS` frame. Will be `true` after calling the 527`http2session.settings()` method. Will be `false` once all sent `SETTINGS` 528frames have been acknowledged. 529 530#### `http2session.ping([payload, ]callback)` 531 532<!-- YAML 533added: v8.9.3 534changes: 535 - version: v18.0.0 536 pr-url: https://github.com/nodejs/node/pull/41678 537 description: Passing an invalid callback to the `callback` argument 538 now throws `ERR_INVALID_ARG_TYPE` instead of 539 `ERR_INVALID_CALLBACK`. 540--> 541 542* `payload` {Buffer|TypedArray|DataView} Optional ping payload. 543* `callback` {Function} 544* Returns: {boolean} 545 546Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must 547be provided. The method will return `true` if the `PING` was sent, `false` 548otherwise. 549 550The maximum number of outstanding (unacknowledged) pings is determined by the 551`maxOutstandingPings` configuration option. The default maximum is 10. 552 553If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` 554containing 8 bytes of data that will be transmitted with the `PING` and 555returned with the ping acknowledgment. 556 557The callback will be invoked with three arguments: an error argument that will 558be `null` if the `PING` was successfully acknowledged, a `duration` argument 559that reports the number of milliseconds elapsed since the ping was sent and the 560acknowledgment was received, and a `Buffer` containing the 8-byte `PING` 561payload. 562 563```js 564session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { 565 if (!err) { 566 console.log(`Ping acknowledged in ${duration} milliseconds`); 567 console.log(`With payload '${payload.toString()}'`); 568 } 569}); 570``` 571 572If the `payload` argument is not specified, the default payload will be the 57364-bit timestamp (little endian) marking the start of the `PING` duration. 574 575#### `http2session.ref()` 576 577<!-- YAML 578added: v9.4.0 579--> 580 581Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session` 582instance's underlying [`net.Socket`][]. 583 584#### `http2session.remoteSettings` 585 586<!-- YAML 587added: v8.4.0 588--> 589 590* {HTTP/2 Settings Object} 591 592A prototype-less object describing the current remote settings of this 593`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. 594 595#### `http2session.setLocalWindowSize(windowSize)` 596 597<!-- YAML 598added: 599 - v15.3.0 600 - v14.18.0 601--> 602 603* `windowSize` {number} 604 605Sets the local endpoint's window size. 606The `windowSize` is the total window size to set, not 607the delta. 608 609```js 610const http2 = require('node:http2'); 611 612const server = http2.createServer(); 613const expectedWindowSize = 2 ** 20; 614server.on('connect', (session) => { 615 616 // Set local window size to be 2 ** 20 617 session.setLocalWindowSize(expectedWindowSize); 618}); 619``` 620 621#### `http2session.setTimeout(msecs, callback)` 622 623<!-- YAML 624added: v8.4.0 625changes: 626 - version: v18.0.0 627 pr-url: https://github.com/nodejs/node/pull/41678 628 description: Passing an invalid callback to the `callback` argument 629 now throws `ERR_INVALID_ARG_TYPE` instead of 630 `ERR_INVALID_CALLBACK`. 631--> 632 633* `msecs` {number} 634* `callback` {Function} 635 636Used to set a callback function that is called when there is no activity on 637the `Http2Session` after `msecs` milliseconds. The given `callback` is 638registered as a listener on the `'timeout'` event. 639 640#### `http2session.socket` 641 642<!-- YAML 643added: v8.4.0 644--> 645 646* {net.Socket|tls.TLSSocket} 647 648Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 649limits available methods to ones safe to use with HTTP/2. 650 651`destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw 652an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See 653[`Http2Session` and Sockets][] for more information. 654 655`setTimeout` method will be called on this `Http2Session`. 656 657All other interactions will be routed directly to the socket. 658 659#### `http2session.state` 660 661<!-- YAML 662added: v8.4.0 663--> 664 665Provides miscellaneous information about the current state of the 666`Http2Session`. 667 668* {Object} 669 * `effectiveLocalWindowSize` {number} The current local (receive) 670 flow control window size for the `Http2Session`. 671 * `effectiveRecvDataLength` {number} The current number of bytes 672 that have been received since the last flow control `WINDOW_UPDATE`. 673 * `nextStreamID` {number} The numeric identifier to be used the 674 next time a new `Http2Stream` is created by this `Http2Session`. 675 * `localWindowSize` {number} The number of bytes that the remote peer can 676 send without receiving a `WINDOW_UPDATE`. 677 * `lastProcStreamID` {number} The numeric id of the `Http2Stream` 678 for which a `HEADERS` or `DATA` frame was most recently received. 679 * `remoteWindowSize` {number} The number of bytes that this `Http2Session` 680 may send without receiving a `WINDOW_UPDATE`. 681 * `outboundQueueSize` {number} The number of frames currently within the 682 outbound queue for this `Http2Session`. 683 * `deflateDynamicTableSize` {number} The current size in bytes of the 684 outbound header compression state table. 685 * `inflateDynamicTableSize` {number} The current size in bytes of the 686 inbound header compression state table. 687 688An object describing the current status of this `Http2Session`. 689 690#### `http2session.settings([settings][, callback])` 691 692<!-- YAML 693added: v8.4.0 694changes: 695 - version: v18.0.0 696 pr-url: https://github.com/nodejs/node/pull/41678 697 description: Passing an invalid callback to the `callback` argument 698 now throws `ERR_INVALID_ARG_TYPE` instead of 699 `ERR_INVALID_CALLBACK`. 700--> 701 702* `settings` {HTTP/2 Settings Object} 703* `callback` {Function} Callback that is called once the session is connected or 704 right away if the session is already connected. 705 * `err` {Error|null} 706 * `settings` {HTTP/2 Settings Object} The updated `settings` object. 707 * `duration` {integer} 708 709Updates the current local settings for this `Http2Session` and sends a new 710`SETTINGS` frame to the connected HTTP/2 peer. 711 712Once called, the `http2session.pendingSettingsAck` property will be `true` 713while the session is waiting for the remote peer to acknowledge the new 714settings. 715 716The new settings will not become effective until the `SETTINGS` acknowledgment 717is received and the `'localSettings'` event is emitted. It is possible to send 718multiple `SETTINGS` frames while acknowledgment is still pending. 719 720#### `http2session.type` 721 722<!-- YAML 723added: v8.4.0 724--> 725 726* {number} 727 728The `http2session.type` will be equal to 729`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a 730server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a 731client. 732 733#### `http2session.unref()` 734 735<!-- YAML 736added: v9.4.0 737--> 738 739Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session` 740instance's underlying [`net.Socket`][]. 741 742### Class: `ServerHttp2Session` 743 744<!-- YAML 745added: v8.4.0 746--> 747 748* Extends: {Http2Session} 749 750#### `serverhttp2session.altsvc(alt, originOrStream)` 751 752<!-- YAML 753added: v9.4.0 754--> 755 756* `alt` {string} A description of the alternative service configuration as 757 defined by [RFC 7838][]. 758* `originOrStream` {number|string|URL|Object} Either a URL string specifying 759 the origin (or an `Object` with an `origin` property) or the numeric 760 identifier of an active `Http2Stream` as given by the `http2stream.id` 761 property. 762 763Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client. 764 765```js 766const http2 = require('node:http2'); 767 768const server = http2.createServer(); 769server.on('session', (session) => { 770 // Set altsvc for origin https://example.org:80 771 session.altsvc('h2=":8000"', 'https://example.org:80'); 772}); 773 774server.on('stream', (stream) => { 775 // Set altsvc for a specific stream 776 stream.session.altsvc('h2=":8000"', stream.id); 777}); 778``` 779 780Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate 781service is associated with the origin of the given `Http2Stream`. 782 783The `alt` and origin string _must_ contain only ASCII bytes and are 784strictly interpreted as a sequence of ASCII bytes. The special value `'clear'` 785may be passed to clear any previously set alternative service for a given 786domain. 787 788When a string is passed for the `originOrStream` argument, it will be parsed as 789a URL and the origin will be derived. For instance, the origin for the 790HTTP URL `'https://example.org/foo/bar'` is the ASCII string 791`'https://example.org'`. An error will be thrown if either the given string 792cannot be parsed as a URL or if a valid origin cannot be derived. 793 794A `URL` object, or any object with an `origin` property, may be passed as 795`originOrStream`, in which case the value of the `origin` property will be 796used. The value of the `origin` property _must_ be a properly serialized 797ASCII origin. 798 799#### Specifying alternative services 800 801The format of the `alt` parameter is strictly defined by [RFC 7838][] as an 802ASCII string containing a comma-delimited list of "alternative" protocols 803associated with a specific host and port. 804 805For example, the value `'h2="example.org:81"'` indicates that the HTTP/2 806protocol is available on the host `'example.org'` on TCP/IP port 81. The 807host and port _must_ be contained within the quote (`"`) characters. 808 809Multiple alternatives may be specified, for instance: `'h2="example.org:81", 810h2=":82"'`. 811 812The protocol identifier (`'h2'` in the examples) may be any valid 813[ALPN Protocol ID][]. 814 815The syntax of these values is not validated by the Node.js implementation and 816are passed through as provided by the user or received from the peer. 817 818#### `serverhttp2session.origin(...origins)` 819 820<!-- YAML 821added: v10.12.0 822--> 823 824* `origins` { string | URL | Object } One or more URL Strings passed as 825 separate arguments. 826 827Submits an `ORIGIN` frame (as defined by [RFC 8336][]) to the connected client 828to advertise the set of origins for which the server is capable of providing 829authoritative responses. 830 831```js 832const http2 = require('node:http2'); 833const options = getSecureOptionsSomehow(); 834const server = http2.createSecureServer(options); 835server.on('stream', (stream) => { 836 stream.respond(); 837 stream.end('ok'); 838}); 839server.on('session', (session) => { 840 session.origin('https://example.com', 'https://example.org'); 841}); 842``` 843 844When a string is passed as an `origin`, it will be parsed as a URL and the 845origin will be derived. For instance, the origin for the HTTP URL 846`'https://example.org/foo/bar'` is the ASCII string 847`'https://example.org'`. An error will be thrown if either the given string 848cannot be parsed as a URL or if a valid origin cannot be derived. 849 850A `URL` object, or any object with an `origin` property, may be passed as 851an `origin`, in which case the value of the `origin` property will be 852used. The value of the `origin` property _must_ be a properly serialized 853ASCII origin. 854 855Alternatively, the `origins` option may be used when creating a new HTTP/2 856server using the `http2.createSecureServer()` method: 857 858```js 859const http2 = require('node:http2'); 860const options = getSecureOptionsSomehow(); 861options.origins = ['https://example.com', 'https://example.org']; 862const server = http2.createSecureServer(options); 863server.on('stream', (stream) => { 864 stream.respond(); 865 stream.end('ok'); 866}); 867``` 868 869### Class: `ClientHttp2Session` 870 871<!-- YAML 872added: v8.4.0 873--> 874 875* Extends: {Http2Session} 876 877#### Event: `'altsvc'` 878 879<!-- YAML 880added: v9.4.0 881--> 882 883* `alt` {string} 884* `origin` {string} 885* `streamId` {number} 886 887The `'altsvc'` event is emitted whenever an `ALTSVC` frame is received by 888the client. The event is emitted with the `ALTSVC` value, origin, and stream 889ID. If no `origin` is provided in the `ALTSVC` frame, `origin` will 890be an empty string. 891 892```js 893const http2 = require('node:http2'); 894const client = http2.connect('https://example.org'); 895 896client.on('altsvc', (alt, origin, streamId) => { 897 console.log(alt); 898 console.log(origin); 899 console.log(streamId); 900}); 901``` 902 903#### Event: `'origin'` 904 905<!-- YAML 906added: v10.12.0 907--> 908 909* `origins` {string\[]} 910 911The `'origin'` event is emitted whenever an `ORIGIN` frame is received by 912the client. The event is emitted with an array of `origin` strings. The 913`http2session.originSet` will be updated to include the received 914origins. 915 916```js 917const http2 = require('node:http2'); 918const client = http2.connect('https://example.org'); 919 920client.on('origin', (origins) => { 921 for (let n = 0; n < origins.length; n++) 922 console.log(origins[n]); 923}); 924``` 925 926The `'origin'` event is only emitted when using a secure TLS connection. 927 928#### `clienthttp2session.request(headers[, options])` 929 930<!-- YAML 931added: v8.4.0 932--> 933 934* `headers` {HTTP/2 Headers Object} 935 936* `options` {Object} 937 * `endStream` {boolean} `true` if the `Http2Stream` _writable_ side should 938 be closed initially, such as when sending a `GET` request that should not 939 expect a payload body. 940 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 941 the created stream is made the sole direct dependency of the parent, with 942 all other existing dependents made a dependent of the newly created stream. 943 **Default:** `false`. 944 * `parent` {number} Specifies the numeric identifier of a stream the newly 945 created stream is dependent on. 946 * `weight` {number} Specifies the relative dependency of a stream in relation 947 to other streams with the same `parent`. The value is a number between `1` 948 and `256` (inclusive). 949 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 950 `'wantTrailers'` event after the final `DATA` frame has been sent. 951 * `signal` {AbortSignal} An AbortSignal that may be used to abort an ongoing 952 request. 953 954* Returns: {ClientHttp2Stream} 955 956For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` 957creates and returns an `Http2Stream` instance that can be used to send an 958HTTP/2 request to the connected server. 959 960When a `ClientHttp2Session` is first created, the socket may not yet be 961connected. if `clienthttp2session.request()` is called during this time, the 962actual request will be deferred until the socket is ready to go. 963If the `session` is closed before the actual request be executed, an 964`ERR_HTTP2_GOAWAY_SESSION` is thrown. 965 966This method is only available if `http2session.type` is equal to 967`http2.constants.NGHTTP2_SESSION_CLIENT`. 968 969```js 970const http2 = require('node:http2'); 971const clientSession = http2.connect('https://localhost:1234'); 972const { 973 HTTP2_HEADER_PATH, 974 HTTP2_HEADER_STATUS, 975} = http2.constants; 976 977const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); 978req.on('response', (headers) => { 979 console.log(headers[HTTP2_HEADER_STATUS]); 980 req.on('data', (chunk) => { /* .. */ }); 981 req.on('end', () => { /* .. */ }); 982}); 983``` 984 985When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 986is emitted immediately after queuing the last chunk of payload data to be sent. 987The `http2stream.sendTrailers()` method can then be called to send trailing 988headers to the peer. 989 990When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 991close when the final `DATA` frame is transmitted. User code must call either 992`http2stream.sendTrailers()` or `http2stream.close()` to close the 993`Http2Stream`. 994 995When `options.signal` is set with an `AbortSignal` and then `abort` on the 996corresponding `AbortController` is called, the request will emit an `'error'` 997event with an `AbortError` error. 998 999The `:method` and `:path` pseudo-headers are not specified within `headers`, 1000they respectively default to: 1001 1002* `:method` = `'GET'` 1003* `:path` = `/` 1004 1005### Class: `Http2Stream` 1006 1007<!-- YAML 1008added: v8.4.0 1009--> 1010 1011* Extends: {stream.Duplex} 1012 1013Each instance of the `Http2Stream` class represents a bidirectional HTTP/2 1014communications stream over an `Http2Session` instance. Any single `Http2Session` 1015may have up to 2<sup>31</sup>-1 `Http2Stream` instances over its lifetime. 1016 1017User code will not construct `Http2Stream` instances directly. Rather, these 1018are created, managed, and provided to user code through the `Http2Session` 1019instance. On the server, `Http2Stream` instances are created either in response 1020to an incoming HTTP request (and handed off to user code via the `'stream'` 1021event), or in response to a call to the `http2stream.pushStream()` method. 1022On the client, `Http2Stream` instances are created and returned when either the 1023`http2session.request()` method is called, or in response to an incoming 1024`'push'` event. 1025 1026The `Http2Stream` class is a base for the [`ServerHttp2Stream`][] and 1027[`ClientHttp2Stream`][] classes, each of which is used specifically by either 1028the Server or Client side, respectively. 1029 1030All `Http2Stream` instances are [`Duplex`][] streams. The `Writable` side of the 1031`Duplex` is used to send data to the connected peer, while the `Readable` side 1032is used to receive data sent by the connected peer. 1033 1034The default text character encoding for an `Http2Stream` is UTF-8. When using an 1035`Http2Stream` to send text, use the `'content-type'` header to set the character 1036encoding. 1037 1038```js 1039stream.respond({ 1040 'content-type': 'text/html; charset=utf-8', 1041 ':status': 200, 1042}); 1043``` 1044 1045#### `Http2Stream` Lifecycle 1046 1047##### Creation 1048 1049On the server side, instances of [`ServerHttp2Stream`][] are created either 1050when: 1051 1052* A new HTTP/2 `HEADERS` frame with a previously unused stream ID is received; 1053* The `http2stream.pushStream()` method is called. 1054 1055On the client side, instances of [`ClientHttp2Stream`][] are created when the 1056`http2session.request()` method is called. 1057 1058On the client, the `Http2Stream` instance returned by `http2session.request()` 1059may not be immediately ready for use if the parent `Http2Session` has not yet 1060been fully established. In such cases, operations called on the `Http2Stream` 1061will be buffered until the `'ready'` event is emitted. User code should rarely, 1062if ever, need to handle the `'ready'` event directly. The ready status of an 1063`Http2Stream` can be determined by checking the value of `http2stream.id`. If 1064the value is `undefined`, the stream is not yet ready for use. 1065 1066##### Destruction 1067 1068All [`Http2Stream`][] instances are destroyed either when: 1069 1070* An `RST_STREAM` frame for the stream is received by the connected peer, 1071 and (for client streams only) pending data has been read. 1072* The `http2stream.close()` method is called, and (for client streams only) 1073 pending data has been read. 1074* The `http2stream.destroy()` or `http2session.destroy()` methods are called. 1075 1076When an `Http2Stream` instance is destroyed, an attempt will be made to send an 1077`RST_STREAM` frame to the connected peer. 1078 1079When the `Http2Stream` instance is destroyed, the `'close'` event will 1080be emitted. Because `Http2Stream` is an instance of `stream.Duplex`, the 1081`'end'` event will also be emitted if the stream data is currently flowing. 1082The `'error'` event may also be emitted if `http2stream.destroy()` was called 1083with an `Error` passed as the first argument. 1084 1085After the `Http2Stream` has been destroyed, the `http2stream.destroyed` 1086property will be `true` and the `http2stream.rstCode` property will specify the 1087`RST_STREAM` error code. The `Http2Stream` instance is no longer usable once 1088destroyed. 1089 1090#### Event: `'aborted'` 1091 1092<!-- YAML 1093added: v8.4.0 1094--> 1095 1096The `'aborted'` event is emitted whenever a `Http2Stream` instance is 1097abnormally aborted in mid-communication. 1098Its listener does not expect any arguments. 1099 1100The `'aborted'` event will only be emitted if the `Http2Stream` writable side 1101has not been ended. 1102 1103#### Event: `'close'` 1104 1105<!-- YAML 1106added: v8.4.0 1107--> 1108 1109The `'close'` event is emitted when the `Http2Stream` is destroyed. Once 1110this event is emitted, the `Http2Stream` instance is no longer usable. 1111 1112The HTTP/2 error code used when closing the stream can be retrieved using 1113the `http2stream.rstCode` property. If the code is any value other than 1114`NGHTTP2_NO_ERROR` (`0`), an `'error'` event will have also been emitted. 1115 1116#### Event: `'error'` 1117 1118<!-- YAML 1119added: v8.4.0 1120--> 1121 1122* `error` {Error} 1123 1124The `'error'` event is emitted when an error occurs during the processing of 1125an `Http2Stream`. 1126 1127#### Event: `'frameError'` 1128 1129<!-- YAML 1130added: v8.4.0 1131--> 1132 1133* `type` {integer} The frame type. 1134* `code` {integer} The error code. 1135* `id` {integer} The stream id (or `0` if the frame isn't associated with a 1136 stream). 1137 1138The `'frameError'` event is emitted when an error occurs while attempting to 1139send a frame. When invoked, the handler function will receive an integer 1140argument identifying the frame type, and an integer argument identifying the 1141error code. The `Http2Stream` instance will be destroyed immediately after the 1142`'frameError'` event is emitted. 1143 1144#### Event: `'ready'` 1145 1146<!-- YAML 1147added: v8.4.0 1148--> 1149 1150The `'ready'` event is emitted when the `Http2Stream` has been opened, has 1151been assigned an `id`, and can be used. The listener does not expect any 1152arguments. 1153 1154#### Event: `'timeout'` 1155 1156<!-- YAML 1157added: v8.4.0 1158--> 1159 1160The `'timeout'` event is emitted after no activity is received for this 1161`Http2Stream` within the number of milliseconds set using 1162`http2stream.setTimeout()`. 1163Its listener does not expect any arguments. 1164 1165#### Event: `'trailers'` 1166 1167<!-- YAML 1168added: v8.4.0 1169--> 1170 1171* `headers` {HTTP/2 Headers Object} An object describing the headers 1172* `flags` {number} The associated numeric flags 1173 1174The `'trailers'` event is emitted when a block of headers associated with 1175trailing header fields is received. The listener callback is passed the 1176[HTTP/2 Headers Object][] and flags associated with the headers. 1177 1178This event might not be emitted if `http2stream.end()` is called 1179before trailers are received and the incoming data is not being read or 1180listened for. 1181 1182```js 1183stream.on('trailers', (headers, flags) => { 1184 console.log(headers); 1185}); 1186``` 1187 1188#### Event: `'wantTrailers'` 1189 1190<!-- YAML 1191added: v10.0.0 1192--> 1193 1194The `'wantTrailers'` event is emitted when the `Http2Stream` has queued the 1195final `DATA` frame to be sent on a frame and the `Http2Stream` is ready to send 1196trailing headers. When initiating a request or response, the `waitForTrailers` 1197option must be set for this event to be emitted. 1198 1199#### `http2stream.aborted` 1200 1201<!-- YAML 1202added: v8.4.0 1203--> 1204 1205* {boolean} 1206 1207Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, 1208the `'aborted'` event will have been emitted. 1209 1210#### `http2stream.bufferSize` 1211 1212<!-- YAML 1213added: 1214 - v11.2.0 1215 - v10.16.0 1216--> 1217 1218* {number} 1219 1220This property shows the number of characters currently buffered to be written. 1221See [`net.Socket.bufferSize`][] for details. 1222 1223#### `http2stream.close(code[, callback])` 1224 1225<!-- YAML 1226added: v8.4.0 1227changes: 1228 - version: v18.0.0 1229 pr-url: https://github.com/nodejs/node/pull/41678 1230 description: Passing an invalid callback to the `callback` argument 1231 now throws `ERR_INVALID_ARG_TYPE` instead of 1232 `ERR_INVALID_CALLBACK`. 1233--> 1234 1235* `code` {number} Unsigned 32-bit integer identifying the error code. 1236 **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`). 1237* `callback` {Function} An optional function registered to listen for the 1238 `'close'` event. 1239 1240Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the 1241connected HTTP/2 peer. 1242 1243#### `http2stream.closed` 1244 1245<!-- YAML 1246added: v9.4.0 1247--> 1248 1249* {boolean} 1250 1251Set to `true` if the `Http2Stream` instance has been closed. 1252 1253#### `http2stream.destroyed` 1254 1255<!-- YAML 1256added: v8.4.0 1257--> 1258 1259* {boolean} 1260 1261Set to `true` if the `Http2Stream` instance has been destroyed and is no longer 1262usable. 1263 1264#### `http2stream.endAfterHeaders` 1265 1266<!-- YAML 1267added: v10.11.0 1268--> 1269 1270* {boolean} 1271 1272Set to `true` if the `END_STREAM` flag was set in the request or response 1273HEADERS frame received, indicating that no additional data should be received 1274and the readable side of the `Http2Stream` will be closed. 1275 1276#### `http2stream.id` 1277 1278<!-- YAML 1279added: v8.4.0 1280--> 1281 1282* {number|undefined} 1283 1284The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` 1285if the stream identifier has not yet been assigned. 1286 1287#### `http2stream.pending` 1288 1289<!-- YAML 1290added: v9.4.0 1291--> 1292 1293* {boolean} 1294 1295Set to `true` if the `Http2Stream` instance has not yet been assigned a 1296numeric stream identifier. 1297 1298#### `http2stream.priority(options)` 1299 1300<!-- YAML 1301added: v8.4.0 1302--> 1303 1304* `options` {Object} 1305 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 1306 this stream is made the sole direct dependency of the parent, with 1307 all other existing dependents made a dependent of this stream. **Default:** 1308 `false`. 1309 * `parent` {number} Specifies the numeric identifier of a stream this stream 1310 is dependent on. 1311 * `weight` {number} Specifies the relative dependency of a stream in relation 1312 to other streams with the same `parent`. The value is a number between `1` 1313 and `256` (inclusive). 1314 * `silent` {boolean} When `true`, changes the priority locally without 1315 sending a `PRIORITY` frame to the connected peer. 1316 1317Updates the priority for this `Http2Stream` instance. 1318 1319#### `http2stream.rstCode` 1320 1321<!-- YAML 1322added: v8.4.0 1323--> 1324 1325* {number} 1326 1327Set to the `RST_STREAM` [error code][] reported when the `Http2Stream` is 1328destroyed after either receiving an `RST_STREAM` frame from the connected peer, 1329calling `http2stream.close()`, or `http2stream.destroy()`. Will be 1330`undefined` if the `Http2Stream` has not been closed. 1331 1332#### `http2stream.sentHeaders` 1333 1334<!-- YAML 1335added: v9.5.0 1336--> 1337 1338* {HTTP/2 Headers Object} 1339 1340An object containing the outbound headers sent for this `Http2Stream`. 1341 1342#### `http2stream.sentInfoHeaders` 1343 1344<!-- YAML 1345added: v9.5.0 1346--> 1347 1348* {HTTP/2 Headers Object\[]} 1349 1350An array of objects containing the outbound informational (additional) headers 1351sent for this `Http2Stream`. 1352 1353#### `http2stream.sentTrailers` 1354 1355<!-- YAML 1356added: v9.5.0 1357--> 1358 1359* {HTTP/2 Headers Object} 1360 1361An object containing the outbound trailers sent for this `HttpStream`. 1362 1363#### `http2stream.session` 1364 1365<!-- YAML 1366added: v8.4.0 1367--> 1368 1369* {Http2Session} 1370 1371A reference to the `Http2Session` instance that owns this `Http2Stream`. The 1372value will be `undefined` after the `Http2Stream` instance is destroyed. 1373 1374#### `http2stream.setTimeout(msecs, callback)` 1375 1376<!-- YAML 1377added: v8.4.0 1378changes: 1379 - version: v18.0.0 1380 pr-url: https://github.com/nodejs/node/pull/41678 1381 description: Passing an invalid callback to the `callback` argument 1382 now throws `ERR_INVALID_ARG_TYPE` instead of 1383 `ERR_INVALID_CALLBACK`. 1384--> 1385 1386* `msecs` {number} 1387* `callback` {Function} 1388 1389```js 1390const http2 = require('node:http2'); 1391const client = http2.connect('http://example.org:8000'); 1392const { NGHTTP2_CANCEL } = http2.constants; 1393const req = client.request({ ':path': '/' }); 1394 1395// Cancel the stream if there's no activity after 5 seconds 1396req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); 1397``` 1398 1399#### `http2stream.state` 1400 1401<!-- YAML 1402added: v8.4.0 1403--> 1404 1405Provides miscellaneous information about the current state of the 1406`Http2Stream`. 1407 1408* {Object} 1409 * `localWindowSize` {number} The number of bytes the connected peer may send 1410 for this `Http2Stream` without receiving a `WINDOW_UPDATE`. 1411 * `state` {number} A flag indicating the low-level current state of the 1412 `Http2Stream` as determined by `nghttp2`. 1413 * `localClose` {number} `1` if this `Http2Stream` has been closed locally. 1414 * `remoteClose` {number} `1` if this `Http2Stream` has been closed 1415 remotely. 1416 * `sumDependencyWeight` {number} The sum weight of all `Http2Stream` 1417 instances that depend on this `Http2Stream` as specified using 1418 `PRIORITY` frames. 1419 * `weight` {number} The priority weight of this `Http2Stream`. 1420 1421A current state of this `Http2Stream`. 1422 1423#### `http2stream.sendTrailers(headers)` 1424 1425<!-- YAML 1426added: v10.0.0 1427--> 1428 1429* `headers` {HTTP/2 Headers Object} 1430 1431Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method 1432will cause the `Http2Stream` to be immediately closed and must only be 1433called after the `'wantTrailers'` event has been emitted. When sending a 1434request or sending a response, the `options.waitForTrailers` option must be set 1435in order to keep the `Http2Stream` open after the final `DATA` frame so that 1436trailers can be sent. 1437 1438```js 1439const http2 = require('node:http2'); 1440const server = http2.createServer(); 1441server.on('stream', (stream) => { 1442 stream.respond(undefined, { waitForTrailers: true }); 1443 stream.on('wantTrailers', () => { 1444 stream.sendTrailers({ xyz: 'abc' }); 1445 }); 1446 stream.end('Hello World'); 1447}); 1448``` 1449 1450The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header 1451fields (e.g. `':method'`, `':path'`, etc). 1452 1453### Class: `ClientHttp2Stream` 1454 1455<!-- YAML 1456added: v8.4.0 1457--> 1458 1459* Extends {Http2Stream} 1460 1461The `ClientHttp2Stream` class is an extension of `Http2Stream` that is 1462used exclusively on HTTP/2 Clients. `Http2Stream` instances on the client 1463provide events such as `'response'` and `'push'` that are only relevant on 1464the client. 1465 1466#### Event: `'continue'` 1467 1468<!-- YAML 1469added: v8.5.0 1470--> 1471 1472Emitted when the server sends a `100 Continue` status, usually because 1473the request contained `Expect: 100-continue`. This is an instruction that 1474the client should send the request body. 1475 1476#### Event: `'headers'` 1477 1478<!-- YAML 1479added: v8.4.0 1480--> 1481 1482* `headers` {HTTP/2 Headers Object} 1483* `flags` {number} 1484 1485The `'headers'` event is emitted when an additional block of headers is received 1486for a stream, such as when a block of `1xx` informational headers is received. 1487The listener callback is passed the [HTTP/2 Headers Object][] and flags 1488associated with the headers. 1489 1490```js 1491stream.on('headers', (headers, flags) => { 1492 console.log(headers); 1493}); 1494``` 1495 1496#### Event: `'push'` 1497 1498<!-- YAML 1499added: v8.4.0 1500--> 1501 1502* `headers` {HTTP/2 Headers Object} 1503* `flags` {number} 1504 1505The `'push'` event is emitted when response headers for a Server Push stream 1506are received. The listener callback is passed the [HTTP/2 Headers Object][] and 1507flags associated with the headers. 1508 1509```js 1510stream.on('push', (headers, flags) => { 1511 console.log(headers); 1512}); 1513``` 1514 1515#### Event: `'response'` 1516 1517<!-- YAML 1518added: v8.4.0 1519--> 1520 1521* `headers` {HTTP/2 Headers Object} 1522* `flags` {number} 1523 1524The `'response'` event is emitted when a response `HEADERS` frame has been 1525received for this stream from the connected HTTP/2 server. The listener is 1526invoked with two arguments: an `Object` containing the received 1527[HTTP/2 Headers Object][], and flags associated with the headers. 1528 1529```js 1530const http2 = require('node:http2'); 1531const client = http2.connect('https://localhost'); 1532const req = client.request({ ':path': '/' }); 1533req.on('response', (headers, flags) => { 1534 console.log(headers[':status']); 1535}); 1536``` 1537 1538### Class: `ServerHttp2Stream` 1539 1540<!-- YAML 1541added: v8.4.0 1542--> 1543 1544* Extends: {Http2Stream} 1545 1546The `ServerHttp2Stream` class is an extension of [`Http2Stream`][] that is 1547used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server 1548provide additional methods such as `http2stream.pushStream()` and 1549`http2stream.respond()` that are only relevant on the server. 1550 1551#### `http2stream.additionalHeaders(headers)` 1552 1553<!-- YAML 1554added: v8.4.0 1555--> 1556 1557* `headers` {HTTP/2 Headers Object} 1558 1559Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. 1560 1561#### `http2stream.headersSent` 1562 1563<!-- YAML 1564added: v8.4.0 1565--> 1566 1567* {boolean} 1568 1569True if headers were sent, false otherwise (read-only). 1570 1571#### `http2stream.pushAllowed` 1572 1573<!-- YAML 1574added: v8.4.0 1575--> 1576 1577* {boolean} 1578 1579Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote 1580client's most recent `SETTINGS` frame. Will be `true` if the remote peer 1581accepts push streams, `false` otherwise. Settings are the same for every 1582`Http2Stream` in the same `Http2Session`. 1583 1584#### `http2stream.pushStream(headers[, options], callback)` 1585 1586<!-- YAML 1587added: v8.4.0 1588changes: 1589 - version: v18.0.0 1590 pr-url: https://github.com/nodejs/node/pull/41678 1591 description: Passing an invalid callback to the `callback` argument 1592 now throws `ERR_INVALID_ARG_TYPE` instead of 1593 `ERR_INVALID_CALLBACK`. 1594--> 1595 1596* `headers` {HTTP/2 Headers Object} 1597* `options` {Object} 1598 * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, 1599 the created stream is made the sole direct dependency of the parent, with 1600 all other existing dependents made a dependent of the newly created stream. 1601 **Default:** `false`. 1602 * `parent` {number} Specifies the numeric identifier of a stream the newly 1603 created stream is dependent on. 1604* `callback` {Function} Callback that is called once the push stream has been 1605 initiated. 1606 * `err` {Error} 1607 * `pushStream` {ServerHttp2Stream} The returned `pushStream` object. 1608 * `headers` {HTTP/2 Headers Object} Headers object the `pushStream` was 1609 initiated with. 1610 1611Initiates a push stream. The callback is invoked with the new `Http2Stream` 1612instance created for the push stream passed as the second argument, or an 1613`Error` passed as the first argument. 1614 1615```js 1616const http2 = require('node:http2'); 1617const server = http2.createServer(); 1618server.on('stream', (stream) => { 1619 stream.respond({ ':status': 200 }); 1620 stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { 1621 if (err) throw err; 1622 pushStream.respond({ ':status': 200 }); 1623 pushStream.end('some pushed data'); 1624 }); 1625 stream.end('some data'); 1626}); 1627``` 1628 1629Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass 1630a `weight` value to `http2stream.priority` with the `silent` option set to 1631`true` to enable server-side bandwidth balancing between concurrent streams. 1632 1633Calling `http2stream.pushStream()` from within a pushed stream is not permitted 1634and will throw an error. 1635 1636#### `http2stream.respond([headers[, options]])` 1637 1638<!-- YAML 1639added: v8.4.0 1640changes: 1641 - version: 1642 - v14.5.0 1643 - v12.19.0 1644 pr-url: https://github.com/nodejs/node/pull/33160 1645 description: Allow explicitly setting date headers. 1646--> 1647 1648* `headers` {HTTP/2 Headers Object} 1649* `options` {Object} 1650 * `endStream` {boolean} Set to `true` to indicate that the response will not 1651 include payload data. 1652 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1653 `'wantTrailers'` event after the final `DATA` frame has been sent. 1654 1655```js 1656const http2 = require('node:http2'); 1657const server = http2.createServer(); 1658server.on('stream', (stream) => { 1659 stream.respond({ ':status': 200 }); 1660 stream.end('some data'); 1661}); 1662``` 1663 1664Initiates a response. When the `options.waitForTrailers` option is set, the 1665`'wantTrailers'` event will be emitted immediately after queuing the last chunk 1666of payload data to be sent. The `http2stream.sendTrailers()` method can then be 1667used to sent trailing header fields to the peer. 1668 1669When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1670close when the final `DATA` frame is transmitted. User code must call either 1671`http2stream.sendTrailers()` or `http2stream.close()` to close the 1672`Http2Stream`. 1673 1674```js 1675const http2 = require('node:http2'); 1676const server = http2.createServer(); 1677server.on('stream', (stream) => { 1678 stream.respond({ ':status': 200 }, { waitForTrailers: true }); 1679 stream.on('wantTrailers', () => { 1680 stream.sendTrailers({ ABC: 'some value to send' }); 1681 }); 1682 stream.end('some data'); 1683}); 1684``` 1685 1686#### `http2stream.respondWithFD(fd[, headers[, options]])` 1687 1688<!-- YAML 1689added: v8.4.0 1690changes: 1691 - version: 1692 - v14.5.0 1693 - v12.19.0 1694 pr-url: https://github.com/nodejs/node/pull/33160 1695 description: Allow explicitly setting date headers. 1696 - version: v12.12.0 1697 pr-url: https://github.com/nodejs/node/pull/29876 1698 description: The `fd` option may now be a `FileHandle`. 1699 - version: v10.0.0 1700 pr-url: https://github.com/nodejs/node/pull/18936 1701 description: Any readable file descriptor, not necessarily for a 1702 regular file, is supported now. 1703--> 1704 1705* `fd` {number|FileHandle} A readable file descriptor. 1706* `headers` {HTTP/2 Headers Object} 1707* `options` {Object} 1708 * `statCheck` {Function} 1709 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1710 `'wantTrailers'` event after the final `DATA` frame has been sent. 1711 * `offset` {number} The offset position at which to begin reading. 1712 * `length` {number} The amount of data from the fd to send. 1713 1714Initiates a response whose data is read from the given file descriptor. No 1715validation is performed on the given file descriptor. If an error occurs while 1716attempting to read data using the file descriptor, the `Http2Stream` will be 1717closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. 1718 1719When used, the `Http2Stream` object's `Duplex` interface will be closed 1720automatically. 1721 1722```js 1723const http2 = require('node:http2'); 1724const fs = require('node:fs'); 1725 1726const server = http2.createServer(); 1727server.on('stream', (stream) => { 1728 const fd = fs.openSync('/some/file', 'r'); 1729 1730 const stat = fs.fstatSync(fd); 1731 const headers = { 1732 'content-length': stat.size, 1733 'last-modified': stat.mtime.toUTCString(), 1734 'content-type': 'text/plain; charset=utf-8', 1735 }; 1736 stream.respondWithFD(fd, headers); 1737 stream.on('close', () => fs.closeSync(fd)); 1738}); 1739``` 1740 1741The optional `options.statCheck` function may be specified to give user code 1742an opportunity to set additional content headers based on the `fs.Stat` details 1743of the given fd. If the `statCheck` function is provided, the 1744`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to 1745collect details on the provided file descriptor. 1746 1747The `offset` and `length` options may be used to limit the response to a 1748specific range subset. This can be used, for instance, to support HTTP Range 1749requests. 1750 1751The file descriptor or `FileHandle` is not closed when the stream is closed, 1752so it will need to be closed manually once it is no longer needed. 1753Using the same file descriptor concurrently for multiple streams 1754is not supported and may result in data loss. Re-using a file descriptor 1755after a stream has finished is supported. 1756 1757When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 1758will be emitted immediately after queuing the last chunk of payload data to be 1759sent. The `http2stream.sendTrailers()` method can then be used to sent trailing 1760header fields to the peer. 1761 1762When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1763close when the final `DATA` frame is transmitted. User code _must_ call either 1764`http2stream.sendTrailers()` or `http2stream.close()` to close the 1765`Http2Stream`. 1766 1767```js 1768const http2 = require('node:http2'); 1769const fs = require('node:fs'); 1770 1771const server = http2.createServer(); 1772server.on('stream', (stream) => { 1773 const fd = fs.openSync('/some/file', 'r'); 1774 1775 const stat = fs.fstatSync(fd); 1776 const headers = { 1777 'content-length': stat.size, 1778 'last-modified': stat.mtime.toUTCString(), 1779 'content-type': 'text/plain; charset=utf-8', 1780 }; 1781 stream.respondWithFD(fd, headers, { waitForTrailers: true }); 1782 stream.on('wantTrailers', () => { 1783 stream.sendTrailers({ ABC: 'some value to send' }); 1784 }); 1785 1786 stream.on('close', () => fs.closeSync(fd)); 1787}); 1788``` 1789 1790#### `http2stream.respondWithFile(path[, headers[, options]])` 1791 1792<!-- YAML 1793added: v8.4.0 1794changes: 1795 - version: 1796 - v14.5.0 1797 - v12.19.0 1798 pr-url: https://github.com/nodejs/node/pull/33160 1799 description: Allow explicitly setting date headers. 1800 - version: v10.0.0 1801 pr-url: https://github.com/nodejs/node/pull/18936 1802 description: Any readable file, not necessarily a 1803 regular file, is supported now. 1804--> 1805 1806* `path` {string|Buffer|URL} 1807* `headers` {HTTP/2 Headers Object} 1808* `options` {Object} 1809 * `statCheck` {Function} 1810 * `onError` {Function} Callback function invoked in the case of an 1811 error before send. 1812 * `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the 1813 `'wantTrailers'` event after the final `DATA` frame has been sent. 1814 * `offset` {number} The offset position at which to begin reading. 1815 * `length` {number} The amount of data from the fd to send. 1816 1817Sends a regular file as the response. The `path` must specify a regular file 1818or an `'error'` event will be emitted on the `Http2Stream` object. 1819 1820When used, the `Http2Stream` object's `Duplex` interface will be closed 1821automatically. 1822 1823The optional `options.statCheck` function may be specified to give user code 1824an opportunity to set additional content headers based on the `fs.Stat` details 1825of the given file: 1826 1827If an error occurs while attempting to read the file data, the `Http2Stream` 1828will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` 1829code. If the `onError` callback is defined, then it will be called. Otherwise 1830the stream will be destroyed. 1831 1832Example using a file path: 1833 1834```js 1835const http2 = require('node:http2'); 1836const server = http2.createServer(); 1837server.on('stream', (stream) => { 1838 function statCheck(stat, headers) { 1839 headers['last-modified'] = stat.mtime.toUTCString(); 1840 } 1841 1842 function onError(err) { 1843 // stream.respond() can throw if the stream has been destroyed by 1844 // the other side. 1845 try { 1846 if (err.code === 'ENOENT') { 1847 stream.respond({ ':status': 404 }); 1848 } else { 1849 stream.respond({ ':status': 500 }); 1850 } 1851 } catch (err) { 1852 // Perform actual error handling. 1853 console.error(err); 1854 } 1855 stream.end(); 1856 } 1857 1858 stream.respondWithFile('/some/file', 1859 { 'content-type': 'text/plain; charset=utf-8' }, 1860 { statCheck, onError }); 1861}); 1862``` 1863 1864The `options.statCheck` function may also be used to cancel the send operation 1865by returning `false`. For instance, a conditional request may check the stat 1866results to determine if the file has been modified to return an appropriate 1867`304` response: 1868 1869```js 1870const http2 = require('node:http2'); 1871const server = http2.createServer(); 1872server.on('stream', (stream) => { 1873 function statCheck(stat, headers) { 1874 // Check the stat here... 1875 stream.respond({ ':status': 304 }); 1876 return false; // Cancel the send operation 1877 } 1878 stream.respondWithFile('/some/file', 1879 { 'content-type': 'text/plain; charset=utf-8' }, 1880 { statCheck }); 1881}); 1882``` 1883 1884The `content-length` header field will be automatically set. 1885 1886The `offset` and `length` options may be used to limit the response to a 1887specific range subset. This can be used, for instance, to support HTTP Range 1888requests. 1889 1890The `options.onError` function may also be used to handle all the errors 1891that could happen before the delivery of the file is initiated. The 1892default behavior is to destroy the stream. 1893 1894When the `options.waitForTrailers` option is set, the `'wantTrailers'` event 1895will be emitted immediately after queuing the last chunk of payload data to be 1896sent. The `http2stream.sendTrailers()` method can then be used to sent trailing 1897header fields to the peer. 1898 1899When `options.waitForTrailers` is set, the `Http2Stream` will not automatically 1900close when the final `DATA` frame is transmitted. User code must call either 1901`http2stream.sendTrailers()` or `http2stream.close()` to close the 1902`Http2Stream`. 1903 1904```js 1905const http2 = require('node:http2'); 1906const server = http2.createServer(); 1907server.on('stream', (stream) => { 1908 stream.respondWithFile('/some/file', 1909 { 'content-type': 'text/plain; charset=utf-8' }, 1910 { waitForTrailers: true }); 1911 stream.on('wantTrailers', () => { 1912 stream.sendTrailers({ ABC: 'some value to send' }); 1913 }); 1914}); 1915``` 1916 1917### Class: `Http2Server` 1918 1919<!-- YAML 1920added: v8.4.0 1921--> 1922 1923* Extends: {net.Server} 1924 1925Instances of `Http2Server` are created using the `http2.createServer()` 1926function. The `Http2Server` class is not exported directly by the 1927`node:http2` module. 1928 1929#### Event: `'checkContinue'` 1930 1931<!-- YAML 1932added: v8.5.0 1933--> 1934 1935* `request` {http2.Http2ServerRequest} 1936* `response` {http2.Http2ServerResponse} 1937 1938If a [`'request'`][] listener is registered or [`http2.createServer()`][] is 1939supplied a callback function, the `'checkContinue'` event is emitted each time 1940a request with an HTTP `Expect: 100-continue` is received. If this event is 1941not listened for, the server will automatically respond with a status 1942`100 Continue` as appropriate. 1943 1944Handling this event involves calling [`response.writeContinue()`][] if the 1945client should continue to send the request body, or generating an appropriate 1946HTTP response (e.g. 400 Bad Request) if the client should not continue to send 1947the request body. 1948 1949When this event is emitted and handled, the [`'request'`][] event will 1950not be emitted. 1951 1952#### Event: `'connection'` 1953 1954<!-- YAML 1955added: v8.4.0 1956--> 1957 1958* `socket` {stream.Duplex} 1959 1960This event is emitted when a new TCP stream is established. `socket` is 1961typically an object of type [`net.Socket`][]. Usually users will not want to 1962access this event. 1963 1964This event can also be explicitly emitted by users to inject connections 1965into the HTTP server. In that case, any [`Duplex`][] stream can be passed. 1966 1967#### Event: `'request'` 1968 1969<!-- YAML 1970added: v8.4.0 1971--> 1972 1973* `request` {http2.Http2ServerRequest} 1974* `response` {http2.Http2ServerResponse} 1975 1976Emitted each time there is a request. There may be multiple requests 1977per session. See the [Compatibility API][]. 1978 1979#### Event: `'session'` 1980 1981<!-- YAML 1982added: v8.4.0 1983--> 1984 1985* `session` {ServerHttp2Session} 1986 1987The `'session'` event is emitted when a new `Http2Session` is created by the 1988`Http2Server`. 1989 1990#### Event: `'sessionError'` 1991 1992<!-- YAML 1993added: v8.4.0 1994--> 1995 1996* `error` {Error} 1997* `session` {ServerHttp2Session} 1998 1999The `'sessionError'` event is emitted when an `'error'` event is emitted by 2000an `Http2Session` object associated with the `Http2Server`. 2001 2002#### Event: `'stream'` 2003 2004<!-- YAML 2005added: v8.4.0 2006--> 2007 2008* `stream` {Http2Stream} A reference to the stream 2009* `headers` {HTTP/2 Headers Object} An object describing the headers 2010* `flags` {number} The associated numeric flags 2011* `rawHeaders` {Array} An array containing the raw header names followed by 2012 their respective values. 2013 2014The `'stream'` event is emitted when a `'stream'` event has been emitted by 2015an `Http2Session` associated with the server. 2016 2017See also [`Http2Session`'s `'stream'` event][]. 2018 2019```js 2020const http2 = require('node:http2'); 2021const { 2022 HTTP2_HEADER_METHOD, 2023 HTTP2_HEADER_PATH, 2024 HTTP2_HEADER_STATUS, 2025 HTTP2_HEADER_CONTENT_TYPE, 2026} = http2.constants; 2027 2028const server = http2.createServer(); 2029server.on('stream', (stream, headers, flags) => { 2030 const method = headers[HTTP2_HEADER_METHOD]; 2031 const path = headers[HTTP2_HEADER_PATH]; 2032 // ... 2033 stream.respond({ 2034 [HTTP2_HEADER_STATUS]: 200, 2035 [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8', 2036 }); 2037 stream.write('hello '); 2038 stream.end('world'); 2039}); 2040``` 2041 2042#### Event: `'timeout'` 2043 2044<!-- YAML 2045added: v8.4.0 2046changes: 2047 - version: v13.0.0 2048 pr-url: https://github.com/nodejs/node/pull/27558 2049 description: The default timeout changed from 120s to 0 (no timeout). 2050--> 2051 2052The `'timeout'` event is emitted when there is no activity on the Server for 2053a given number of milliseconds set using `http2server.setTimeout()`. 2054**Default:** 0 (no timeout) 2055 2056#### `server.close([callback])` 2057 2058<!-- YAML 2059added: v8.4.0 2060--> 2061 2062* `callback` {Function} 2063 2064Stops the server from establishing new sessions. This does not prevent new 2065request streams from being created due to the persistent nature of HTTP/2 2066sessions. To gracefully shut down the server, call [`http2session.close()`][] on 2067all active sessions. 2068 2069If `callback` is provided, it is not invoked until all active sessions have been 2070closed, although the server has already stopped allowing new sessions. See 2071[`net.Server.close()`][] for more details. 2072 2073#### `server.setTimeout([msecs][, callback])` 2074 2075<!-- YAML 2076added: v8.4.0 2077changes: 2078 - version: v18.0.0 2079 pr-url: https://github.com/nodejs/node/pull/41678 2080 description: Passing an invalid callback to the `callback` argument 2081 now throws `ERR_INVALID_ARG_TYPE` instead of 2082 `ERR_INVALID_CALLBACK`. 2083 - version: v13.0.0 2084 pr-url: https://github.com/nodejs/node/pull/27558 2085 description: The default timeout changed from 120s to 0 (no timeout). 2086--> 2087 2088* `msecs` {number} **Default:** 0 (no timeout) 2089* `callback` {Function} 2090* Returns: {Http2Server} 2091 2092Used to set the timeout value for http2 server requests, 2093and sets a callback function that is called when there is no activity 2094on the `Http2Server` after `msecs` milliseconds. 2095 2096The given callback is registered as a listener on the `'timeout'` event. 2097 2098In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` 2099error will be thrown. 2100 2101#### `server.timeout` 2102 2103<!-- YAML 2104added: v8.4.0 2105changes: 2106 - version: v13.0.0 2107 pr-url: https://github.com/nodejs/node/pull/27558 2108 description: The default timeout changed from 120s to 0 (no timeout). 2109--> 2110 2111* {number} Timeout in milliseconds. **Default:** 0 (no timeout) 2112 2113The number of milliseconds of inactivity before a socket is presumed 2114to have timed out. 2115 2116A value of `0` will disable the timeout behavior on incoming connections. 2117 2118The socket timeout logic is set up on connection, so changing this 2119value only affects new connections to the server, not any existing connections. 2120 2121#### `server.updateSettings([settings])` 2122 2123<!-- YAML 2124added: 2125 - v15.1.0 2126 - v14.17.0 2127--> 2128 2129* `settings` {HTTP/2 Settings Object} 2130 2131Used to update the server with the provided settings. 2132 2133Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. 2134 2135Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. 2136 2137### Class: `Http2SecureServer` 2138 2139<!-- YAML 2140added: v8.4.0 2141--> 2142 2143* Extends: {tls.Server} 2144 2145Instances of `Http2SecureServer` are created using the 2146`http2.createSecureServer()` function. The `Http2SecureServer` class is not 2147exported directly by the `node:http2` module. 2148 2149#### Event: `'checkContinue'` 2150 2151<!-- YAML 2152added: v8.5.0 2153--> 2154 2155* `request` {http2.Http2ServerRequest} 2156* `response` {http2.Http2ServerResponse} 2157 2158If a [`'request'`][] listener is registered or [`http2.createSecureServer()`][] 2159is supplied a callback function, the `'checkContinue'` event is emitted each 2160time a request with an HTTP `Expect: 100-continue` is received. If this event 2161is not listened for, the server will automatically respond with a status 2162`100 Continue` as appropriate. 2163 2164Handling this event involves calling [`response.writeContinue()`][] if the 2165client should continue to send the request body, or generating an appropriate 2166HTTP response (e.g. 400 Bad Request) if the client should not continue to send 2167the request body. 2168 2169When this event is emitted and handled, the [`'request'`][] event will 2170not be emitted. 2171 2172#### Event: `'connection'` 2173 2174<!-- YAML 2175added: v8.4.0 2176--> 2177 2178* `socket` {stream.Duplex} 2179 2180This event is emitted when a new TCP stream is established, before the TLS 2181handshake begins. `socket` is typically an object of type [`net.Socket`][]. 2182Usually users will not want to access this event. 2183 2184This event can also be explicitly emitted by users to inject connections 2185into the HTTP server. In that case, any [`Duplex`][] stream can be passed. 2186 2187#### Event: `'request'` 2188 2189<!-- YAML 2190added: v8.4.0 2191--> 2192 2193* `request` {http2.Http2ServerRequest} 2194* `response` {http2.Http2ServerResponse} 2195 2196Emitted each time there is a request. There may be multiple requests 2197per session. See the [Compatibility API][]. 2198 2199#### Event: `'session'` 2200 2201<!-- YAML 2202added: v8.4.0 2203--> 2204 2205* `session` {ServerHttp2Session} 2206 2207The `'session'` event is emitted when a new `Http2Session` is created by the 2208`Http2SecureServer`. 2209 2210#### Event: `'sessionError'` 2211 2212<!-- YAML 2213added: v8.4.0 2214--> 2215 2216* `error` {Error} 2217* `session` {ServerHttp2Session} 2218 2219The `'sessionError'` event is emitted when an `'error'` event is emitted by 2220an `Http2Session` object associated with the `Http2SecureServer`. 2221 2222#### Event: `'stream'` 2223 2224<!-- YAML 2225added: v8.4.0 2226--> 2227 2228* `stream` {Http2Stream} A reference to the stream 2229* `headers` {HTTP/2 Headers Object} An object describing the headers 2230* `flags` {number} The associated numeric flags 2231* `rawHeaders` {Array} An array containing the raw header names followed by 2232 their respective values. 2233 2234The `'stream'` event is emitted when a `'stream'` event has been emitted by 2235an `Http2Session` associated with the server. 2236 2237See also [`Http2Session`'s `'stream'` event][]. 2238 2239```js 2240const http2 = require('node:http2'); 2241const { 2242 HTTP2_HEADER_METHOD, 2243 HTTP2_HEADER_PATH, 2244 HTTP2_HEADER_STATUS, 2245 HTTP2_HEADER_CONTENT_TYPE, 2246} = http2.constants; 2247 2248const options = getOptionsSomehow(); 2249 2250const server = http2.createSecureServer(options); 2251server.on('stream', (stream, headers, flags) => { 2252 const method = headers[HTTP2_HEADER_METHOD]; 2253 const path = headers[HTTP2_HEADER_PATH]; 2254 // ... 2255 stream.respond({ 2256 [HTTP2_HEADER_STATUS]: 200, 2257 [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8', 2258 }); 2259 stream.write('hello '); 2260 stream.end('world'); 2261}); 2262``` 2263 2264#### Event: `'timeout'` 2265 2266<!-- YAML 2267added: v8.4.0 2268--> 2269 2270The `'timeout'` event is emitted when there is no activity on the Server for 2271a given number of milliseconds set using `http2secureServer.setTimeout()`. 2272**Default:** 2 minutes. 2273 2274#### Event: `'unknownProtocol'` 2275 2276<!-- YAML 2277added: v8.4.0 2278--> 2279 2280* `socket` {stream.Duplex} 2281 2282The `'unknownProtocol'` event is emitted when a connecting client fails to 2283negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler 2284receives the socket for handling. If no listener is registered for this event, 2285the connection is terminated. A timeout may be specified using the 2286`'unknownProtocolTimeout'` option passed to [`http2.createSecureServer()`][]. 2287See the [Compatibility API][]. 2288 2289#### `server.close([callback])` 2290 2291<!-- YAML 2292added: v8.4.0 2293--> 2294 2295* `callback` {Function} 2296 2297Stops the server from establishing new sessions. This does not prevent new 2298request streams from being created due to the persistent nature of HTTP/2 2299sessions. To gracefully shut down the server, call [`http2session.close()`][] on 2300all active sessions. 2301 2302If `callback` is provided, it is not invoked until all active sessions have been 2303closed, although the server has already stopped allowing new sessions. See 2304[`tls.Server.close()`][] for more details. 2305 2306#### `server.setTimeout([msecs][, callback])` 2307 2308<!-- YAML 2309added: v8.4.0 2310changes: 2311 - version: v18.0.0 2312 pr-url: https://github.com/nodejs/node/pull/41678 2313 description: Passing an invalid callback to the `callback` argument 2314 now throws `ERR_INVALID_ARG_TYPE` instead of 2315 `ERR_INVALID_CALLBACK`. 2316--> 2317 2318* `msecs` {number} **Default:** `120000` (2 minutes) 2319* `callback` {Function} 2320* Returns: {Http2SecureServer} 2321 2322Used to set the timeout value for http2 secure server requests, 2323and sets a callback function that is called when there is no activity 2324on the `Http2SecureServer` after `msecs` milliseconds. 2325 2326The given callback is registered as a listener on the `'timeout'` event. 2327 2328In case if `callback` is not a function, a new `ERR_INVALID_ARG_TYPE` 2329error will be thrown. 2330 2331#### `server.timeout` 2332 2333<!-- YAML 2334added: v8.4.0 2335changes: 2336 - version: v13.0.0 2337 pr-url: https://github.com/nodejs/node/pull/27558 2338 description: The default timeout changed from 120s to 0 (no timeout). 2339--> 2340 2341* {number} Timeout in milliseconds. **Default:** 0 (no timeout) 2342 2343The number of milliseconds of inactivity before a socket is presumed 2344to have timed out. 2345 2346A value of `0` will disable the timeout behavior on incoming connections. 2347 2348The socket timeout logic is set up on connection, so changing this 2349value only affects new connections to the server, not any existing connections. 2350 2351#### `server.updateSettings([settings])` 2352 2353<!-- YAML 2354added: 2355 - v15.1.0 2356 - v14.17.0 2357--> 2358 2359* `settings` {HTTP/2 Settings Object} 2360 2361Used to update the server with the provided settings. 2362 2363Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. 2364 2365Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. 2366 2367### `http2.createServer([options][, onRequestHandler])` 2368 2369<!-- YAML 2370added: v8.4.0 2371changes: 2372 - version: 2373 - v15.10.0 2374 - v14.16.0 2375 - v12.21.0 2376 - v10.24.0 2377 pr-url: https://github.com/nodejs-private/node-private/pull/246 2378 description: Added `unknownProtocolTimeout` option with a default of 10000. 2379 - version: 2380 - v14.4.0 2381 - v12.18.0 2382 - v10.21.0 2383 commit: 3948830ce6408be620b09a70bf66158623022af0 2384 pr-url: https://github.com/nodejs-private/node-private/pull/204 2385 description: Added `maxSettings` option with a default of 32. 2386 - version: 2387 - v13.3.0 2388 - v12.16.0 2389 pr-url: https://github.com/nodejs/node/pull/30534 2390 description: Added `maxSessionRejectedStreams` option with a default of 100. 2391 - version: 2392 - v13.3.0 2393 - v12.16.0 2394 pr-url: https://github.com/nodejs/node/pull/30534 2395 description: Added `maxSessionInvalidFrames` option with a default of 1000. 2396 - version: v13.0.0 2397 pr-url: https://github.com/nodejs/node/pull/29144 2398 description: The `PADDING_STRATEGY_CALLBACK` has been made equivalent to 2399 providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` 2400 has been removed. 2401 - version: v12.4.0 2402 pr-url: https://github.com/nodejs/node/pull/27782 2403 description: The `options` parameter now supports `net.createServer()` 2404 options. 2405 - version: v9.6.0 2406 pr-url: https://github.com/nodejs/node/pull/15752 2407 description: Added the `Http1IncomingMessage` and `Http1ServerResponse` 2408 option. 2409 - version: v8.9.3 2410 pr-url: https://github.com/nodejs/node/pull/17105 2411 description: Added the `maxOutstandingPings` option with a default limit of 2412 10. 2413 - version: v8.9.3 2414 pr-url: https://github.com/nodejs/node/pull/16676 2415 description: Added the `maxHeaderListPairs` option with a default limit of 2416 128 header pairs. 2417--> 2418 2419* `options` {Object} 2420 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 2421 for deflating header fields. **Default:** `4Kib`. 2422 * `maxSettings` {number} Sets the maximum number of settings entries per 2423 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 2424 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 2425 is permitted to use. The value is expressed in terms of number of megabytes, 2426 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. 2427 This is a credit based limit, existing `Http2Stream`s may cause this 2428 limit to be exceeded, but new `Http2Stream` instances will be rejected 2429 while this limit is exceeded. The current number of `Http2Stream` sessions, 2430 the current memory use of the header compression tables, current data 2431 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 2432 counted towards the current limit. **Default:** `10`. 2433 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 2434 This is similar to [`server.maxHeadersCount`][] or 2435 [`request.maxHeadersCount`][] in the `node:http` module. The minimum value 2436 is `4`. **Default:** `128`. 2437 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 2438 unacknowledged pings. **Default:** `10`. 2439 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 2440 serialized, compressed block of headers. Attempts to send headers that 2441 exceed this limit will result in a `'frameError'` event being emitted 2442 and the stream being closed and destroyed. 2443 While this sets the maximum allowed size to the entire block of headers, 2444 `nghttp2` (the internal http2 library) has a limit of `65536` 2445 for each decompressed key/value pair. 2446 * `paddingStrategy` {number} The strategy used for determining the amount of 2447 padding to use for `HEADERS` and `DATA` frames. **Default:** 2448 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 2449 * `http2.constants.PADDING_STRATEGY_NONE`: No padding is applied. 2450 * `http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, 2451 determined by the internal implementation, is applied. 2452 * `http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough 2453 padding to ensure that the total frame length, including the 9-byte 2454 header, is a multiple of 8. For each frame, there is a maximum allowed 2455 number of padding bytes that is determined by current flow control state 2456 and settings. If this maximum is less than the calculated amount needed to 2457 ensure alignment, the maximum is used and the total frame length is not 2458 necessarily aligned at 8 bytes. 2459 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 2460 streams for the remote peer as if a `SETTINGS` frame had been received. Will 2461 be overridden if the remote peer sets its own value for 2462 `maxConcurrentStreams`. **Default:** `100`. 2463 * `maxSessionInvalidFrames` {integer} Sets the maximum number of invalid 2464 frames that will be tolerated before the session is closed. 2465 **Default:** `1000`. 2466 * `maxSessionRejectedStreams` {integer} Sets the maximum number of rejected 2467 upon creation streams that will be tolerated before the session is closed. 2468 Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` 2469 error that should tell the peer to not open any more streams, continuing 2470 to open streams is therefore regarded as a sign of a misbehaving peer. 2471 **Default:** `100`. 2472 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 2473 remote peer upon connection. 2474 * `Http1IncomingMessage` {http.IncomingMessage} Specifies the 2475 `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending 2476 the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`. 2477 * `Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` 2478 class to used for HTTP/1 fallback. Useful for extending the original 2479 `http.ServerResponse`. **Default:** `http.ServerResponse`. 2480 * `Http2ServerRequest` {http2.Http2ServerRequest} Specifies the 2481 `Http2ServerRequest` class to use. 2482 Useful for extending the original `Http2ServerRequest`. 2483 **Default:** `Http2ServerRequest`. 2484 * `Http2ServerResponse` {http2.Http2ServerResponse} Specifies the 2485 `Http2ServerResponse` class to use. 2486 Useful for extending the original `Http2ServerResponse`. 2487 **Default:** `Http2ServerResponse`. 2488 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 2489 a server should wait when an [`'unknownProtocol'`][] is emitted. If the 2490 socket has not been destroyed by that time the server will destroy it. 2491 **Default:** `10000`. 2492 * ...: Any [`net.createServer()`][] option can be provided. 2493* `onRequestHandler` {Function} See [Compatibility API][] 2494* Returns: {Http2Server} 2495 2496Returns a `net.Server` instance that creates and manages `Http2Session` 2497instances. 2498 2499Since there are no browsers known that support 2500[unencrypted HTTP/2][HTTP/2 Unencrypted], the use of 2501[`http2.createSecureServer()`][] is necessary when communicating 2502with browser clients. 2503 2504```js 2505const http2 = require('node:http2'); 2506 2507// Create an unencrypted HTTP/2 server. 2508// Since there are no browsers known that support 2509// unencrypted HTTP/2, the use of `http2.createSecureServer()` 2510// is necessary when communicating with browser clients. 2511const server = http2.createServer(); 2512 2513server.on('stream', (stream, headers) => { 2514 stream.respond({ 2515 'content-type': 'text/html; charset=utf-8', 2516 ':status': 200, 2517 }); 2518 stream.end('<h1>Hello World</h1>'); 2519}); 2520 2521server.listen(8000); 2522``` 2523 2524### `http2.createSecureServer(options[, onRequestHandler])` 2525 2526<!-- YAML 2527added: v8.4.0 2528changes: 2529 - version: 2530 - v15.10.0 2531 - v14.16.0 2532 - v12.21.0 2533 - v10.24.0 2534 pr-url: https://github.com/nodejs-private/node-private/pull/246 2535 description: Added `unknownProtocolTimeout` option with a default of 10000. 2536 - version: 2537 - v14.4.0 2538 - v12.18.0 2539 - v10.21.0 2540 commit: 3948830ce6408be620b09a70bf66158623022af0 2541 pr-url: https://github.com/nodejs-private/node-private/pull/204 2542 description: Added `maxSettings` option with a default of 32. 2543 - version: 2544 - v13.3.0 2545 - v12.16.0 2546 pr-url: https://github.com/nodejs/node/pull/30534 2547 description: Added `maxSessionRejectedStreams` option with a default of 100. 2548 - version: 2549 - v13.3.0 2550 - v12.16.0 2551 pr-url: https://github.com/nodejs/node/pull/30534 2552 description: Added `maxSessionInvalidFrames` option with a default of 1000. 2553 - version: v13.0.0 2554 pr-url: https://github.com/nodejs/node/pull/29144 2555 description: The `PADDING_STRATEGY_CALLBACK` has been made equivalent to 2556 providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` 2557 has been removed. 2558 - version: v10.12.0 2559 pr-url: https://github.com/nodejs/node/pull/22956 2560 description: Added the `origins` option to automatically send an `ORIGIN` 2561 frame on `Http2Session` startup. 2562 - version: v8.9.3 2563 pr-url: https://github.com/nodejs/node/pull/17105 2564 description: Added the `maxOutstandingPings` option with a default limit of 2565 10. 2566 - version: v8.9.3 2567 pr-url: https://github.com/nodejs/node/pull/16676 2568 description: Added the `maxHeaderListPairs` option with a default limit of 2569 128 header pairs. 2570--> 2571 2572* `options` {Object} 2573 * `allowHTTP1` {boolean} Incoming client connections that do not support 2574 HTTP/2 will be downgraded to HTTP/1.x when set to `true`. 2575 See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. 2576 **Default:** `false`. 2577 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 2578 for deflating header fields. **Default:** `4Kib`. 2579 * `maxSettings` {number} Sets the maximum number of settings entries per 2580 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 2581 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 2582 is permitted to use. The value is expressed in terms of number of megabytes, 2583 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a 2584 credit based limit, existing `Http2Stream`s may cause this 2585 limit to be exceeded, but new `Http2Stream` instances will be rejected 2586 while this limit is exceeded. The current number of `Http2Stream` sessions, 2587 the current memory use of the header compression tables, current data 2588 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 2589 counted towards the current limit. **Default:** `10`. 2590 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 2591 This is similar to [`server.maxHeadersCount`][] or 2592 [`request.maxHeadersCount`][] in the `node:http` module. The minimum value 2593 is `4`. **Default:** `128`. 2594 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 2595 unacknowledged pings. **Default:** `10`. 2596 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 2597 serialized, compressed block of headers. Attempts to send headers that 2598 exceed this limit will result in a `'frameError'` event being emitted 2599 and the stream being closed and destroyed. 2600 * `paddingStrategy` {number} Strategy used for determining the amount of 2601 padding to use for `HEADERS` and `DATA` frames. **Default:** 2602 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 2603 * `http2.constants.PADDING_STRATEGY_NONE`: No padding is applied. 2604 * `http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, 2605 determined by the internal implementation, is applied. 2606 * `http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough 2607 padding to ensure that the total frame length, including the 2608 9-byte header, is a multiple of 8. For each frame, there is a maximum 2609 allowed number of padding bytes that is determined by current flow control 2610 state and settings. If this maximum is less than the calculated amount 2611 needed to ensure alignment, the maximum is used and the total frame length 2612 is not necessarily aligned at 8 bytes. 2613 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 2614 streams for the remote peer as if a `SETTINGS` frame had been received. Will 2615 be overridden if the remote peer sets its own value for 2616 `maxConcurrentStreams`. **Default:** `100`. 2617 * `maxSessionInvalidFrames` {integer} Sets the maximum number of invalid 2618 frames that will be tolerated before the session is closed. 2619 **Default:** `1000`. 2620 * `maxSessionRejectedStreams` {integer} Sets the maximum number of rejected 2621 upon creation streams that will be tolerated before the session is closed. 2622 Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` 2623 error that should tell the peer to not open any more streams, continuing 2624 to open streams is therefore regarded as a sign of a misbehaving peer. 2625 **Default:** `100`. 2626 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 2627 remote peer upon connection. 2628 * ...: Any [`tls.createServer()`][] options can be provided. For 2629 servers, the identity options (`pfx` or `key`/`cert`) are usually required. 2630 * `origins` {string\[]} An array of origin strings to send within an `ORIGIN` 2631 frame immediately following creation of a new server `Http2Session`. 2632 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 2633 a server should wait when an [`'unknownProtocol'`][] event is emitted. If 2634 the socket has not been destroyed by that time the server will destroy it. 2635 **Default:** `10000`. 2636* `onRequestHandler` {Function} See [Compatibility API][] 2637* Returns: {Http2SecureServer} 2638 2639Returns a `tls.Server` instance that creates and manages `Http2Session` 2640instances. 2641 2642```js 2643const http2 = require('node:http2'); 2644const fs = require('node:fs'); 2645 2646const options = { 2647 key: fs.readFileSync('server-key.pem'), 2648 cert: fs.readFileSync('server-cert.pem'), 2649}; 2650 2651// Create a secure HTTP/2 server 2652const server = http2.createSecureServer(options); 2653 2654server.on('stream', (stream, headers) => { 2655 stream.respond({ 2656 'content-type': 'text/html; charset=utf-8', 2657 ':status': 200, 2658 }); 2659 stream.end('<h1>Hello World</h1>'); 2660}); 2661 2662server.listen(8443); 2663``` 2664 2665### `http2.connect(authority[, options][, listener])` 2666 2667<!-- YAML 2668added: v8.4.0 2669changes: 2670 - version: 2671 - v15.10.0 2672 - v14.16.0 2673 - v12.21.0 2674 - v10.24.0 2675 pr-url: https://github.com/nodejs-private/node-private/pull/246 2676 description: Added `unknownProtocolTimeout` option with a default of 10000. 2677 - version: 2678 - v14.4.0 2679 - v12.18.0 2680 - v10.21.0 2681 commit: 3948830ce6408be620b09a70bf66158623022af0 2682 pr-url: https://github.com/nodejs-private/node-private/pull/204 2683 description: Added `maxSettings` option with a default of 32. 2684 - version: v13.0.0 2685 pr-url: https://github.com/nodejs/node/pull/29144 2686 description: The `PADDING_STRATEGY_CALLBACK` has been made equivalent to 2687 providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` 2688 has been removed. 2689 - version: v8.9.3 2690 pr-url: https://github.com/nodejs/node/pull/17105 2691 description: Added the `maxOutstandingPings` option with a default limit of 2692 10. 2693 - version: v8.9.3 2694 pr-url: https://github.com/nodejs/node/pull/16676 2695 description: Added the `maxHeaderListPairs` option with a default limit of 2696 128 header pairs. 2697--> 2698 2699* `authority` {string|URL} The remote HTTP/2 server to connect to. This must 2700 be in the form of a minimal, valid URL with the `http://` or `https://` 2701 prefix, host name, and IP port (if a non-default port is used). Userinfo 2702 (user ID and password), path, querystring, and fragment details in the 2703 URL will be ignored. 2704* `options` {Object} 2705 * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size 2706 for deflating header fields. **Default:** `4Kib`. 2707 * `maxSettings` {number} Sets the maximum number of settings entries per 2708 `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`. 2709 * `maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` 2710 is permitted to use. The value is expressed in terms of number of megabytes, 2711 e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. 2712 This is a credit based limit, existing `Http2Stream`s may cause this 2713 limit to be exceeded, but new `Http2Stream` instances will be rejected 2714 while this limit is exceeded. The current number of `Http2Stream` sessions, 2715 the current memory use of the header compression tables, current data 2716 queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all 2717 counted towards the current limit. **Default:** `10`. 2718 * `maxHeaderListPairs` {number} Sets the maximum number of header entries. 2719 This is similar to [`server.maxHeadersCount`][] or 2720 [`request.maxHeadersCount`][] in the `node:http` module. The minimum value 2721 is `1`. **Default:** `128`. 2722 * `maxOutstandingPings` {number} Sets the maximum number of outstanding, 2723 unacknowledged pings. **Default:** `10`. 2724 * `maxReservedRemoteStreams` {number} Sets the maximum number of reserved push 2725 streams the client will accept at any given time. Once the current number of 2726 currently reserved push streams exceeds reaches this limit, new push streams 2727 sent by the server will be automatically rejected. The minimum allowed value 2728 is 0. The maximum allowed value is 2<sup>32</sup>-1. A negative value sets 2729 this option to the maximum allowed value. **Default:** `200`. 2730 * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a 2731 serialized, compressed block of headers. Attempts to send headers that 2732 exceed this limit will result in a `'frameError'` event being emitted 2733 and the stream being closed and destroyed. 2734 * `paddingStrategy` {number} Strategy used for determining the amount of 2735 padding to use for `HEADERS` and `DATA` frames. **Default:** 2736 `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of: 2737 * `http2.constants.PADDING_STRATEGY_NONE`: No padding is applied. 2738 * `http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, 2739 determined by the internal implementation, is applied. 2740 * `http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough 2741 padding to ensure that the total frame length, including the 2742 9-byte header, is a multiple of 8. For each frame, there is a maximum 2743 allowed number of padding bytes that is determined by current flow control 2744 state and settings. If this maximum is less than the calculated amount 2745 needed to ensure alignment, the maximum is used and the total frame length 2746 is not necessarily aligned at 8 bytes. 2747 * `peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent 2748 streams for the remote peer as if a `SETTINGS` frame had been received. Will 2749 be overridden if the remote peer sets its own value for 2750 `maxConcurrentStreams`. **Default:** `100`. 2751 * `protocol` {string} The protocol to connect with, if not set in the 2752 `authority`. Value may be either `'http:'` or `'https:'`. **Default:** 2753 `'https:'` 2754 * `settings` {HTTP/2 Settings Object} The initial settings to send to the 2755 remote peer upon connection. 2756 * `createConnection` {Function} An optional callback that receives the `URL` 2757 instance passed to `connect` and the `options` object, and returns any 2758 [`Duplex`][] stream that is to be used as the connection for this session. 2759 * ...: Any [`net.connect()`][] or [`tls.connect()`][] options can be provided. 2760 * `unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that 2761 a server should wait when an [`'unknownProtocol'`][] event is emitted. If 2762 the socket has not been destroyed by that time the server will destroy it. 2763 **Default:** `10000`. 2764* `listener` {Function} Will be registered as a one-time listener of the 2765 [`'connect'`][] event. 2766* Returns: {ClientHttp2Session} 2767 2768Returns a `ClientHttp2Session` instance. 2769 2770```js 2771const http2 = require('node:http2'); 2772const client = http2.connect('https://localhost:1234'); 2773 2774/* Use the client */ 2775 2776client.close(); 2777``` 2778 2779### `http2.constants` 2780 2781<!-- YAML 2782added: v8.4.0 2783--> 2784 2785#### Error codes for `RST_STREAM` and `GOAWAY` 2786 2787| Value | Name | Constant | 2788| ------ | ------------------- | --------------------------------------------- | 2789| `0x00` | No Error | `http2.constants.NGHTTP2_NO_ERROR` | 2790| `0x01` | Protocol Error | `http2.constants.NGHTTP2_PROTOCOL_ERROR` | 2791| `0x02` | Internal Error | `http2.constants.NGHTTP2_INTERNAL_ERROR` | 2792| `0x03` | Flow Control Error | `http2.constants.NGHTTP2_FLOW_CONTROL_ERROR` | 2793| `0x04` | Settings Timeout | `http2.constants.NGHTTP2_SETTINGS_TIMEOUT` | 2794| `0x05` | Stream Closed | `http2.constants.NGHTTP2_STREAM_CLOSED` | 2795| `0x06` | Frame Size Error | `http2.constants.NGHTTP2_FRAME_SIZE_ERROR` | 2796| `0x07` | Refused Stream | `http2.constants.NGHTTP2_REFUSED_STREAM` | 2797| `0x08` | Cancel | `http2.constants.NGHTTP2_CANCEL` | 2798| `0x09` | Compression Error | `http2.constants.NGHTTP2_COMPRESSION_ERROR` | 2799| `0x0a` | Connect Error | `http2.constants.NGHTTP2_CONNECT_ERROR` | 2800| `0x0b` | Enhance Your Calm | `http2.constants.NGHTTP2_ENHANCE_YOUR_CALM` | 2801| `0x0c` | Inadequate Security | `http2.constants.NGHTTP2_INADEQUATE_SECURITY` | 2802| `0x0d` | HTTP/1.1 Required | `http2.constants.NGHTTP2_HTTP_1_1_REQUIRED` | 2803 2804The `'timeout'` event is emitted when there is no activity on the Server for 2805a given number of milliseconds set using `http2server.setTimeout()`. 2806 2807### `http2.getDefaultSettings()` 2808 2809<!-- YAML 2810added: v8.4.0 2811--> 2812 2813* Returns: {HTTP/2 Settings Object} 2814 2815Returns an object containing the default settings for an `Http2Session` 2816instance. This method returns a new object instance every time it is called 2817so instances returned may be safely modified for use. 2818 2819### `http2.getPackedSettings([settings])` 2820 2821<!-- YAML 2822added: v8.4.0 2823--> 2824 2825* `settings` {HTTP/2 Settings Object} 2826* Returns: {Buffer} 2827 2828Returns a `Buffer` instance containing serialized representation of the given 2829HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended 2830for use with the `HTTP2-Settings` header field. 2831 2832```js 2833const http2 = require('node:http2'); 2834 2835const packed = http2.getPackedSettings({ enablePush: false }); 2836 2837console.log(packed.toString('base64')); 2838// Prints: AAIAAAAA 2839``` 2840 2841### `http2.getUnpackedSettings(buf)` 2842 2843<!-- YAML 2844added: v8.4.0 2845--> 2846 2847* `buf` {Buffer|TypedArray} The packed settings. 2848* Returns: {HTTP/2 Settings Object} 2849 2850Returns a [HTTP/2 Settings Object][] containing the deserialized settings from 2851the given `Buffer` as generated by `http2.getPackedSettings()`. 2852 2853### `http2.sensitiveHeaders` 2854 2855<!-- YAML 2856added: 2857 - v15.0.0 2858 - v14.18.0 2859--> 2860 2861* {symbol} 2862 2863This symbol can be set as a property on the HTTP/2 headers object with an array 2864value in order to provide a list of headers considered sensitive. 2865See [Sensitive headers][] for more details. 2866 2867### Headers object 2868 2869Headers are represented as own-properties on JavaScript objects. The property 2870keys will be serialized to lower-case. Property values should be strings (if 2871they are not they will be coerced to strings) or an `Array` of strings (in order 2872to send more than one value per header field). 2873 2874```js 2875const headers = { 2876 ':status': '200', 2877 'content-type': 'text-plain', 2878 'ABC': ['has', 'more', 'than', 'one', 'value'], 2879}; 2880 2881stream.respond(headers); 2882``` 2883 2884Header objects passed to callback functions will have a `null` prototype. This 2885means that normal JavaScript object methods such as 2886`Object.prototype.toString()` and `Object.prototype.hasOwnProperty()` will 2887not work. 2888 2889For incoming headers: 2890 2891* The `:status` header is converted to `number`. 2892* Duplicates of `:status`, `:method`, `:authority`, `:scheme`, `:path`, 2893 `:protocol`, `age`, `authorization`, `access-control-allow-credentials`, 2894 `access-control-max-age`, `access-control-request-method`, `content-encoding`, 2895 `content-language`, `content-length`, `content-location`, `content-md5`, 2896 `content-range`, `content-type`, `date`, `dnt`, `etag`, `expires`, `from`, 2897 `host`, `if-match`, `if-modified-since`, `if-none-match`, `if-range`, 2898 `if-unmodified-since`, `last-modified`, `location`, `max-forwards`, 2899 `proxy-authorization`, `range`, `referer`,`retry-after`, `tk`, 2900 `upgrade-insecure-requests`, `user-agent` or `x-content-type-options` are 2901 discarded. 2902* `set-cookie` is always an array. Duplicates are added to the array. 2903* For duplicate `cookie` headers, the values are joined together with '; '. 2904* For all other headers, the values are joined together with ', '. 2905 2906```js 2907const http2 = require('node:http2'); 2908const server = http2.createServer(); 2909server.on('stream', (stream, headers) => { 2910 console.log(headers[':path']); 2911 console.log(headers.ABC); 2912}); 2913``` 2914 2915#### Sensitive headers 2916 2917HTTP2 headers can be marked as sensitive, which means that the HTTP/2 2918header compression algorithm will never index them. This can make sense for 2919header values with low entropy and that may be considered valuable to an 2920attacker, for example `Cookie` or `Authorization`. To achieve this, add 2921the header name to the `[http2.sensitiveHeaders]` property as an array: 2922 2923```js 2924const headers = { 2925 ':status': '200', 2926 'content-type': 'text-plain', 2927 'cookie': 'some-cookie', 2928 'other-sensitive-header': 'very secret data', 2929 [http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header'], 2930}; 2931 2932stream.respond(headers); 2933``` 2934 2935For some headers, such as `Authorization` and short `Cookie` headers, 2936this flag is set automatically. 2937 2938This property is also set for received headers. It will contain the names of 2939all headers marked as sensitive, including ones marked that way automatically. 2940 2941### Settings object 2942 2943<!-- YAML 2944added: v8.4.0 2945changes: 2946 - version: v12.12.0 2947 pr-url: https://github.com/nodejs/node/pull/29833 2948 description: The `maxConcurrentStreams` setting is stricter. 2949 - version: v8.9.3 2950 pr-url: https://github.com/nodejs/node/pull/16676 2951 description: The `maxHeaderListSize` setting is now strictly enforced. 2952--> 2953 2954The `http2.getDefaultSettings()`, `http2.getPackedSettings()`, 2955`http2.createServer()`, `http2.createSecureServer()`, 2956`http2session.settings()`, `http2session.localSettings`, and 2957`http2session.remoteSettings` APIs either return or receive as input an 2958object that defines configuration settings for an `Http2Session` object. 2959These objects are ordinary JavaScript objects containing the following 2960properties. 2961 2962* `headerTableSize` {number} Specifies the maximum number of bytes used for 2963 header compression. The minimum allowed value is 0. The maximum allowed value 2964 is 2<sup>32</sup>-1. **Default:** `4096`. 2965* `enablePush` {boolean} Specifies `true` if HTTP/2 Push Streams are to be 2966 permitted on the `Http2Session` instances. **Default:** `true`. 2967* `initialWindowSize` {number} Specifies the _sender's_ initial window size in 2968 bytes for stream-level flow control. The minimum allowed value is 0. The 2969 maximum allowed value is 2<sup>32</sup>-1. **Default:** `65535`. 2970* `maxFrameSize` {number} Specifies the size in bytes of the largest frame 2971 payload. The minimum allowed value is 16,384. The maximum allowed value is 2972 2<sup>24</sup>-1. **Default:** `16384`. 2973* `maxConcurrentStreams` {number} Specifies the maximum number of concurrent 2974 streams permitted on an `Http2Session`. There is no default value which 2975 implies, at least theoretically, 2<sup>32</sup>-1 streams may be open 2976 concurrently at any given time in an `Http2Session`. The minimum value 2977 is 0. The maximum allowed value is 2<sup>32</sup>-1. **Default:** 2978 `4294967295`. 2979* `maxHeaderListSize` {number} Specifies the maximum size (uncompressed octets) 2980 of header list that will be accepted. The minimum allowed value is 0. The 2981 maximum allowed value is 2<sup>32</sup>-1. **Default:** `65535`. 2982* `maxHeaderSize` {number} Alias for `maxHeaderListSize`. 2983* `enableConnectProtocol`{boolean} Specifies `true` if the "Extended Connect 2984 Protocol" defined by [RFC 8441][] is to be enabled. This setting is only 2985 meaningful if sent by the server. Once the `enableConnectProtocol` setting 2986 has been enabled for a given `Http2Session`, it cannot be disabled. 2987 **Default:** `false`. 2988 2989All additional properties on the settings object are ignored. 2990 2991### Error handling 2992 2993There are several types of error conditions that may arise when using the 2994`node:http2` module: 2995 2996Validation errors occur when an incorrect argument, option, or setting value is 2997passed in. These will always be reported by a synchronous `throw`. 2998 2999State errors occur when an action is attempted at an incorrect time (for 3000instance, attempting to send data on a stream after it has closed). These will 3001be reported using either a synchronous `throw` or via an `'error'` event on 3002the `Http2Stream`, `Http2Session` or HTTP/2 Server objects, depending on where 3003and when the error occurs. 3004 3005Internal errors occur when an HTTP/2 session fails unexpectedly. These will be 3006reported via an `'error'` event on the `Http2Session` or HTTP/2 Server objects. 3007 3008Protocol errors occur when various HTTP/2 protocol constraints are violated. 3009These will be reported using either a synchronous `throw` or via an `'error'` 3010event on the `Http2Stream`, `Http2Session` or HTTP/2 Server objects, depending 3011on where and when the error occurs. 3012 3013### Invalid character handling in header names and values 3014 3015The HTTP/2 implementation applies stricter handling of invalid characters in 3016HTTP header names and values than the HTTP/1 implementation. 3017 3018Header field names are _case-insensitive_ and are transmitted over the wire 3019strictly as lower-case strings. The API provided by Node.js allows header 3020names to be set as mixed-case strings (e.g. `Content-Type`) but will convert 3021those to lower-case (e.g. `content-type`) upon transmission. 3022 3023Header field-names _must only_ contain one or more of the following ASCII 3024characters: `a`-`z`, `A`-`Z`, `0`-`9`, `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`, 3025`-`, `.`, `^`, `_`, `` ` `` (backtick), `|`, and `~`. 3026 3027Using invalid characters within an HTTP header field name will cause the 3028stream to be closed with a protocol error being reported. 3029 3030Header field values are handled with more leniency but _should_ not contain 3031new-line or carriage return characters and _should_ be limited to US-ASCII 3032characters, per the requirements of the HTTP specification. 3033 3034### Push streams on the client 3035 3036To receive pushed streams on the client, set a listener for the `'stream'` 3037event on the `ClientHttp2Session`: 3038 3039```js 3040const http2 = require('node:http2'); 3041 3042const client = http2.connect('http://localhost'); 3043 3044client.on('stream', (pushedStream, requestHeaders) => { 3045 pushedStream.on('push', (responseHeaders) => { 3046 // Process response headers 3047 }); 3048 pushedStream.on('data', (chunk) => { /* handle pushed data */ }); 3049}); 3050 3051const req = client.request({ ':path': '/' }); 3052``` 3053 3054### Supporting the `CONNECT` method 3055 3056The `CONNECT` method is used to allow an HTTP/2 server to be used as a proxy 3057for TCP/IP connections. 3058 3059A simple TCP Server: 3060 3061```js 3062const net = require('node:net'); 3063 3064const server = net.createServer((socket) => { 3065 let name = ''; 3066 socket.setEncoding('utf8'); 3067 socket.on('data', (chunk) => name += chunk); 3068 socket.on('end', () => socket.end(`hello ${name}`)); 3069}); 3070 3071server.listen(8000); 3072``` 3073 3074An HTTP/2 CONNECT proxy: 3075 3076```js 3077const http2 = require('node:http2'); 3078const { NGHTTP2_REFUSED_STREAM } = http2.constants; 3079const net = require('node:net'); 3080 3081const proxy = http2.createServer(); 3082proxy.on('stream', (stream, headers) => { 3083 if (headers[':method'] !== 'CONNECT') { 3084 // Only accept CONNECT requests 3085 stream.close(NGHTTP2_REFUSED_STREAM); 3086 return; 3087 } 3088 const auth = new URL(`tcp://${headers[':authority']}`); 3089 // It's a very good idea to verify that hostname and port are 3090 // things this proxy should be connecting to. 3091 const socket = net.connect(auth.port, auth.hostname, () => { 3092 stream.respond(); 3093 socket.pipe(stream); 3094 stream.pipe(socket); 3095 }); 3096 socket.on('error', (error) => { 3097 stream.close(http2.constants.NGHTTP2_CONNECT_ERROR); 3098 }); 3099}); 3100 3101proxy.listen(8001); 3102``` 3103 3104An HTTP/2 CONNECT client: 3105 3106```js 3107const http2 = require('node:http2'); 3108 3109const client = http2.connect('http://localhost:8001'); 3110 3111// Must not specify the ':path' and ':scheme' headers 3112// for CONNECT requests or an error will be thrown. 3113const req = client.request({ 3114 ':method': 'CONNECT', 3115 ':authority': 'localhost:8000', 3116}); 3117 3118req.on('response', (headers) => { 3119 console.log(headers[http2.constants.HTTP2_HEADER_STATUS]); 3120}); 3121let data = ''; 3122req.setEncoding('utf8'); 3123req.on('data', (chunk) => data += chunk); 3124req.on('end', () => { 3125 console.log(`The server says: ${data}`); 3126 client.close(); 3127}); 3128req.end('Jane'); 3129``` 3130 3131### The extended `CONNECT` protocol 3132 3133[RFC 8441][] defines an "Extended CONNECT Protocol" extension to HTTP/2 that 3134may be used to bootstrap the use of an `Http2Stream` using the `CONNECT` 3135method as a tunnel for other communication protocols (such as WebSockets). 3136 3137The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using 3138the `enableConnectProtocol` setting: 3139 3140```js 3141const http2 = require('node:http2'); 3142const settings = { enableConnectProtocol: true }; 3143const server = http2.createServer({ settings }); 3144``` 3145 3146Once the client receives the `SETTINGS` frame from the server indicating that 3147the extended CONNECT may be used, it may send `CONNECT` requests that use the 3148`':protocol'` HTTP/2 pseudo-header: 3149 3150```js 3151const http2 = require('node:http2'); 3152const client = http2.connect('http://localhost:8080'); 3153client.on('remoteSettings', (settings) => { 3154 if (settings.enableConnectProtocol) { 3155 const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' }); 3156 // ... 3157 } 3158}); 3159``` 3160 3161## Compatibility API 3162 3163The Compatibility API has the goal of providing a similar developer experience 3164of HTTP/1 when using HTTP/2, making it possible to develop applications 3165that support both [HTTP/1][] and HTTP/2. This API targets only the 3166**public API** of the [HTTP/1][]. However many modules use internal 3167methods or state, and those _are not supported_ as it is a completely 3168different implementation. 3169 3170The following example creates an HTTP/2 server using the compatibility 3171API: 3172 3173```js 3174const http2 = require('node:http2'); 3175const server = http2.createServer((req, res) => { 3176 res.setHeader('Content-Type', 'text/html'); 3177 res.setHeader('X-Foo', 'bar'); 3178 res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); 3179 res.end('ok'); 3180}); 3181``` 3182 3183In order to create a mixed [HTTPS][] and HTTP/2 server, refer to the 3184[ALPN negotiation][] section. 3185Upgrading from non-tls HTTP/1 servers is not supported. 3186 3187The HTTP/2 compatibility API is composed of [`Http2ServerRequest`][] and 3188[`Http2ServerResponse`][]. They aim at API compatibility with HTTP/1, but 3189they do not hide the differences between the protocols. As an example, 3190the status message for HTTP codes is ignored. 3191 3192### ALPN negotiation 3193 3194ALPN negotiation allows supporting both [HTTPS][] and HTTP/2 over 3195the same socket. The `req` and `res` objects can be either HTTP/1 or 3196HTTP/2, and an application **must** restrict itself to the public API of 3197[HTTP/1][], and detect if it is possible to use the more advanced 3198features of HTTP/2. 3199 3200The following example creates a server that supports both protocols: 3201 3202```js 3203const { createSecureServer } = require('node:http2'); 3204const { readFileSync } = require('node:fs'); 3205 3206const cert = readFileSync('./cert.pem'); 3207const key = readFileSync('./key.pem'); 3208 3209const server = createSecureServer( 3210 { cert, key, allowHTTP1: true }, 3211 onRequest, 3212).listen(4443); 3213 3214function onRequest(req, res) { 3215 // Detects if it is a HTTPS request or HTTP/2 3216 const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? 3217 req.stream.session : req; 3218 res.writeHead(200, { 'content-type': 'application/json' }); 3219 res.end(JSON.stringify({ 3220 alpnProtocol, 3221 httpVersion: req.httpVersion, 3222 })); 3223} 3224``` 3225 3226The `'request'` event works identically on both [HTTPS][] and 3227HTTP/2. 3228 3229### Class: `http2.Http2ServerRequest` 3230 3231<!-- YAML 3232added: v8.4.0 3233--> 3234 3235* Extends: {stream.Readable} 3236 3237A `Http2ServerRequest` object is created by [`http2.Server`][] or 3238[`http2.SecureServer`][] and passed as the first argument to the 3239[`'request'`][] event. It may be used to access a request status, headers, and 3240data. 3241 3242#### Event: `'aborted'` 3243 3244<!-- YAML 3245added: v8.4.0 3246--> 3247 3248The `'aborted'` event is emitted whenever a `Http2ServerRequest` instance is 3249abnormally aborted in mid-communication. 3250 3251The `'aborted'` event will only be emitted if the `Http2ServerRequest` writable 3252side has not been ended. 3253 3254#### Event: `'close'` 3255 3256<!-- YAML 3257added: v8.4.0 3258--> 3259 3260Indicates that the underlying [`Http2Stream`][] was closed. 3261Just like `'end'`, this event occurs only once per response. 3262 3263#### `request.aborted` 3264 3265<!-- YAML 3266added: v10.1.0 3267--> 3268 3269* {boolean} 3270 3271The `request.aborted` property will be `true` if the request has 3272been aborted. 3273 3274#### `request.authority` 3275 3276<!-- YAML 3277added: v8.4.0 3278--> 3279 3280* {string} 3281 3282The request authority pseudo header field. Because HTTP/2 allows requests 3283to set either `:authority` or `host`, this value is derived from 3284`req.headers[':authority']` if present. Otherwise, it is derived from 3285`req.headers['host']`. 3286 3287#### `request.complete` 3288 3289<!-- YAML 3290added: v12.10.0 3291--> 3292 3293* {boolean} 3294 3295The `request.complete` property will be `true` if the request has 3296been completed, aborted, or destroyed. 3297 3298#### `request.connection` 3299 3300<!-- YAML 3301added: v8.4.0 3302deprecated: v13.0.0 3303--> 3304 3305> Stability: 0 - Deprecated. Use [`request.socket`][]. 3306 3307* {net.Socket|tls.TLSSocket} 3308 3309See [`request.socket`][]. 3310 3311#### `request.destroy([error])` 3312 3313<!-- YAML 3314added: v8.4.0 3315--> 3316 3317* `error` {Error} 3318 3319Calls `destroy()` on the [`Http2Stream`][] that received 3320the [`Http2ServerRequest`][]. If `error` is provided, an `'error'` event 3321is emitted and `error` is passed as an argument to any listeners on the event. 3322 3323It does nothing if the stream was already destroyed. 3324 3325#### `request.headers` 3326 3327<!-- YAML 3328added: v8.4.0 3329--> 3330 3331* {Object} 3332 3333The request/response headers object. 3334 3335Key-value pairs of header names and values. Header names are lower-cased. 3336 3337```js 3338// Prints something like: 3339// 3340// { 'user-agent': 'curl/7.22.0', 3341// host: '127.0.0.1:8000', 3342// accept: '*/*' } 3343console.log(request.headers); 3344``` 3345 3346See [HTTP/2 Headers Object][]. 3347 3348In HTTP/2, the request path, host name, protocol, and method are represented as 3349special headers prefixed with the `:` character (e.g. `':path'`). These special 3350headers will be included in the `request.headers` object. Care must be taken not 3351to inadvertently modify these special headers or errors may occur. For instance, 3352removing all headers from the request will cause errors to occur: 3353 3354```js 3355removeAllHeaders(request.headers); 3356assert(request.url); // Fails because the :path header has been removed 3357``` 3358 3359#### `request.httpVersion` 3360 3361<!-- YAML 3362added: v8.4.0 3363--> 3364 3365* {string} 3366 3367In case of server request, the HTTP version sent by the client. In the case of 3368client response, the HTTP version of the connected-to server. Returns 3369`'2.0'`. 3370 3371Also `message.httpVersionMajor` is the first integer and 3372`message.httpVersionMinor` is the second. 3373 3374#### `request.method` 3375 3376<!-- YAML 3377added: v8.4.0 3378--> 3379 3380* {string} 3381 3382The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. 3383 3384#### `request.rawHeaders` 3385 3386<!-- YAML 3387added: v8.4.0 3388--> 3389 3390* {string\[]} 3391 3392The raw request/response headers list exactly as they were received. 3393 3394The keys and values are in the same list. It is _not_ a 3395list of tuples. So, the even-numbered offsets are key values, and the 3396odd-numbered offsets are the associated values. 3397 3398Header names are not lowercased, and duplicates are not merged. 3399 3400```js 3401// Prints something like: 3402// 3403// [ 'user-agent', 3404// 'this is invalid because there can be only one', 3405// 'User-Agent', 3406// 'curl/7.22.0', 3407// 'Host', 3408// '127.0.0.1:8000', 3409// 'ACCEPT', 3410// '*/*' ] 3411console.log(request.rawHeaders); 3412``` 3413 3414#### `request.rawTrailers` 3415 3416<!-- YAML 3417added: v8.4.0 3418--> 3419 3420* {string\[]} 3421 3422The raw request/response trailer keys and values exactly as they were 3423received. Only populated at the `'end'` event. 3424 3425#### `request.scheme` 3426 3427<!-- YAML 3428added: v8.4.0 3429--> 3430 3431* {string} 3432 3433The request scheme pseudo header field indicating the scheme 3434portion of the target URL. 3435 3436#### `request.setTimeout(msecs, callback)` 3437 3438<!-- YAML 3439added: v8.4.0 3440--> 3441 3442* `msecs` {number} 3443* `callback` {Function} 3444* Returns: {http2.Http2ServerRequest} 3445 3446Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is 3447provided, then it is added as a listener on the `'timeout'` event on 3448the response object. 3449 3450If no `'timeout'` listener is added to the request, the response, or 3451the server, then [`Http2Stream`][]s are destroyed when they time out. If a 3452handler is assigned to the request, the response, or the server's `'timeout'` 3453events, timed out sockets must be handled explicitly. 3454 3455#### `request.socket` 3456 3457<!-- YAML 3458added: v8.4.0 3459--> 3460 3461* {net.Socket|tls.TLSSocket} 3462 3463Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 3464applies getters, setters, and methods based on HTTP/2 logic. 3465 3466`destroyed`, `readable`, and `writable` properties will be retrieved from and 3467set on `request.stream`. 3468 3469`destroy`, `emit`, `end`, `on` and `once` methods will be called on 3470`request.stream`. 3471 3472`setTimeout` method will be called on `request.stream.session`. 3473 3474`pause`, `read`, `resume`, and `write` will throw an error with code 3475`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See [`Http2Session` and Sockets][] for 3476more information. 3477 3478All other interactions will be routed directly to the socket. With TLS support, 3479use [`request.socket.getPeerCertificate()`][] to obtain the client's 3480authentication details. 3481 3482#### `request.stream` 3483 3484<!-- YAML 3485added: v8.4.0 3486--> 3487 3488* {Http2Stream} 3489 3490The [`Http2Stream`][] object backing the request. 3491 3492#### `request.trailers` 3493 3494<!-- YAML 3495added: v8.4.0 3496--> 3497 3498* {Object} 3499 3500The request/response trailers object. Only populated at the `'end'` event. 3501 3502#### `request.url` 3503 3504<!-- YAML 3505added: v8.4.0 3506--> 3507 3508* {string} 3509 3510Request URL string. This contains only the URL that is present in the actual 3511HTTP request. If the request is: 3512 3513```http 3514GET /status?name=ryan HTTP/1.1 3515Accept: text/plain 3516``` 3517 3518Then `request.url` will be: 3519 3520<!-- eslint-disable semi --> 3521 3522```js 3523'/status?name=ryan' 3524``` 3525 3526To parse the url into its parts, `new URL()` can be used: 3527 3528```console 3529$ node 3530> new URL('/status?name=ryan', 'http://example.com') 3531URL { 3532 href: 'http://example.com/status?name=ryan', 3533 origin: 'http://example.com', 3534 protocol: 'http:', 3535 username: '', 3536 password: '', 3537 host: 'example.com', 3538 hostname: 'example.com', 3539 port: '', 3540 pathname: '/status', 3541 search: '?name=ryan', 3542 searchParams: URLSearchParams { 'name' => 'ryan' }, 3543 hash: '' 3544} 3545``` 3546 3547### Class: `http2.Http2ServerResponse` 3548 3549<!-- YAML 3550added: v8.4.0 3551--> 3552 3553* Extends: {Stream} 3554 3555This object is created internally by an HTTP server, not by the user. It is 3556passed as the second parameter to the [`'request'`][] event. 3557 3558#### Event: `'close'` 3559 3560<!-- YAML 3561added: v8.4.0 3562--> 3563 3564Indicates that the underlying [`Http2Stream`][] was terminated before 3565[`response.end()`][] was called or able to flush. 3566 3567#### Event: `'finish'` 3568 3569<!-- YAML 3570added: v8.4.0 3571--> 3572 3573Emitted when the response has been sent. More specifically, this event is 3574emitted when the last segment of the response headers and body have been 3575handed off to the HTTP/2 multiplexing for transmission over the network. It 3576does not imply that the client has received anything yet. 3577 3578After this event, no more events will be emitted on the response object. 3579 3580#### `response.addTrailers(headers)` 3581 3582<!-- YAML 3583added: v8.4.0 3584--> 3585 3586* `headers` {Object} 3587 3588This method adds HTTP trailing headers (a header but at the end of the 3589message) to the response. 3590 3591Attempting to set a header field name or value that contains invalid characters 3592will result in a [`TypeError`][] being thrown. 3593 3594#### `response.connection` 3595 3596<!-- YAML 3597added: v8.4.0 3598deprecated: v13.0.0 3599--> 3600 3601> Stability: 0 - Deprecated. Use [`response.socket`][]. 3602 3603* {net.Socket|tls.TLSSocket} 3604 3605See [`response.socket`][]. 3606 3607#### `response.createPushResponse(headers, callback)` 3608 3609<!-- YAML 3610added: v8.4.0 3611changes: 3612 - version: v18.0.0 3613 pr-url: https://github.com/nodejs/node/pull/41678 3614 description: Passing an invalid callback to the `callback` argument 3615 now throws `ERR_INVALID_ARG_TYPE` instead of 3616 `ERR_INVALID_CALLBACK`. 3617--> 3618 3619* `headers` {HTTP/2 Headers Object} An object describing the headers 3620* `callback` {Function} Called once `http2stream.pushStream()` is finished, 3621 or either when the attempt to create the pushed `Http2Stream` has failed or 3622 has been rejected, or the state of `Http2ServerRequest` is closed prior to 3623 calling the `http2stream.pushStream()` method 3624 * `err` {Error} 3625 * `res` {http2.Http2ServerResponse} The newly-created `Http2ServerResponse` 3626 object 3627 3628Call [`http2stream.pushStream()`][] with the given headers, and wrap the 3629given [`Http2Stream`][] on a newly created `Http2ServerResponse` as the callback 3630parameter if successful. When `Http2ServerRequest` is closed, the callback is 3631called with an error `ERR_HTTP2_INVALID_STREAM`. 3632 3633#### `response.end([data[, encoding]][, callback])` 3634 3635<!-- YAML 3636added: v8.4.0 3637changes: 3638 - version: v10.0.0 3639 pr-url: https://github.com/nodejs/node/pull/18780 3640 description: This method now returns a reference to `ServerResponse`. 3641--> 3642 3643* `data` {string|Buffer|Uint8Array} 3644* `encoding` {string} 3645* `callback` {Function} 3646* Returns: {this} 3647 3648This method signals to the server that all of the response headers and body 3649have been sent; that server should consider this message complete. 3650The method, `response.end()`, MUST be called on each response. 3651 3652If `data` is specified, it is equivalent to calling 3653[`response.write(data, encoding)`][] followed by `response.end(callback)`. 3654 3655If `callback` is specified, it will be called when the response stream 3656is finished. 3657 3658#### `response.finished` 3659 3660<!-- YAML 3661added: v8.4.0 3662deprecated: 3663 - v13.4.0 3664 - v12.16.0 3665--> 3666 3667> Stability: 0 - Deprecated. Use [`response.writableEnded`][]. 3668 3669* {boolean} 3670 3671Boolean value that indicates whether the response has completed. Starts 3672as `false`. After [`response.end()`][] executes, the value will be `true`. 3673 3674#### `response.getHeader(name)` 3675 3676<!-- YAML 3677added: v8.4.0 3678--> 3679 3680* `name` {string} 3681* Returns: {string} 3682 3683Reads out a header that has already been queued but not sent to the client. 3684The name is case-insensitive. 3685 3686```js 3687const contentType = response.getHeader('content-type'); 3688``` 3689 3690#### `response.getHeaderNames()` 3691 3692<!-- YAML 3693added: v8.4.0 3694--> 3695 3696* Returns: {string\[]} 3697 3698Returns an array containing the unique names of the current outgoing headers. 3699All header names are lowercase. 3700 3701```js 3702response.setHeader('Foo', 'bar'); 3703response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 3704 3705const headerNames = response.getHeaderNames(); 3706// headerNames === ['foo', 'set-cookie'] 3707``` 3708 3709#### `response.getHeaders()` 3710 3711<!-- YAML 3712added: v8.4.0 3713--> 3714 3715* Returns: {Object} 3716 3717Returns a shallow copy of the current outgoing headers. Since a shallow copy 3718is used, array values may be mutated without additional calls to various 3719header-related http module methods. The keys of the returned object are the 3720header names and the values are the respective header values. All header names 3721are lowercase. 3722 3723The object returned by the `response.getHeaders()` method _does not_ 3724prototypically inherit from the JavaScript `Object`. This means that typical 3725`Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others 3726are not defined and _will not work_. 3727 3728```js 3729response.setHeader('Foo', 'bar'); 3730response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); 3731 3732const headers = response.getHeaders(); 3733// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } 3734``` 3735 3736#### `response.hasHeader(name)` 3737 3738<!-- YAML 3739added: v8.4.0 3740--> 3741 3742* `name` {string} 3743* Returns: {boolean} 3744 3745Returns `true` if the header identified by `name` is currently set in the 3746outgoing headers. The header name matching is case-insensitive. 3747 3748```js 3749const hasContentType = response.hasHeader('content-type'); 3750``` 3751 3752#### `response.headersSent` 3753 3754<!-- YAML 3755added: v8.4.0 3756--> 3757 3758* {boolean} 3759 3760True if headers were sent, false otherwise (read-only). 3761 3762#### `response.removeHeader(name)` 3763 3764<!-- YAML 3765added: v8.4.0 3766--> 3767 3768* `name` {string} 3769 3770Removes a header that has been queued for implicit sending. 3771 3772```js 3773response.removeHeader('Content-Encoding'); 3774``` 3775 3776#### `response.req` 3777 3778<!-- YAML 3779added: v15.7.0 3780--> 3781 3782* {http2.Http2ServerRequest} 3783 3784A reference to the original HTTP2 `request` object. 3785 3786#### `response.sendDate` 3787 3788<!-- YAML 3789added: v8.4.0 3790--> 3791 3792* {boolean} 3793 3794When true, the Date header will be automatically generated and sent in 3795the response if it is not already present in the headers. Defaults to true. 3796 3797This should only be disabled for testing; HTTP requires the Date header 3798in responses. 3799 3800#### `response.setHeader(name, value)` 3801 3802<!-- YAML 3803added: v8.4.0 3804--> 3805 3806* `name` {string} 3807* `value` {string|string\[]} 3808 3809Sets a single header value for implicit headers. If this header already exists 3810in the to-be-sent headers, its value will be replaced. Use an array of strings 3811here to send multiple headers with the same name. 3812 3813```js 3814response.setHeader('Content-Type', 'text/html; charset=utf-8'); 3815``` 3816 3817or 3818 3819```js 3820response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 3821``` 3822 3823Attempting to set a header field name or value that contains invalid characters 3824will result in a [`TypeError`][] being thrown. 3825 3826When headers have been set with [`response.setHeader()`][], they will be merged 3827with any headers passed to [`response.writeHead()`][], with the headers passed 3828to [`response.writeHead()`][] given precedence. 3829 3830```js 3831// Returns content-type = text/plain 3832const server = http2.createServer((req, res) => { 3833 res.setHeader('Content-Type', 'text/html; charset=utf-8'); 3834 res.setHeader('X-Foo', 'bar'); 3835 res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); 3836 res.end('ok'); 3837}); 3838``` 3839 3840#### `response.setTimeout(msecs[, callback])` 3841 3842<!-- YAML 3843added: v8.4.0 3844--> 3845 3846* `msecs` {number} 3847* `callback` {Function} 3848* Returns: {http2.Http2ServerResponse} 3849 3850Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is 3851provided, then it is added as a listener on the `'timeout'` event on 3852the response object. 3853 3854If no `'timeout'` listener is added to the request, the response, or 3855the server, then [`Http2Stream`][]s are destroyed when they time out. If a 3856handler is assigned to the request, the response, or the server's `'timeout'` 3857events, timed out sockets must be handled explicitly. 3858 3859#### `response.socket` 3860 3861<!-- YAML 3862added: v8.4.0 3863--> 3864 3865* {net.Socket|tls.TLSSocket} 3866 3867Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but 3868applies getters, setters, and methods based on HTTP/2 logic. 3869 3870`destroyed`, `readable`, and `writable` properties will be retrieved from and 3871set on `response.stream`. 3872 3873`destroy`, `emit`, `end`, `on` and `once` methods will be called on 3874`response.stream`. 3875 3876`setTimeout` method will be called on `response.stream.session`. 3877 3878`pause`, `read`, `resume`, and `write` will throw an error with code 3879`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See [`Http2Session` and Sockets][] for 3880more information. 3881 3882All other interactions will be routed directly to the socket. 3883 3884```js 3885const http2 = require('node:http2'); 3886const server = http2.createServer((req, res) => { 3887 const ip = req.socket.remoteAddress; 3888 const port = req.socket.remotePort; 3889 res.end(`Your IP address is ${ip} and your source port is ${port}.`); 3890}).listen(3000); 3891``` 3892 3893#### `response.statusCode` 3894 3895<!-- YAML 3896added: v8.4.0 3897--> 3898 3899* {number} 3900 3901When using implicit headers (not calling [`response.writeHead()`][] explicitly), 3902this property controls the status code that will be sent to the client when 3903the headers get flushed. 3904 3905```js 3906response.statusCode = 404; 3907``` 3908 3909After response header was sent to the client, this property indicates the 3910status code which was sent out. 3911 3912#### `response.statusMessage` 3913 3914<!-- YAML 3915added: v8.4.0 3916--> 3917 3918* {string} 3919 3920Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns 3921an empty string. 3922 3923#### `response.stream` 3924 3925<!-- YAML 3926added: v8.4.0 3927--> 3928 3929* {Http2Stream} 3930 3931The [`Http2Stream`][] object backing the response. 3932 3933#### `response.writableEnded` 3934 3935<!-- YAML 3936added: v12.9.0 3937--> 3938 3939* {boolean} 3940 3941Is `true` after [`response.end()`][] has been called. This property 3942does not indicate whether the data has been flushed, for this use 3943[`writable.writableFinished`][] instead. 3944 3945#### `response.write(chunk[, encoding][, callback])` 3946 3947<!-- YAML 3948added: v8.4.0 3949--> 3950 3951* `chunk` {string|Buffer|Uint8Array} 3952* `encoding` {string} 3953* `callback` {Function} 3954* Returns: {boolean} 3955 3956If this method is called and [`response.writeHead()`][] has not been called, 3957it will switch to implicit header mode and flush the implicit headers. 3958 3959This sends a chunk of the response body. This method may 3960be called multiple times to provide successive parts of the body. 3961 3962In the `node:http` module, the response body is omitted when the 3963request is a HEAD request. Similarly, the `204` and `304` responses 3964_must not_ include a message body. 3965 3966`chunk` can be a string or a buffer. If `chunk` is a string, 3967the second parameter specifies how to encode it into a byte stream. 3968By default the `encoding` is `'utf8'`. `callback` will be called when this chunk 3969of data is flushed. 3970 3971This is the raw HTTP body and has nothing to do with higher-level multi-part 3972body encodings that may be used. 3973 3974The first time [`response.write()`][] is called, it will send the buffered 3975header information and the first chunk of the body to the client. The second 3976time [`response.write()`][] is called, Node.js assumes data will be streamed, 3977and sends the new data separately. That is, the response is buffered up to the 3978first chunk of the body. 3979 3980Returns `true` if the entire data was flushed successfully to the kernel 3981buffer. Returns `false` if all or part of the data was queued in user memory. 3982`'drain'` will be emitted when the buffer is free again. 3983 3984#### `response.writeContinue()` 3985 3986<!-- YAML 3987added: v8.4.0 3988--> 3989 3990Sends a status `100 Continue` to the client, indicating that the request body 3991should be sent. See the [`'checkContinue'`][] event on `Http2Server` and 3992`Http2SecureServer`. 3993 3994#### `response.writeEarlyHints(hints)` 3995 3996<!-- YAML 3997added: v18.11.0 3998--> 3999 4000* `hints` {Object} 4001 4002Sends a status `103 Early Hints` to the client with a Link header, 4003indicating that the user agent can preload/preconnect the linked resources. 4004The `hints` is an object containing the values of headers to be sent with 4005early hints message. 4006 4007**Example** 4008 4009```js 4010const earlyHintsLink = '</styles.css>; rel=preload; as=style'; 4011response.writeEarlyHints({ 4012 'link': earlyHintsLink, 4013}); 4014 4015const earlyHintsLinks = [ 4016 '</styles.css>; rel=preload; as=style', 4017 '</scripts.js>; rel=preload; as=script', 4018]; 4019response.writeEarlyHints({ 4020 'link': earlyHintsLinks, 4021}); 4022``` 4023 4024#### `response.writeHead(statusCode[, statusMessage][, headers])` 4025 4026<!-- YAML 4027added: v8.4.0 4028changes: 4029 - version: 4030 - v11.10.0 4031 - v10.17.0 4032 pr-url: https://github.com/nodejs/node/pull/25974 4033 description: Return `this` from `writeHead()` to allow chaining with 4034 `end()`. 4035--> 4036 4037* `statusCode` {number} 4038* `statusMessage` {string} 4039* `headers` {Object|Array} 4040* Returns: {http2.Http2ServerResponse} 4041 4042Sends a response header to the request. The status code is a 3-digit HTTP 4043status code, like `404`. The last argument, `headers`, are the response headers. 4044 4045Returns a reference to the `Http2ServerResponse`, so that calls can be chained. 4046 4047For compatibility with [HTTP/1][], a human-readable `statusMessage` may be 4048passed as the second argument. However, because the `statusMessage` has no 4049meaning within HTTP/2, the argument will have no effect and a process warning 4050will be emitted. 4051 4052```js 4053const body = 'hello world'; 4054response.writeHead(200, { 4055 'Content-Length': Buffer.byteLength(body), 4056 'Content-Type': 'text/plain; charset=utf-8', 4057}); 4058``` 4059 4060`Content-Length` is given in bytes not characters. The 4061`Buffer.byteLength()` API may be used to determine the number of bytes in a 4062given encoding. On outbound messages, Node.js does not check if Content-Length 4063and the length of the body being transmitted are equal or not. However, when 4064receiving messages, Node.js will automatically reject messages when the 4065`Content-Length` does not match the actual payload size. 4066 4067This method may be called at most one time on a message before 4068[`response.end()`][] is called. 4069 4070If [`response.write()`][] or [`response.end()`][] are called before calling 4071this, the implicit/mutable headers will be calculated and call this function. 4072 4073When headers have been set with [`response.setHeader()`][], they will be merged 4074with any headers passed to [`response.writeHead()`][], with the headers passed 4075to [`response.writeHead()`][] given precedence. 4076 4077```js 4078// Returns content-type = text/plain 4079const server = http2.createServer((req, res) => { 4080 res.setHeader('Content-Type', 'text/html; charset=utf-8'); 4081 res.setHeader('X-Foo', 'bar'); 4082 res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); 4083 res.end('ok'); 4084}); 4085``` 4086 4087Attempting to set a header field name or value that contains invalid characters 4088will result in a [`TypeError`][] being thrown. 4089 4090## Collecting HTTP/2 performance metrics 4091 4092The [Performance Observer][] API can be used to collect basic performance 4093metrics for each `Http2Session` and `Http2Stream` instance. 4094 4095```js 4096const { PerformanceObserver } = require('node:perf_hooks'); 4097 4098const obs = new PerformanceObserver((items) => { 4099 const entry = items.getEntries()[0]; 4100 console.log(entry.entryType); // prints 'http2' 4101 if (entry.name === 'Http2Session') { 4102 // Entry contains statistics about the Http2Session 4103 } else if (entry.name === 'Http2Stream') { 4104 // Entry contains statistics about the Http2Stream 4105 } 4106}); 4107obs.observe({ entryTypes: ['http2'] }); 4108``` 4109 4110The `entryType` property of the `PerformanceEntry` will be equal to `'http2'`. 4111 4112The `name` property of the `PerformanceEntry` will be equal to either 4113`'Http2Stream'` or `'Http2Session'`. 4114 4115If `name` is equal to `Http2Stream`, the `PerformanceEntry` will contain the 4116following additional properties: 4117 4118* `bytesRead` {number} The number of `DATA` frame bytes received for this 4119 `Http2Stream`. 4120* `bytesWritten` {number} The number of `DATA` frame bytes sent for this 4121 `Http2Stream`. 4122* `id` {number} The identifier of the associated `Http2Stream` 4123* `timeToFirstByte` {number} The number of milliseconds elapsed between the 4124 `PerformanceEntry` `startTime` and the reception of the first `DATA` frame. 4125* `timeToFirstByteSent` {number} The number of milliseconds elapsed between 4126 the `PerformanceEntry` `startTime` and sending of the first `DATA` frame. 4127* `timeToFirstHeader` {number} The number of milliseconds elapsed between the 4128 `PerformanceEntry` `startTime` and the reception of the first header. 4129 4130If `name` is equal to `Http2Session`, the `PerformanceEntry` will contain the 4131following additional properties: 4132 4133* `bytesRead` {number} The number of bytes received for this `Http2Session`. 4134* `bytesWritten` {number} The number of bytes sent for this `Http2Session`. 4135* `framesReceived` {number} The number of HTTP/2 frames received by the 4136 `Http2Session`. 4137* `framesSent` {number} The number of HTTP/2 frames sent by the `Http2Session`. 4138* `maxConcurrentStreams` {number} The maximum number of streams concurrently 4139 open during the lifetime of the `Http2Session`. 4140* `pingRTT` {number} The number of milliseconds elapsed since the transmission 4141 of a `PING` frame and the reception of its acknowledgment. Only present if 4142 a `PING` frame has been sent on the `Http2Session`. 4143* `streamAverageDuration` {number} The average duration (in milliseconds) for 4144 all `Http2Stream` instances. 4145* `streamCount` {number} The number of `Http2Stream` instances processed by 4146 the `Http2Session`. 4147* `type` {string} Either `'server'` or `'client'` to identify the type of 4148 `Http2Session`. 4149 4150## Note on `:authority` and `host` 4151 4152HTTP/2 requires requests to have either the `:authority` pseudo-header 4153or the `host` header. Prefer `:authority` when constructing an HTTP/2 4154request directly, and `host` when converting from HTTP/1 (in proxies, 4155for instance). 4156 4157The compatibility API falls back to `host` if `:authority` is not 4158present. See [`request.authority`][] for more information. However, 4159if you don't use the compatibility API (or use `req.headers` directly), 4160you need to implement any fall-back behavior yourself. 4161 4162[ALPN Protocol ID]: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids 4163[ALPN negotiation]: #alpn-negotiation 4164[Compatibility API]: #compatibility-api 4165[HTTP/1]: http.md 4166[HTTP/2]: https://tools.ietf.org/html/rfc7540 4167[HTTP/2 Headers Object]: #headers-object 4168[HTTP/2 Settings Object]: #settings-object 4169[HTTP/2 Unencrypted]: https://http2.github.io/faq/#does-http2-require-encryption 4170[HTTPS]: https.md 4171[Performance Observer]: perf_hooks.md 4172[RFC 7838]: https://tools.ietf.org/html/rfc7838 4173[RFC 8336]: https://tools.ietf.org/html/rfc8336 4174[RFC 8441]: https://tools.ietf.org/html/rfc8441 4175[Sensitive headers]: #sensitive-headers 4176[`'checkContinue'`]: #event-checkcontinue 4177[`'connect'`]: #event-connect 4178[`'request'`]: #event-request 4179[`'unknownProtocol'`]: #event-unknownprotocol 4180[`ClientHttp2Stream`]: #class-clienthttp2stream 4181[`Duplex`]: stream.md#class-streamduplex 4182[`Http2ServerRequest`]: #class-http2http2serverrequest 4183[`Http2ServerResponse`]: #class-http2http2serverresponse 4184[`Http2Session` and Sockets]: #http2session-and-sockets 4185[`Http2Session`'s `'stream'` event]: #event-stream 4186[`Http2Stream`]: #class-http2stream 4187[`ServerHttp2Stream`]: #class-serverhttp2stream 4188[`TypeError`]: errors.md#class-typeerror 4189[`http2.SecureServer`]: #class-http2secureserver 4190[`http2.Server`]: #class-http2server 4191[`http2.createSecureServer()`]: #http2createsecureserveroptions-onrequesthandler 4192[`http2.createServer()`]: #http2createserveroptions-onrequesthandler 4193[`http2session.close()`]: #http2sessionclosecallback 4194[`http2stream.pushStream()`]: #http2streampushstreamheaders-options-callback 4195[`import()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import 4196[`net.Server.close()`]: net.md#serverclosecallback 4197[`net.Socket.bufferSize`]: net.md#socketbuffersize 4198[`net.Socket.prototype.ref()`]: net.md#socketref 4199[`net.Socket.prototype.unref()`]: net.md#socketunref 4200[`net.Socket`]: net.md#class-netsocket 4201[`net.connect()`]: net.md#netconnect 4202[`net.createServer()`]: net.md#netcreateserveroptions-connectionlistener 4203[`request.authority`]: #requestauthority 4204[`request.maxHeadersCount`]: http.md#requestmaxheaderscount 4205[`request.socket.getPeerCertificate()`]: tls.md#tlssocketgetpeercertificatedetailed 4206[`request.socket`]: #requestsocket 4207[`response.end()`]: #responseenddata-encoding-callback 4208[`response.setHeader()`]: #responsesetheadername-value 4209[`response.socket`]: #responsesocket 4210[`response.writableEnded`]: #responsewritableended 4211[`response.write()`]: #responsewritechunk-encoding-callback 4212[`response.write(data, encoding)`]: http.md#responsewritechunk-encoding-callback 4213[`response.writeContinue()`]: #responsewritecontinue 4214[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers 4215[`server.maxHeadersCount`]: http.md#servermaxheaderscount 4216[`tls.Server.close()`]: tls.md#serverclosecallback 4217[`tls.TLSSocket`]: tls.md#class-tlstlssocket 4218[`tls.connect()`]: tls.md#tlsconnectoptions-callback 4219[`tls.createServer()`]: tls.md#tlscreateserveroptions-secureconnectionlistener 4220[`writable.writableFinished`]: stream.md#writablewritablefinished 4221[error code]: #error-codes-for-rst_stream-and-goaway 4222