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