-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
Copy pathhttp2.md
4235 lines (3257 loc) Β· 131 KB
/
http2.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# HTTP/2
<!-- YAML
added: v8.4.0
changes:
- version:
- v15.3.0
- v14.17.0
pr-url: https://github.com/nodejs/node/pull/36070
description: It is possible to abort a request with an AbortSignal.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/34664
description: Requests with the `host` header (with or without
`:authority`) can now be sent/received.
- version: v10.10.0
pr-url: https://github.com/nodejs/node/pull/22466
description: HTTP/2 is now Stable. Previously, it had been Experimental.
-->
<!--introduced_in=v8.4.0-->
> Stability: 2 - Stable
<!-- source_link=lib/http2.js -->
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
```js
const http2 = require('node:http2');
```
## Determining if crypto support is unavailable
It is possible for Node.js to be built without including support for the
`node:crypto` module. In such cases, attempting to `import` from `node:http2` or
calling `require('node:http2')` will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
```cjs
let http2;
try {
http2 = require('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}
```
When using the lexical ESM `import` keyword, the error can only be
caught if a handler for `process.on('uncaughtException')` is registered
_before_ any attempt to load the module is made (using, for instance,
a preload module).
When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
[`import()`][] function instead of the lexical `import` keyword:
```mjs
let http2;
try {
http2 = await import('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}
```
## Core API
The Core API provides a low-level interface designed specifically around
support for HTTP/2 protocol features. It is specifically _not_ designed for
compatibility with the existing [HTTP/1][] module API. However,
the [Compatibility API][] is.
The `http2` Core API is much more symmetric between client and server than the
`http` API. For instance, most events, like `'error'`, `'connect'` and
`'stream'`, can be emitted either by client-side code or server-side code.
### Server-side example
The following illustrates a simple HTTP/2 server using the Core API.
Since there are no browsers known that support
[unencrypted HTTP/2][HTTP/2 Unencrypted], the use of
[`http2.createSecureServer()`][] is necessary when communicating
with browser clients.
```js
const http2 = require('node:http2');
const fs = require('node:fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
cert: fs.readFileSync('localhost-cert.pem')
});
server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
server.listen(8443);
```
To generate the certificate and key for this example, run:
```bash
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
-keyout localhost-privkey.pem -out localhost-cert.pem
```
### Client-side example
The following illustrates an HTTP/2 client:
```js
const http2 = require('node:http2');
const fs = require('node:fs');
const client = http2.connect('https://localhost:8443', {
ca: fs.readFileSync('localhost-cert.pem')
});
client.on('error', (err) => console.error(err));
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
for (const name in headers) {
console.log(`${name}: ${headers[name]}`);
}
});
req.setEncoding('utf8');
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
console.log(`\n${data}`);
client.close();
});
req.end();
```
### Class: `Http2Session`
<!-- YAML
added: v8.4.0
-->
* Extends: {EventEmitter}
Instances of the `http2.Http2Session` class represent an active communications
session between an HTTP/2 client and server. Instances of this class are _not_
intended to be constructed directly by user code.
Each `Http2Session` instance will exhibit slightly different behaviors
depending on whether it is operating as a server or a client. The
`http2session.type` property can be used to determine the mode in which an
`Http2Session` is operating. On the server side, user code should rarely
have occasion to work with the `Http2Session` object directly, with most
actions typically taken through interactions with either the `Http2Server` or
`Http2Stream` objects.
User code will not create `Http2Session` instances directly. Server-side
`Http2Session` instances are created by the `Http2Server` instance when a
new HTTP/2 connection is received. Client-side `Http2Session` instances are
created using the `http2.connect()` method.
#### `Http2Session` and sockets
Every `Http2Session` instance is associated with exactly one [`net.Socket`][] or
[`tls.TLSSocket`][] when it is created. When either the `Socket` or the
`Http2Session` are destroyed, both will be destroyed.
Because of the specific serialization and processing requirements imposed
by the HTTP/2 protocol, it is not recommended for user code to read data from
or write data to a `Socket` instance bound to a `Http2Session`. Doing so can
put the HTTP/2 session into an indeterminate state causing the session and
the socket to become unusable.
Once a `Socket` has been bound to an `Http2Session`, user code should rely
solely on the API of the `Http2Session`.
#### Event: `'close'`
<!-- YAML
added: v8.4.0
-->
The `'close'` event is emitted once the `Http2Session` has been destroyed. Its
listener does not expect any arguments.
#### Event: `'connect'`
<!-- YAML
added: v8.4.0
-->
* `session` {Http2Session}
* `socket` {net.Socket}
The `'connect'` event is emitted once the `Http2Session` has been successfully
connected to the remote peer and communication may begin.
User code will typically not listen for this event directly.
#### Event: `'error'`
<!-- YAML
added: v8.4.0
-->
* `error` {Error}
The `'error'` event is emitted when an error occurs during the processing of
an `Http2Session`.
#### Event: `'frameError'`
<!-- YAML
added: v8.4.0
-->
* `type` {integer} The frame type.
* `code` {integer} The error code.
* `id` {integer} The stream id (or `0` if the frame isn't associated with a
stream).
The `'frameError'` event is emitted when an error occurs while attempting to
send a frame on the session. If the frame that could not be sent is associated
with a specific `Http2Stream`, an attempt to emit a `'frameError'` event on the
`Http2Stream` is made.
If the `'frameError'` event is associated with a stream, the stream will be
closed and destroyed immediately following the `'frameError'` event. If the
event is not associated with a stream, the `Http2Session` will be shut down
immediately following the `'frameError'` event.
#### Event: `'goaway'`
<!-- YAML
added: v8.4.0
-->
* `errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.
* `lastStreamID` {number} The ID of the last stream the remote peer successfully
processed (or `0` if no ID is specified).
* `opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY`
frame, a `Buffer` instance will be passed containing that data.
The `'goaway'` event is emitted when a `GOAWAY` frame is received.
The `Http2Session` instance will be shut down automatically when the `'goaway'`
event is emitted.
#### Event: `'localSettings'`
<!-- YAML
added: v8.4.0
-->
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame
has been received.
When using `http2session.settings()` to submit new settings, the modified
settings do not take effect until the `'localSettings'` event is emitted.
```js
session.settings({ enablePush: false });
session.on('localSettings', (settings) => {
/* Use the new settings */
});
```
#### Event: `'ping'`
<!-- YAML
added: v10.12.0
-->
* `payload` {Buffer} The `PING` frame 8-byte payload
The `'ping'` event is emitted whenever a `PING` frame is received from the
connected peer.
#### Event: `'remoteSettings'`
<!-- YAML
added: v8.4.0
-->
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received
from the connected peer.
```js
session.on('remoteSettings', (settings) => {
/* Use the new settings */
});
```
#### Event: `'stream'`
<!-- YAML
added: v8.4.0
-->
* `stream` {Http2Stream} A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` {number} The associated numeric flags
* `rawHeaders` {Array} An array containing the raw header names followed by
their respective values.
The `'stream'` event is emitted when a new `Http2Stream` is created.
```js
const http2 = require('node:http2');
session.on('stream', (stream, headers, flags) => {
const method = headers[':method'];
const path = headers[':path'];
// ...
stream.respond({
':status': 200,
'content-type': 'text/plain; charset=utf-8'
});
stream.write('hello ');
stream.end('world');
});
```
On the server side, user code will typically not listen for this event directly,
and would instead register a handler for the `'stream'` event emitted by the
`net.Server` or `tls.Server` instances returned by `http2.createServer()` and
`http2.createSecureServer()`, respectively, as in the example below:
```js
const http2 = require('node:http2');
// Create an unencrypted HTTP/2 server
const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.on('error', (error) => console.error(error));
stream.end('<h1>Hello World</h1>');
});
server.listen(80);
```
Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
a network error will destroy each individual stream and must be handled on the
stream level, as shown above.
#### Event: `'timeout'`
<!-- YAML
added: v8.4.0
-->
After the `http2session.setTimeout()` method is used to set the timeout period
for this `Http2Session`, the `'timeout'` event is emitted if there is no
activity on the `Http2Session` after the configured number of milliseconds.
Its listener does not expect any arguments.
```js
session.setTimeout(2000);
session.on('timeout', () => { /* .. */ });
```
#### `http2session.alpnProtocol`
<!-- YAML
added: v9.4.0
-->
* {string|undefined}
Value will be `undefined` if the `Http2Session` is not yet connected to a
socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or
will return the value of the connected `TLSSocket`'s own `alpnProtocol`
property.
#### `http2session.close([callback])`
<!-- YAML
added: v9.4.0
-->
* `callback` {Function}
Gracefully closes the `Http2Session`, allowing any existing streams to
complete on their own and preventing new `Http2Stream` instances from being
created. Once closed, `http2session.destroy()` _might_ be called if there
are no open `Http2Stream` instances.
If specified, the `callback` function is registered as a handler for the
`'close'` event.
#### `http2session.closed`
<!-- YAML
added: v9.4.0
-->
* {boolean}
Will be `true` if this `Http2Session` instance has been closed, otherwise
`false`.
#### `http2session.connecting`
<!-- YAML
added: v10.0.0
-->
* {boolean}
Will be `true` if this `Http2Session` instance is still connecting, will be set
to `false` before emitting `connect` event and/or calling the `http2.connect`
callback.
#### `http2session.destroy([error][, code])`
<!-- YAML
added: v8.4.0
-->
* `error` {Error} An `Error` object if the `Http2Session` is being destroyed
due to an error.
* `code` {number} The HTTP/2 error code to send in the final `GOAWAY` frame.
If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`,
otherwise defaults to `NO_ERROR`.
Immediately terminates the `Http2Session` and the associated `net.Socket` or
`tls.TLSSocket`.
Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`
is not undefined, an `'error'` event will be emitted immediately before the
`'close'` event.
If there are any remaining open `Http2Streams` associated with the
`Http2Session`, those will also be destroyed.
#### `http2session.destroyed`
<!-- YAML
added: v8.4.0
-->
* {boolean}
Will be `true` if this `Http2Session` instance has been destroyed and must no
longer be used, otherwise `false`.
#### `http2session.encrypted`
<!-- YAML
added: v9.4.0
-->
* {boolean|undefined}
Value is `undefined` if the `Http2Session` session socket has not yet been
connected, `true` if the `Http2Session` is connected with a `TLSSocket`,
and `false` if the `Http2Session` is connected to any other kind of socket
or stream.
#### `http2session.goaway([code[, lastStreamID[, opaqueData]]])`
<!-- YAML
added: v9.4.0
-->
* `code` {number} An HTTP/2 error code
* `lastStreamID` {number} The numeric ID of the last processed `Http2Stream`
* `opaqueData` {Buffer|TypedArray|DataView} A `TypedArray` or `DataView`
instance containing additional data to be carried within the `GOAWAY` frame.
Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the
`Http2Session`.
#### `http2session.localSettings`
<!-- YAML
added: v8.4.0
-->
* {HTTP/2 Settings Object}
A prototype-less object describing the current local settings of this
`Http2Session`. The local settings are local to _this_ `Http2Session` instance.
#### `http2session.originSet`
<!-- YAML
added: v9.4.0
-->
* {string\[]|undefined}
If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property
will return an `Array` of origins for which the `Http2Session` may be
considered authoritative.
The `originSet` property is only available when using a secure TLS connection.
#### `http2session.pendingSettingsAck`
<!-- YAML
added: v8.4.0
-->
* {boolean}
Indicates whether the `Http2Session` is currently waiting for acknowledgment of
a sent `SETTINGS` frame. Will be `true` after calling the
`http2session.settings()` method. Will be `false` once all sent `SETTINGS`
frames have been acknowledged.
#### `http2session.ping([payload, ]callback)`
<!-- YAML
added: v8.9.3
changes:
- version: v18.0.0
pr-url: https://github.com/nodejs/node/pull/41678
description: Passing an invalid callback to the `callback` argument
now throws `ERR_INVALID_ARG_TYPE` instead of
`ERR_INVALID_CALLBACK`.
-->
* `payload` {Buffer|TypedArray|DataView} Optional ping payload.
* `callback` {Function}
* Returns: {boolean}
Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must
be provided. The method will return `true` if the `PING` was sent, `false`
otherwise.
The maximum number of outstanding (unacknowledged) pings is determined by the
`maxOutstandingPings` configuration option. The default maximum is 10.
If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`
containing 8 bytes of data that will be transmitted with the `PING` and
returned with the ping acknowledgment.
The callback will be invoked with three arguments: an error argument that will
be `null` if the `PING` was successfully acknowledged, a `duration` argument
that reports the number of milliseconds elapsed since the ping was sent and the
acknowledgment was received, and a `Buffer` containing the 8-byte `PING`
payload.
```js
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
if (!err) {
console.log(`Ping acknowledged in ${duration} milliseconds`);
console.log(`With payload '${payload.toString()}'`);
}
});
```
If the `payload` argument is not specified, the default payload will be the
64-bit timestamp (little endian) marking the start of the `PING` duration.
#### `http2session.ref()`
<!-- YAML
added: v9.4.0
-->
Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
#### `http2session.remoteSettings`
<!-- YAML
added: v8.4.0
-->
* {HTTP/2 Settings Object}
A prototype-less object describing the current remote settings of this
`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer.
#### `http2session.setLocalWindowSize(windowSize)`
<!-- YAML
added:
- v15.3.0
- v14.18.0
-->
* `windowSize` {number}
Sets the local endpoint's window size.
The `windowSize` is the total window size to set, not
the delta.
```js
const http2 = require('node:http2');
const server = http2.createServer();
const expectedWindowSize = 2 ** 20;
server.on('connect', (session) => {
// Set local window size to be 2 ** 20
session.setLocalWindowSize(expectedWindowSize);
});
```
#### `http2session.setTimeout(msecs, callback)`
<!-- YAML
added: v8.4.0
changes:
- version: v18.0.0
pr-url: https://github.com/nodejs/node/pull/41678
description: Passing an invalid callback to the `callback` argument
now throws `ERR_INVALID_ARG_TYPE` instead of
`ERR_INVALID_CALLBACK`.
-->
* `msecs` {number}
* `callback` {Function}
Used to set a callback function that is called when there is no activity on
the `Http2Session` after `msecs` milliseconds. The given `callback` is
registered as a listener on the `'timeout'` event.
#### `http2session.socket`
<!-- YAML
added: v8.4.0
-->
* {net.Socket|tls.TLSSocket}
Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
limits available methods to ones safe to use with HTTP/2.
`destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw
an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See
[`Http2Session` and Sockets][] for more information.
`setTimeout` method will be called on this `Http2Session`.
All other interactions will be routed directly to the socket.
#### `http2session.state`
<!-- YAML
added: v8.4.0
-->
Provides miscellaneous information about the current state of the
`Http2Session`.
* {Object}
* `effectiveLocalWindowSize` {number} The current local (receive)
flow control window size for the `Http2Session`.
* `effectiveRecvDataLength` {number} The current number of bytes
that have been received since the last flow control `WINDOW_UPDATE`.
* `nextStreamID` {number} The numeric identifier to be used the
next time a new `Http2Stream` is created by this `Http2Session`.
* `localWindowSize` {number} The number of bytes that the remote peer can
send without receiving a `WINDOW_UPDATE`.
* `lastProcStreamID` {number} The numeric id of the `Http2Stream`
for which a `HEADERS` or `DATA` frame was most recently received.
* `remoteWindowSize` {number} The number of bytes that this `Http2Session`
may send without receiving a `WINDOW_UPDATE`.
* `outboundQueueSize` {number} The number of frames currently within the
outbound queue for this `Http2Session`.
* `deflateDynamicTableSize` {number} The current size in bytes of the
outbound header compression state table.
* `inflateDynamicTableSize` {number} The current size in bytes of the
inbound header compression state table.
An object describing the current status of this `Http2Session`.
#### `http2session.settings([settings][, callback])`
<!-- YAML
added: v8.4.0
changes:
- version: v18.0.0
pr-url: https://github.com/nodejs/node/pull/41678
description: Passing an invalid callback to the `callback` argument
now throws `ERR_INVALID_ARG_TYPE` instead of
`ERR_INVALID_CALLBACK`.
-->
* `settings` {HTTP/2 Settings Object}
* `callback` {Function} Callback that is called once the session is connected or
right away if the session is already connected.
* `err` {Error|null}
* `settings` {HTTP/2 Settings Object} The updated `settings` object.
* `duration` {integer}
Updates the current local settings for this `Http2Session` and sends a new
`SETTINGS` frame to the connected HTTP/2 peer.
Once called, the `http2session.pendingSettingsAck` property will be `true`
while the session is waiting for the remote peer to acknowledge the new
settings.
The new settings will not become effective until the `SETTINGS` acknowledgment
is received and the `'localSettings'` event is emitted. It is possible to send
multiple `SETTINGS` frames while acknowledgment is still pending.
#### `http2session.type`
<!-- YAML
added: v8.4.0
-->
* {number}
The `http2session.type` will be equal to
`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a
server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a
client.
#### `http2session.unref()`
<!-- YAML
added: v9.4.0
-->
Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
### Class: `ServerHttp2Session`
<!-- YAML
added: v8.4.0
-->
* Extends: {Http2Session}
#### `serverhttp2session.altsvc(alt, originOrStream)`
<!-- YAML
added: v9.4.0
-->
* `alt` {string} A description of the alternative service configuration as
defined by [RFC 7838][].
* `originOrStream` {number|string|URL|Object} Either a URL string specifying
the origin (or an `Object` with an `origin` property) or the numeric
identifier of an active `Http2Stream` as given by the `http2stream.id`
property.
Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client.
```js
const http2 = require('node:http2');
const server = http2.createServer();
server.on('session', (session) => {
// Set altsvc for origin https://example.org:80
session.altsvc('h2=":8000"', 'https://example.org:80');
});
server.on('stream', (stream) => {
// Set altsvc for a specific stream
stream.session.altsvc('h2=":8000"', stream.id);
});
```
Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate
service is associated with the origin of the given `Http2Stream`.
The `alt` and origin string _must_ contain only ASCII bytes and are
strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`
may be passed to clear any previously set alternative service for a given
domain.
When a string is passed for the `originOrStream` argument, it will be parsed as
a URL and the origin will be derived. For instance, the origin for the
HTTP URL `'https://example.org/foo/bar'` is the ASCII string
`'https://example.org'`. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.
A `URL` object, or any object with an `origin` property, may be passed as
`originOrStream`, in which case the value of the `origin` property will be
used. The value of the `origin` property _must_ be a properly serialized
ASCII origin.
#### Specifying alternative services
The format of the `alt` parameter is strictly defined by [RFC 7838][] as an
ASCII string containing a comma-delimited list of "alternative" protocols
associated with a specific host and port.
For example, the value `'h2="example.org:81"'` indicates that the HTTP/2
protocol is available on the host `'example.org'` on TCP/IP port 81. The
host and port _must_ be contained within the quote (`"`) characters.
Multiple alternatives may be specified, for instance: `'h2="example.org:81",
h2=":82"'`.
The protocol identifier (`'h2'` in the examples) may be any valid
[ALPN Protocol ID][].
The syntax of these values is not validated by the Node.js implementation and
are passed through as provided by the user or received from the peer.
#### `serverhttp2session.origin(...origins)`
<!-- YAML
added: v10.12.0
-->
* `origins` { string | URL | Object } One or more URL Strings passed as
separate arguments.
Submits an `ORIGIN` frame (as defined by [RFC 8336][]) to the connected client
to advertise the set of origins for which the server is capable of providing
authoritative responses.
```js
const http2 = require('node:http2');
const options = getSecureOptionsSomehow();
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});
server.on('session', (session) => {
session.origin('https://example.com', 'https://example.org');
});
```
When a string is passed as an `origin`, it will be parsed as a URL and the
origin will be derived. For instance, the origin for the HTTP URL
`'https://example.org/foo/bar'` is the ASCII string
`'https://example.org'`. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.
A `URL` object, or any object with an `origin` property, may be passed as
an `origin`, in which case the value of the `origin` property will be
used. The value of the `origin` property _must_ be a properly serialized
ASCII origin.
Alternatively, the `origins` option may be used when creating a new HTTP/2
server using the `http2.createSecureServer()` method:
```js
const http2 = require('node:http2');
const options = getSecureOptionsSomehow();
options.origins = ['https://example.com', 'https://example.org'];
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
stream.respond();
stream.end('ok');
});
```
### Class: `ClientHttp2Session`
<!-- YAML
added: v8.4.0
-->
* Extends: {Http2Session}
#### Event: `'altsvc'`
<!-- YAML
added: v9.4.0
-->
* `alt` {string}
* `origin` {string}
* `streamId` {number}
The `'altsvc'` event is emitted whenever an `ALTSVC` frame is received by
the client. The event is emitted with the `ALTSVC` value, origin, and stream
ID. If no `origin` is provided in the `ALTSVC` frame, `origin` will
be an empty string.
```js
const http2 = require('node:http2');
const client = http2.connect('https://example.org');
client.on('altsvc', (alt, origin, streamId) => {
console.log(alt);
console.log(origin);
console.log(streamId);
});
```
#### Event: `'origin'`
<!-- YAML
added: v10.12.0
-->
* `origins` {string\[]}
The `'origin'` event is emitted whenever an `ORIGIN` frame is received by
the client. The event is emitted with an array of `origin` strings. The
`http2session.originSet` will be updated to include the received
origins.
```js
const http2 = require('node:http2');
const client = http2.connect('https://example.org');
client.on('origin', (origins) => {
for (let n = 0; n < origins.length; n++)
console.log(origins[n]);
});
```
The `'origin'` event is only emitted when using a secure TLS connection.
#### `clienthttp2session.request(headers[, options])`
<!-- YAML
added: v8.4.0
-->
* `headers` {HTTP/2 Headers Object}
* `options` {Object}
* `endStream` {boolean} `true` if the `Http2Stream` _writable_ side should
be closed initially, such as when sending a `GET` request that should not
expect a payload body.
* `exclusive` {boolean} When `true` and `parent` identifies a parent Stream,
the created stream is made the sole direct dependency of the parent, with
all other existing dependents made a dependent of the newly created stream.
**Default:** `false`.
* `parent` {number} Specifies the numeric identifier of a stream the newly
created stream is dependent on.
* `weight` {number} Specifies the relative dependency of a stream in relation
to other streams with the same `parent`. The value is a number between `1`
and `256` (inclusive).
* `waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the
`'wantTrailers'` event after the final `DATA` frame has been sent.
* `signal` {AbortSignal} An AbortSignal that may be used to abort an ongoing
request.
* Returns: {ClientHttp2Stream}
For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`
creates and returns an `Http2Stream` instance that can be used to send an
HTTP/2 request to the connected server.
When a `ClientHttp2Session` is first created, the socket may not yet be
connected. if `clienthttp2session.request()` is called during this time, the
actual request will be deferred until the socket is ready to go.
If the `session` is closed before the actual request be executed, an
`ERR_HTTP2_GOAWAY_SESSION` is thrown.
This method is only available if `http2session.type` is equal to
`http2.constants.NGHTTP2_SESSION_CLIENT`.
```js
const http2 = require('node:http2');
const clientSession = http2.connect('https://localhost:1234');
const {
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS
} = http2.constants;
const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
req.on('response', (headers) => {
console.log(headers[HTTP2_HEADER_STATUS]);
req.on('data', (chunk) => { /* .. */ });
req.on('end', () => { /* .. */ });
});
```
When the `options.waitForTrailers` option is set, the `'wantTrailers'` event
is emitted immediately after queuing the last chunk of payload data to be sent.
The `http2stream.sendTrailers()` method can then be called to send trailing
headers to the peer.
When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
close when the final `DATA` frame is transmitted. User code must call either
`http2stream.sendTrailers()` or `http2stream.close()` to close the
`Http2Stream`.
When `options.signal` is set with an `AbortSignal` and then `abort` on the
corresponding `AbortController` is called, the request will emit an `'error'`
event with an `AbortError` error.
The `:method` and `:path` pseudo-headers are not specified within `headers`,
they respectively default to: