Source Code: lib/http2.js
The node:http2 module provides an implementation of the HTTP/2 protocol.\nIt can be accessed using:
node:http2
const http2 = require('node:http2');\n
It is possible for Node.js to be built without including support for the\nnode:crypto module. In such cases, attempting to import from node:http2 or\ncalling require('node:http2') will result in an error being thrown.
node:crypto
import
require('node:http2')
When using CommonJS, the error thrown can be caught using try/catch:
let http2;\ntry {\n http2 = require('node:http2');\n} catch (err) {\n console.log('http2 support is disabled!');\n}\n
When using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made (using, for instance,\na preload module).
process.on('uncaughtException')
When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:
import()
let http2;\ntry {\n http2 = await import('node:http2');\n} catch (err) {\n console.log('http2 support is disabled!');\n}\n
The Core API provides a low-level interface designed specifically around\nsupport for HTTP/2 protocol features. It is specifically not designed for\ncompatibility with the existing HTTP/1 module API. However,\nthe Compatibility API is.
The http2 Core API is much more symmetric between client and server than the\nhttp API. For instance, most events, like 'error', 'connect' and\n'stream', can be emitted either by client-side code or server-side code.
http2
http
'error'
'connect'
'stream'
The following illustrates a simple HTTP/2 server using the Core API.\nSince there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.
http2.createSecureServer()
const http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createSecureServer({\n key: fs.readFileSync('localhost-privkey.pem'),\n cert: fs.readFileSync('localhost-cert.pem')\n});\nserver.on('error', (err) => console.error(err));\n\nserver.on('stream', (stream, headers) => {\n // stream is a Duplex\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(8443);\n
To generate the certificate and key for this example, run:
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n -keyout localhost-privkey.pem -out localhost-cert.pem\n
The following illustrates an HTTP/2 client:
const http2 = require('node:http2');\nconst fs = require('node:fs');\nconst client = http2.connect('https://localhost:8443', {\n ca: fs.readFileSync('localhost-cert.pem')\n});\nclient.on('error', (err) => console.error(err));\n\nconst req = client.request({ ':path': '/' });\n\nreq.on('response', (headers, flags) => {\n for (const name in headers) {\n console.log(`${name}: ${headers[name]}`);\n }\n});\n\nreq.setEncoding('utf8');\nlet data = '';\nreq.on('data', (chunk) => { data += chunk; });\nreq.on('end', () => {\n console.log(`\\n${data}`);\n client.close();\n});\nreq.end();\n
Headers are represented as own-properties on JavaScript objects. The property\nkeys will be serialized to lower-case. Property values should be strings (if\nthey are not they will be coerced to strings) or an Array of strings (in order\nto send more than one value per header field).
Array
const headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'ABC': ['has', 'more', 'than', 'one', 'value']\n};\n\nstream.respond(headers);\n
Header objects passed to callback functions will have a null prototype. This\nmeans that normal JavaScript object methods such as\nObject.prototype.toString() and Object.prototype.hasOwnProperty() will\nnot work.
null
Object.prototype.toString()
Object.prototype.hasOwnProperty()
For incoming headers:
:status
number
:method
:authority
:scheme
:path
:protocol
age
authorization
access-control-allow-credentials
access-control-max-age
access-control-request-method
content-encoding
content-language
content-length
content-location
content-md5
content-range
content-type
date
dnt
etag
expires
from
host
if-match
if-modified-since
if-none-match
if-range
if-unmodified-since
last-modified
location
max-forwards
proxy-authorization
range
referer
retry-after
tk
upgrade-insecure-requests
user-agent
x-content-type-options
set-cookie
cookie
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream, headers) => {\n console.log(headers[':path']);\n console.log(headers.ABC);\n});\n
HTTP2 headers can be marked as sensitive, which means that the HTTP/2\nheader compression algorithm will never index them. This can make sense for\nheader values with low entropy and that may be considered valuable to an\nattacker, for example Cookie or Authorization. To achieve this, add\nthe header name to the [http2.sensitiveHeaders] property as an array:
Cookie
Authorization
[http2.sensitiveHeaders]
const headers = {\n ':status': '200',\n 'content-type': 'text-plain',\n 'cookie': 'some-cookie',\n 'other-sensitive-header': 'very secret data',\n [http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header']\n};\n\nstream.respond(headers);\n
For some headers, such as Authorization and short Cookie headers,\nthis flag is set automatically.
This property is also set for received headers. It will contain the names of\nall headers marked as sensitive, including ones marked that way automatically.
The http2.getDefaultSettings(), http2.getPackedSettings(),\nhttp2.createServer(), http2.createSecureServer(),\nhttp2session.settings(), http2session.localSettings, and\nhttp2session.remoteSettings APIs either return or receive as input an\nobject that defines configuration settings for an Http2Session object.\nThese objects are ordinary JavaScript objects containing the following\nproperties.
http2.getDefaultSettings()
http2.getPackedSettings()
http2.createServer()
http2session.settings()
http2session.localSettings
http2session.remoteSettings
Http2Session
headerTableSize
4096
enablePush
true
initialWindowSize
65535
maxFrameSize
16384
maxConcurrentStreams
4294967295
maxHeaderListSize
maxHeaderSize
enableConnectProtocol
false
All additional properties on the settings object are ignored.
There are several types of error conditions that may arise when using the\nnode:http2 module:
Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.
throw
State errors occur when an action is attempted at an incorrect time (for\ninstance, attempting to send data on a stream after it has closed). These will\nbe reported using either a synchronous throw or via an 'error' event on\nthe Http2Stream, Http2Session or HTTP/2 Server objects, depending on where\nand when the error occurs.
Http2Stream
Internal errors occur when an HTTP/2 session fails unexpectedly. These will be\nreported via an 'error' event on the Http2Session or HTTP/2 Server objects.
Protocol errors occur when various HTTP/2 protocol constraints are violated.\nThese will be reported using either a synchronous throw or via an 'error'\nevent on the Http2Stream, Http2Session or HTTP/2 Server objects, depending\non where and when the error occurs.
The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.
Header field names are case-insensitive and are transmitted over the wire\nstrictly as lower-case strings. The API provided by Node.js allows header\nnames to be set as mixed-case strings (e.g. Content-Type) but will convert\nthose to lower-case (e.g. content-type) upon transmission.
Content-Type
Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.
a
z
A
Z
0
9
!
#
$
%
&
'
*
+
-
.
^
_
`
|
~
Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.
Header field values are handled with more leniency but should not contain\nnew-line or carriage return characters and should be limited to US-ASCII\ncharacters, per the requirements of the HTTP specification.
To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:
ClientHttp2Session
const http2 = require('node:http2');\n\nconst client = http2.connect('http://localhost');\n\nclient.on('stream', (pushedStream, requestHeaders) => {\n pushedStream.on('push', (responseHeaders) => {\n // Process response headers\n });\n pushedStream.on('data', (chunk) => { /* handle pushed data */ });\n});\n\nconst req = client.request({ ':path': '/' });\n
The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.
CONNECT
A simple TCP Server:
const net = require('node:net');\n\nconst server = net.createServer((socket) => {\n let name = '';\n socket.setEncoding('utf8');\n socket.on('data', (chunk) => name += chunk);\n socket.on('end', () => socket.end(`hello ${name}`));\n});\n\nserver.listen(8000);\n
An HTTP/2 CONNECT proxy:
const http2 = require('node:http2');\nconst { NGHTTP2_REFUSED_STREAM } = http2.constants;\nconst net = require('node:net');\n\nconst proxy = http2.createServer();\nproxy.on('stream', (stream, headers) => {\n if (headers[':method'] !== 'CONNECT') {\n // Only accept CONNECT requests\n stream.close(NGHTTP2_REFUSED_STREAM);\n return;\n }\n const auth = new URL(`tcp://${headers[':authority']}`);\n // It's a very good idea to verify that hostname and port are\n // things this proxy should be connecting to.\n const socket = net.connect(auth.port, auth.hostname, () => {\n stream.respond();\n socket.pipe(stream);\n stream.pipe(socket);\n });\n socket.on('error', (error) => {\n stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);\n });\n});\n\nproxy.listen(8001);\n
An HTTP/2 CONNECT client:
const http2 = require('node:http2');\n\nconst client = http2.connect('http://localhost:8001');\n\n// Must not specify the ':path' and ':scheme' headers\n// for CONNECT requests or an error will be thrown.\nconst req = client.request({\n ':method': 'CONNECT',\n ':authority': `localhost:${port}`\n});\n\nreq.on('response', (headers) => {\n console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);\n});\nlet data = '';\nreq.setEncoding('utf8');\nreq.on('data', (chunk) => data += chunk);\nreq.on('end', () => {\n console.log(`The server says: ${data}`);\n client.close();\n});\nreq.end('Jane');\n
RFC 8441 defines an \"Extended CONNECT Protocol\" extension to HTTP/2 that\nmay be used to bootstrap the use of an Http2Stream using the CONNECT\nmethod as a tunnel for other communication protocols (such as WebSockets).
The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:
const http2 = require('node:http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
Once the client receives the SETTINGS frame from the server indicating that\nthe extended CONNECT may be used, it may send CONNECT requests that use the\n':protocol' HTTP/2 pseudo-header:
SETTINGS
':protocol'
const http2 = require('node:http2');\nconst client = http2.connect('http://localhost:8080');\nclient.on('remoteSettings', (settings) => {\n if (settings.enableConnectProtocol) {\n const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });\n // ...\n }\n});\n
Instances of the http2.Http2Session class represent an active communications\nsession between an HTTP/2 client and server. Instances of this class are not\nintended to be constructed directly by user code.
http2.Http2Session
Each Http2Session instance will exhibit slightly different behaviors\ndepending on whether it is operating as a server or a client. The\nhttp2session.type property can be used to determine the mode in which an\nHttp2Session is operating. On the server side, user code should rarely\nhave occasion to work with the Http2Session object directly, with most\nactions typically taken through interactions with either the Http2Server or\nHttp2Stream objects.
http2session.type
Http2Server
User code will not create Http2Session instances directly. Server-side\nHttp2Session instances are created by the Http2Server instance when a\nnew HTTP/2 connection is received. Client-side Http2Session instances are\ncreated using the http2.connect() method.
http2.connect()
Every Http2Session instance is associated with exactly one net.Socket or\ntls.TLSSocket when it is created. When either the Socket or the\nHttp2Session are destroyed, both will be destroyed.
net.Socket
tls.TLSSocket
Socket
Because of the specific serialization and processing requirements imposed\nby the HTTP/2 protocol, it is not recommended for user code to read data from\nor write data to a Socket instance bound to a Http2Session. Doing so can\nput the HTTP/2 session into an indeterminate state causing the session and\nthe socket to become unusable.
Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.
The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.
'close'
The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.
User code will typically not listen for this event directly.
The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.
The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame on the session. If the frame that could not be sent is associated\nwith a specific Http2Stream, an attempt to emit a 'frameError' event on the\nHttp2Stream is made.
'frameError'
If the 'frameError' event is associated with a stream, the stream will be\nclosed and destroyed immediately following the 'frameError' event. If the\nevent is not associated with a stream, the Http2Session will be shut down\nimmediately following the 'frameError' event.
The 'goaway' event is emitted when a GOAWAY frame is received.
'goaway'
GOAWAY
The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.
The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.
'localSettings'
When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n /* Use the new settings */\n});\n
The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.
'ping'
PING
The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.
'remoteSettings'
session.on('remoteSettings', (settings) => {\n /* Use the new settings */\n});\n
The 'stream' event is emitted when a new Http2Stream is created.
const http2 = require('node:http2');\nsession.on('stream', (stream, headers, flags) => {\n const method = headers[':method'];\n const path = headers[':path'];\n // ...\n stream.respond({\n ':status': 200,\n 'content-type': 'text/plain; charset=utf-8'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
On the server side, user code will typically not listen for this event directly,\nand would instead register a handler for the 'stream' event emitted by the\nnet.Server or tls.Server instances returned by http2.createServer() and\nhttp2.createSecureServer(), respectively, as in the example below:
net.Server
tls.Server
const http2 = require('node:http2');\n\n// Create an unencrypted HTTP/2 server\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200\n });\n stream.on('error', (error) => console.error(error));\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,\na network error will destroy each individual stream and must be handled on the\nstream level, as shown above.
After the http2session.setTimeout() method is used to set the timeout period\nfor this Http2Session, the 'timeout' event is emitted if there is no\nactivity on the Http2Session after the configured number of milliseconds.\nIts listener does not expect any arguments.
http2session.setTimeout()
'timeout'
session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
Value will be undefined if the Http2Session is not yet connected to a\nsocket, h2c if the Http2Session is not connected to a TLSSocket, or\nwill return the value of the connected TLSSocket's own alpnProtocol\nproperty.
undefined
h2c
TLSSocket
alpnProtocol
Will be true if this Http2Session instance has been closed, otherwise\nfalse.
Will be true if this Http2Session instance is still connecting, will be set\nto false before emitting connect event and/or calling the http2.connect\ncallback.
connect
http2.connect
Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.
Value is undefined if the Http2Session session socket has not yet been\nconnected, true if the Http2Session is connected with a TLSSocket,\nand false if the Http2Session is connected to any other kind of socket\nor stream.
A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.
If the Http2Session is connected to a TLSSocket, the originSet property\nwill return an Array of origins for which the Http2Session may be\nconsidered authoritative.
originSet
The originSet property is only available when using a secure TLS connection.
Indicates whether the Http2Session is currently waiting for acknowledgment of\na sent SETTINGS frame. Will be true after calling the\nhttp2session.settings() method. Will be false once all sent SETTINGS\nframes have been acknowledged.
A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.
Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\nlimits available methods to ones safe to use with HTTP/2.
Proxy
destroy, emit, end, pause, read, resume, and write will throw\nan error with code ERR_HTTP2_NO_SOCKET_MANIPULATION. See\nHttp2Session and Sockets for more information.
destroy
emit
end
pause
read
resume
write
ERR_HTTP2_NO_SOCKET_MANIPULATION
setTimeout method will be called on this Http2Session.
setTimeout
All other interactions will be routed directly to the socket.
Provides miscellaneous information about the current state of the\nHttp2Session.
effectiveLocalWindowSize
effectiveRecvDataLength
WINDOW_UPDATE
nextStreamID
localWindowSize
lastProcStreamID
HEADERS
DATA
remoteWindowSize
outboundQueueSize
deflateDynamicTableSize
inflateDynamicTableSize
An object describing the current status of this Http2Session.
The http2session.type will be equal to\nhttp2.constants.NGHTTP2_SESSION_SERVER if this Http2Session instance is a\nserver, and http2.constants.NGHTTP2_SESSION_CLIENT if the instance is a\nclient.
http2.constants.NGHTTP2_SESSION_SERVER
http2.constants.NGHTTP2_SESSION_CLIENT
Gracefully closes the Http2Session, allowing any existing streams to\ncomplete on their own and preventing new Http2Stream instances from being\ncreated. Once closed, http2session.destroy() might be called if there\nare no open Http2Stream instances.
http2session.destroy()
If specified, the callback function is registered as a handler for the\n'close' event.
callback
Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.
Once destroyed, the Http2Session will emit the 'close' event. If error\nis not undefined, an 'error' event will be emitted immediately before the\n'close' event.
error
If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.
Http2Streams
Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.
Sends a PING frame to the connected HTTP/2 peer. A callback function must\nbe provided. The method will return true if the PING was sent, false\notherwise.
The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.
maxOutstandingPings
If provided, the payload must be a Buffer, TypedArray, or DataView\ncontaining 8 bytes of data that will be transmitted with the PING and\nreturned with the ping acknowledgment.
payload
Buffer
TypedArray
DataView
The callback will be invoked with three arguments: an error argument that will\nbe null if the PING was successfully acknowledged, a duration argument\nthat reports the number of milliseconds elapsed since the ping was sent and the\nacknowledgment was received, and a Buffer containing the 8-byte PING\npayload.
duration
session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {\n if (!err) {\n console.log(`Ping acknowledged in ${duration} milliseconds`);\n console.log(`With payload '${payload.toString()}'`);\n }\n});\n
If the payload argument is not specified, the default payload will be the\n64-bit timestamp (little endian) marking the start of the PING duration.
Calls ref() on this Http2Session\ninstance's underlying net.Socket.
ref()
Sets the local endpoint's window size.\nThe windowSize is the total window size to set, not\nthe delta.
windowSize
const http2 = require('node:http2');\n\nconst server = http2.createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('connect', (session) => {\n\n // Set local window size to be 2 ** 20\n session.setLocalWindowSize(expectedWindowSize);\n});\n
Used to set a callback function that is called when there is no activity on\nthe Http2Session after msecs milliseconds. The given callback is\nregistered as a listener on the 'timeout' event.
msecs
Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.
Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.
http2session.pendingSettingsAck
The new settings will not become effective until the SETTINGS acknowledgment\nis received and the 'localSettings' event is emitted. It is possible to send\nmultiple SETTINGS frames while acknowledgment is still pending.
Calls unref() on this Http2Session\ninstance's underlying net.Socket.
unref()
Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.
ALTSVC
const http2 = require('node:http2');\n\nconst server = http2.createServer();\nserver.on('session', (session) => {\n // Set altsvc for origin https://example.org:80\n session.altsvc('h2=\":8000\"', 'https://example.org:80');\n});\n\nserver.on('stream', (stream) => {\n // Set altsvc for a specific stream\n stream.session.altsvc('h2=\":8000\"', stream.id);\n});\n
Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.
The alt and origin string must contain only ASCII bytes and are\nstrictly interpreted as a sequence of ASCII bytes. The special value 'clear'\nmay be passed to clear any previously set alternative service for a given\ndomain.
alt
'clear'
When a string is passed for the originOrStream argument, it will be parsed as\na URL and the origin will be derived. For instance, the origin for the\nHTTP URL 'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot be parsed as a URL or if a valid origin cannot be derived.
originOrStream
'https://example.org/foo/bar'
'https://example.org'
A URL object, or any object with an origin property, may be passed as\noriginOrStream, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.
URL
origin
Submits an ORIGIN frame (as defined by RFC 8336) to the connected client\nto advertise the set of origins for which the server is capable of providing\nauthoritative responses.
ORIGIN
const http2 = require('node:http2');\nconst options = getSecureOptionsSomehow();\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\nserver.on('session', (session) => {\n session.origin('https://example.com', 'https://example.org');\n});\n
When a string is passed as an origin, it will be parsed as a URL and the\norigin will be derived. For instance, the origin for the HTTP URL\n'https://example.org/foo/bar' is the ASCII string\n'https://example.org'. An error will be thrown if either the given string\ncannot 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\nan origin, in which case the value of the origin property will be\nused. The value of the origin property must be a properly serialized\nASCII origin.
Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:
origins
const http2 = require('node:http2');\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream) => {\n stream.respond();\n stream.end('ok');\n});\n
The format of the alt parameter is strictly defined by RFC 7838 as an\nASCII string containing a comma-delimited list of \"alternative\" protocols\nassociated with a specific host and port.
For example, the value 'h2=\"example.org:81\"' indicates that the HTTP/2\nprotocol is available on the host 'example.org' on TCP/IP port 81. The\nhost and port must be contained within the quote (\") characters.
'h2=\"example.org:81\"'
'example.org'
\"
Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.
'h2=\"example.org:81\", h2=\":82\"'
The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.
'h2'
The syntax of these values is not validated by the Node.js implementation and\nare passed through as provided by the user or received from the peer.
The 'altsvc' event is emitted whenever an ALTSVC frame is received by\nthe client. The event is emitted with the ALTSVC value, origin, and stream\nID. If no origin is provided in the ALTSVC frame, origin will\nbe an empty string.
'altsvc'
const http2 = require('node:http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('altsvc', (alt, origin, streamId) => {\n console.log(alt);\n console.log(origin);\n console.log(streamId);\n});\n
The 'origin' event is emitted whenever an ORIGIN frame is received by\nthe client. The event is emitted with an array of origin strings. The\nhttp2session.originSet will be updated to include the received\norigins.
'origin'
http2session.originSet
const http2 = require('node:http2');\nconst client = http2.connect('https://example.org');\n\nclient.on('origin', (origins) => {\n for (let n = 0; n < origins.length; n++)\n console.log(origins[n]);\n});\n
The 'origin' event is only emitted when using a secure TLS connection.
For HTTP/2 Client Http2Session instances only, the http2session.request()\ncreates and returns an Http2Stream instance that can be used to send an\nHTTP/2 request to the connected server.
http2session.request()
When a ClientHttp2Session is first created, the socket may not yet be\nconnected. if clienthttp2session.request() is called during this time, the\nactual request will be deferred until the socket is ready to go.\nIf the session is closed before the actual request be executed, an\nERR_HTTP2_GOAWAY_SESSION is thrown.
clienthttp2session.request()
session
ERR_HTTP2_GOAWAY_SESSION
This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.
const http2 = require('node:http2');\nconst clientSession = http2.connect('https://localhost:1234');\nconst {\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS\n} = http2.constants;\n\nconst req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });\nreq.on('response', (headers) => {\n console.log(headers[HTTP2_HEADER_STATUS]);\n req.on('data', (chunk) => { /* .. */ });\n req.on('end', () => { /* .. */ });\n});\n
When the options.waitForTrailers option is set, the 'wantTrailers' event\nis emitted immediately after queuing the last chunk of payload data to be sent.\nThe http2stream.sendTrailers() method can then be called to send trailing\nheaders to the peer.
options.waitForTrailers
'wantTrailers'
http2stream.sendTrailers()
When options.waitForTrailers is set, the Http2Stream will not automatically\nclose when the final DATA frame is transmitted. User code must call either\nhttp2stream.sendTrailers() or http2stream.close() to close the\nHttp2Stream.
http2stream.close()
When options.signal is set with an AbortSignal and then abort on the\ncorresponding AbortController is called, the request will emit an 'error'\nevent with an AbortError error.
options.signal
AbortSignal
abort
AbortController
AbortError
The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:
headers
'GET'
/
Each instance of the Http2Stream class represents a bidirectional HTTP/2\ncommunications stream over an Http2Session instance. Any single Http2Session\nmay have up to 231-1 Http2Stream instances over its lifetime.
User code will not construct Http2Stream instances directly. Rather, these\nare created, managed, and provided to user code through the Http2Session\ninstance. On the server, Http2Stream instances are created either in response\nto an incoming HTTP request (and handed off to user code via the 'stream'\nevent), or in response to a call to the http2stream.pushStream() method.\nOn the client, Http2Stream instances are created and returned when either the\nhttp2session.request() method is called, or in response to an incoming\n'push' event.
http2stream.pushStream()
'push'
The Http2Stream class is a base for the ServerHttp2Stream and\nClientHttp2Stream classes, each of which is used specifically by either\nthe Server or Client side, respectively.
ServerHttp2Stream
ClientHttp2Stream
All Http2Stream instances are Duplex streams. The Writable side of the\nDuplex is used to send data to the connected peer, while the Readable side\nis used to receive data sent by the connected peer.
Duplex
Writable
Readable
The default text character encoding for an Http2Stream is UTF-8. When using an\nHttp2Stream to send text, use the 'content-type' header to set the character\nencoding.
'content-type'
stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200\n});\n
On the server side, instances of ServerHttp2Stream are created either\nwhen:
On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.
On the client, the Http2Stream instance returned by http2session.request()\nmay not be immediately ready for use if the parent Http2Session has not yet\nbeen fully established. In such cases, operations called on the Http2Stream\nwill be buffered until the 'ready' event is emitted. User code should rarely,\nif ever, need to handle the 'ready' event directly. The ready status of an\nHttp2Stream can be determined by checking the value of http2stream.id. If\nthe value is undefined, the stream is not yet ready for use.
'ready'
http2stream.id
All Http2Stream instances are destroyed either when:
RST_STREAM
http2stream.destroy()
When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.
When the Http2Stream instance is destroyed, the 'close' event will\nbe emitted. Because Http2Stream is an instance of stream.Duplex, the\n'end' event will also be emitted if the stream data is currently flowing.\nThe 'error' event may also be emitted if http2stream.destroy() was called\nwith an Error passed as the first argument.
stream.Duplex
'end'
Error
After the Http2Stream has been destroyed, the http2stream.destroyed\nproperty will be true and the http2stream.rstCode property will specify the\nRST_STREAM error code. The Http2Stream instance is no longer usable once\ndestroyed.
http2stream.destroyed
http2stream.rstCode
The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.
'aborted'
The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.
The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.
The HTTP/2 error code used when closing the stream can be retrieved using\nthe http2stream.rstCode property. If the code is any value other than\nNGHTTP2_NO_ERROR (0), an 'error' event will have also been emitted.
NGHTTP2_NO_ERROR
The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.
The 'frameError' event is emitted when an error occurs while attempting to\nsend a frame. When invoked, the handler function will receive an integer\nargument identifying the frame type, and an integer argument identifying the\nerror code. The Http2Stream instance will be destroyed immediately after the\n'frameError' event is emitted.
The 'ready' event is emitted when the Http2Stream has been opened, has\nbeen assigned an id, and can be used. The listener does not expect any\narguments.
id
The 'timeout' event is emitted after no activity is received for this\nHttp2Stream within the number of milliseconds set using\nhttp2stream.setTimeout().\nIts listener does not expect any arguments.
http2stream.setTimeout()
The 'trailers' event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the\nHTTP/2 Headers Object and flags associated with the headers.
'trailers'
This event might not be emitted if http2stream.end() is called\nbefore trailers are received and the incoming data is not being read or\nlistened for.
http2stream.end()
stream.on('trailers', (headers, flags) => {\n console.log(headers);\n});\n
The 'wantTrailers' event is emitted when the Http2Stream has queued the\nfinal DATA frame to be sent on a frame and the Http2Stream is ready to send\ntrailing headers. When initiating a request or response, the waitForTrailers\noption must be set for this event to be emitted.
waitForTrailers
Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.
This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.
net.Socket.bufferSize
Set to true if the Http2Stream instance has been closed.
Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.
Set to true if the END_STREAM flag was set in the request or response\nHEADERS frame received, indicating that no additional data should be received\nand the readable side of the Http2Stream will be closed.
END_STREAM
The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.
Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.
Set to the RST_STREAM error code reported when the Http2Stream is\ndestroyed after either receiving an RST_STREAM frame from the connected peer,\ncalling http2stream.close(), or http2stream.destroy(). Will be\nundefined if the Http2Stream has not been closed.
An object containing the outbound headers sent for this Http2Stream.
An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.
An object containing the outbound trailers sent for this HttpStream.
HttpStream
A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.
Provides miscellaneous information about the current state of the\nHttp2Stream.
state
nghttp2
localClose
1
remoteClose
sumDependencyWeight
PRIORITY
weight
A current state of this Http2Stream.
Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.
Updates the priority for this Http2Stream instance.
const http2 = require('node:http2');\nconst client = http2.connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = http2.constants;\nconst req = client.request({ ':path': '/' });\n\n// Cancel the stream if there's no activity after 5 seconds\nreq.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));\n
Sends a trailing HEADERS frame to the connected HTTP/2 peer. This method\nwill cause the Http2Stream to be immediately closed and must only be\ncalled after the 'wantTrailers' event has been emitted. When sending a\nrequest or sending a response, the options.waitForTrailers option must be set\nin order to keep the Http2Stream open after the final DATA frame so that\ntrailers can be sent.
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond(undefined, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ xyz: 'abc' });\n });\n stream.end('Hello World');\n});\n
The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).
':method'
':path'
The ClientHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Clients. Http2Stream instances on the client\nprovide events such as 'response' and 'push' that are only relevant on\nthe client.
'response'
Emitted when the server sends a 100 Continue status, usually because\nthe request contained Expect: 100-continue. This is an instruction that\nthe client should send the request body.
100 Continue
Expect: 100-continue
The 'headers' event is emitted when an additional block of headers is received\nfor a stream, such as when a block of 1xx informational headers is received.\nThe listener callback is passed the HTTP/2 Headers Object and flags\nassociated with the headers.
'headers'
1xx
stream.on('headers', (headers, flags) => {\n console.log(headers);\n});\n
The 'push' event is emitted when response headers for a Server Push stream\nare received. The listener callback is passed the HTTP/2 Headers Object and\nflags associated with the headers.
stream.on('push', (headers, flags) => {\n console.log(headers);\n});\n
The 'response' event is emitted when a response HEADERS frame has been\nreceived for this stream from the connected HTTP/2 server. The listener is\ninvoked with two arguments: an Object containing the received\nHTTP/2 Headers Object, and flags associated with the headers.
Object
const http2 = require('node:http2');\nconst client = http2.connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n console.log(headers[':status']);\n});\n
The ServerHttp2Stream class is an extension of Http2Stream that is\nused exclusively on HTTP/2 Servers. Http2Stream instances on the server\nprovide additional methods such as http2stream.pushStream() and\nhttp2stream.respond() that are only relevant on the server.
http2stream.respond()
Sends an additional informational HEADERS frame to the connected HTTP/2 peer.
Initiates a push stream. The callback is invoked with the new Http2Stream\ninstance created for the push stream passed as the second argument, or an\nError passed as the first argument.
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {\n if (err) throw err;\n pushStream.respond({ ':status': 200 });\n pushStream.end('some pushed data');\n });\n stream.end('some data');\n});\n
Setting the weight of a push stream is not allowed in the HEADERS frame. Pass\na weight value to http2stream.priority with the silent option set to\ntrue to enable server-side bandwidth balancing between concurrent streams.
http2stream.priority
silent
Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 });\n stream.end('some data');\n});\n
Initiates a response. When the options.waitForTrailers option is set, the\n'wantTrailers' event will be emitted immediately after queuing the last chunk\nof payload data to be sent. The http2stream.sendTrailers() method can then be\nused to sent trailing header fields to the peer.
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respond({ ':status': 200 }, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n stream.end('some data');\n});\n
Initiates a response whose data is read from the given file descriptor. No\nvalidation is performed on the given file descriptor. If an error occurs while\nattempting to read data using the file descriptor, the Http2Stream will be\nclosed using an RST_STREAM frame using the standard INTERNAL_ERROR code.
INTERNAL_ERROR
When used, the Http2Stream object's Duplex interface will be closed\nautomatically.
const http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8'\n };\n stream.respondWithFD(fd, headers);\n stream.on('close', () => fs.closeSync(fd));\n});\n
The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given fd. If the statCheck function is provided, the\nhttp2stream.respondWithFD() method will perform an fs.fstat() call to\ncollect details on the provided file descriptor.
options.statCheck
fs.Stat
statCheck
http2stream.respondWithFD()
fs.fstat()
The offset and length options may be used to limit the response to a\nspecific range subset. This can be used, for instance, to support HTTP Range\nrequests.
offset
length
The file descriptor or FileHandle is not closed when the stream is closed,\nso it will need to be closed manually once it is no longer needed.\nUsing the same file descriptor concurrently for multiple streams\nis not supported and may result in data loss. Re-using a file descriptor\nafter a stream has finished is supported.
FileHandle
When the options.waitForTrailers option is set, the 'wantTrailers' event\nwill be emitted immediately after queuing the last chunk of payload data to be\nsent. The http2stream.sendTrailers() method can then be used to sent trailing\nheader fields to the peer.
const http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n const fd = fs.openSync('/some/file', 'r');\n\n const stat = fs.fstatSync(fd);\n const headers = {\n 'content-length': stat.size,\n 'last-modified': stat.mtime.toUTCString(),\n 'content-type': 'text/plain; charset=utf-8'\n };\n stream.respondWithFD(fd, headers, { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n\n stream.on('close', () => fs.closeSync(fd));\n});\n
Sends a regular file as the response. The path must specify a regular file\nor an 'error' event will be emitted on the Http2Stream object.
path
The optional options.statCheck function may be specified to give user code\nan opportunity to set additional content headers based on the fs.Stat details\nof the given file:
If an error occurs while attempting to read the file data, the Http2Stream\nwill be closed using an RST_STREAM frame using the standard INTERNAL_ERROR\ncode. If the onError callback is defined, then it will be called. Otherwise\nthe stream will be destroyed.
onError
Example using a file path:
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n headers['last-modified'] = stat.mtime.toUTCString();\n }\n\n function onError(err) {\n // stream.respond() can throw if the stream has been destroyed by\n // the other side.\n try {\n if (err.code === 'ENOENT') {\n stream.respond({ ':status': 404 });\n } else {\n stream.respond({ ':status': 500 });\n }\n } catch (err) {\n // Perform actual error handling.\n console.log(err);\n }\n stream.end();\n }\n\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck, onError });\n});\n
The options.statCheck function may also be used to cancel the send operation\nby returning false. For instance, a conditional request may check the stat\nresults to determine if the file has been modified to return an appropriate\n304 response:
304
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n function statCheck(stat, headers) {\n // Check the stat here...\n stream.respond({ ':status': 304 });\n return false; // Cancel the send operation\n }\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { statCheck });\n});\n
The content-length header field will be automatically set.
The options.onError function may also be used to handle all the errors\nthat could happen before the delivery of the file is initiated. The\ndefault behavior is to destroy the stream.
options.onError
const http2 = require('node:http2');\nconst server = http2.createServer();\nserver.on('stream', (stream) => {\n stream.respondWithFile('/some/file',\n { 'content-type': 'text/plain; charset=utf-8' },\n { waitForTrailers: true });\n stream.on('wantTrailers', () => {\n stream.sendTrailers({ ABC: 'some value to send' });\n });\n});\n
True if headers were sent, false otherwise (read-only).
Read-only property mapped to the SETTINGS_ENABLE_PUSH flag of the remote\nclient's most recent SETTINGS frame. Will be true if the remote peer\naccepts push streams, false otherwise. Settings are the same for every\nHttp2Stream in the same Http2Session.
SETTINGS_ENABLE_PUSH
Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the\nnode:http2 module.
If a 'request' listener is registered or http2.createServer() is\nsupplied a callback function, the 'checkContinue' event is emitted each time\na request with an HTTP Expect: 100-continue is received. If this event is\nnot listened for, the server will automatically respond with a status\n100 Continue as appropriate.
'request'
'checkContinue'
Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.
response.writeContinue()
When this event is emitted and handled, the 'request' event will\nnot be emitted.
This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event.
socket
This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.
Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.
The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.
'session'
The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.
'sessionError'
The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.
See also Http2Session's 'stream' event.
const http2 = require('node:http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst server = http2.createServer();\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().\nDefault: 0 (no timeout)
http2server.setTimeout()
Stops the server from establishing new sessions. This does not prevent new\nrequest streams from being created due to the persistent nature of HTTP/2\nsessions. To gracefully shut down the server, call http2session.close() on\nall active sessions.
http2session.close()
If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\nnet.Server.close() for more details.
net.Server.close()
Used to set the timeout value for http2 server requests,\nand sets a callback function that is called when there is no activity\non the Http2Server after msecs milliseconds.
The given callback is registered as a listener on the 'timeout' event.
In case if callback is not a function, a new ERR_INVALID_CALLBACK\nerror will be thrown.
ERR_INVALID_CALLBACK
Used to update the server with the provided settings.
Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.
ERR_HTTP2_INVALID_SETTING_VALUE
settings
Throws ERR_INVALID_ARG_TYPE for invalid settings argument.
ERR_INVALID_ARG_TYPE
The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
A value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the node:http2 module.
Http2SecureServer
If a 'request' listener is registered or http2.createSecureServer()\nis supplied a callback function, the 'checkContinue' event is emitted each\ntime a request with an HTTP Expect: 100-continue is received. If this event\nis not listened for, the server will automatically respond with a status\n100 Continue as appropriate.
This event is emitted when a new TCP stream is established, before the TLS\nhandshake begins. socket is typically an object of type net.Socket.\nUsually users will not want to access this event.
The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.
The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.
const http2 = require('node:http2');\nconst {\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_STATUS,\n HTTP2_HEADER_CONTENT_TYPE\n} = http2.constants;\n\nconst options = getOptionsSomehow();\n\nconst server = http2.createSecureServer(options);\nserver.on('stream', (stream, headers, flags) => {\n const method = headers[HTTP2_HEADER_METHOD];\n const path = headers[HTTP2_HEADER_PATH];\n // ...\n stream.respond({\n [HTTP2_HEADER_STATUS]: 200,\n [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'\n });\n stream.write('hello ');\n stream.end('world');\n});\n
The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 2 minutes.
http2secureServer.setTimeout()
The 'unknownProtocol' event is emitted when a connecting client fails to\nnegotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler\nreceives the socket for handling. If no listener is registered for this event,\nthe connection is terminated. A timeout may be specified using the\n'unknownProtocolTimeout' option passed to http2.createSecureServer().\nSee the Compatibility API.
'unknownProtocol'
'unknownProtocolTimeout'
If callback is provided, it is not invoked until all active sessions have been\nclosed, although the server has already stopped allowing new sessions. See\ntls.Server.close() for more details.
tls.Server.close()
Used to set the timeout value for http2 secure server requests,\nand sets a callback function that is called when there is no activity\non the Http2SecureServer after msecs milliseconds.
Returns a net.Server instance that creates and manages Http2Session\ninstances.
Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.
const http2 = require('node:http2');\n\n// Create an unencrypted HTTP/2 server.\n// Since there are no browsers known that support\n// unencrypted HTTP/2, the use of `http2.createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = http2.createServer();\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
Returns a tls.Server instance that creates and manages Http2Session\ninstances.
const http2 = require('node:http2');\nconst fs = require('node:fs');\n\nconst options = {\n key: fs.readFileSync('server-key.pem'),\n cert: fs.readFileSync('server-cert.pem')\n};\n\n// Create a secure HTTP/2 server\nconst server = http2.createSecureServer(options);\n\nserver.on('stream', (stream, headers) => {\n stream.respond({\n 'content-type': 'text/html; charset=utf-8',\n ':status': 200\n });\n stream.end('<h1>Hello World</h1>');\n});\n\nserver.listen(80);\n
Returns a ClientHttp2Session instance.
const http2 = require('node:http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
Returns an object containing the default settings for an Http2Session\ninstance. This method returns a new object instance every time it is called\nso instances returned may be safely modified for use.
Returns a Buffer instance containing serialized representation of the given\nHTTP/2 settings as specified in the HTTP/2 specification. This is intended\nfor use with the HTTP2-Settings header field.
HTTP2-Settings
const http2 = require('node:http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().
0x00
http2.constants.NGHTTP2_NO_ERROR
0x01
http2.constants.NGHTTP2_PROTOCOL_ERROR
0x02
http2.constants.NGHTTP2_INTERNAL_ERROR
0x03
http2.constants.NGHTTP2_FLOW_CONTROL_ERROR
0x04
http2.constants.NGHTTP2_SETTINGS_TIMEOUT
0x05
http2.constants.NGHTTP2_STREAM_CLOSED
0x06
http2.constants.NGHTTP2_FRAME_SIZE_ERROR
0x07
http2.constants.NGHTTP2_REFUSED_STREAM
0x08
http2.constants.NGHTTP2_CANCEL
0x09
http2.constants.NGHTTP2_COMPRESSION_ERROR
0x0a
http2.constants.NGHTTP2_CONNECT_ERROR
0x0b
http2.constants.NGHTTP2_ENHANCE_YOUR_CALM
0x0c
http2.constants.NGHTTP2_INADEQUATE_SECURITY
0x0d
http2.constants.NGHTTP2_HTTP_1_1_REQUIRED
The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().
This symbol can be set as a property on the HTTP/2 headers object with an array\nvalue in order to provide a list of headers considered sensitive.\nSee Sensitive headers for more details.
The Compatibility API has the goal of providing a similar developer experience\nof HTTP/1 when using HTTP/2, making it possible to develop applications\nthat support both HTTP/1 and HTTP/2. This API targets only the\npublic API of the HTTP/1. However many modules use internal\nmethods or state, and those are not supported as it is a completely\ndifferent implementation.
The following example creates an HTTP/2 server using the compatibility\nAPI:
const http2 = require('node:http2');\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n
In order to create a mixed HTTPS and HTTP/2 server, refer to the\nALPN negotiation section.\nUpgrading from non-tls HTTP/1 servers is not supported.
The HTTP/2 compatibility API is composed of Http2ServerRequest and\nHttp2ServerResponse. They aim at API compatibility with HTTP/1, but\nthey do not hide the differences between the protocols. As an example,\nthe status message for HTTP codes is ignored.
Http2ServerRequest
Http2ServerResponse
ALPN negotiation allows supporting both HTTPS and HTTP/2 over\nthe same socket. The req and res objects can be either HTTP/1 or\nHTTP/2, and an application must restrict itself to the public API of\nHTTP/1, and detect if it is possible to use the more advanced\nfeatures of HTTP/2.
req
res
The following example creates a server that supports both protocols:
const { createSecureServer } = require('node:http2');\nconst { readFileSync } = require('node:fs');\n\nconst cert = readFileSync('./cert.pem');\nconst key = readFileSync('./key.pem');\n\nconst server = createSecureServer(\n { cert, key, allowHTTP1: true },\n onRequest\n).listen(4443);\n\nfunction onRequest(req, res) {\n // Detects if it is a HTTPS request or HTTP/2\n const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?\n req.stream.session : req;\n res.writeHead(200, { 'content-type': 'application/json' });\n res.end(JSON.stringify({\n alpnProtocol,\n httpVersion: req.httpVersion\n }));\n}\n
The 'request' event works identically on both HTTPS and\nHTTP/2.
A Http2ServerRequest object is created by http2.Server or\nhttp2.SecureServer and passed as the first argument to the\n'request' event. It may be used to access a request status, headers, and\ndata.
http2.Server
http2.SecureServer
The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.
The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.
Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.
The request.aborted property will be true if the request has\nbeen aborted.
request.aborted
The request authority pseudo header field. Because HTTP/2 allows requests\nto set either :authority or host, this value is derived from\nreq.headers[':authority'] if present. Otherwise, it is derived from\nreq.headers['host'].
req.headers[':authority']
req.headers['host']
The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.
request.complete
See request.socket.
request.socket
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n
See HTTP/2 Headers Object.
In HTTP/2, the request path, host name, protocol, and method are represented as\nspecial headers prefixed with the : character (e.g. ':path'). These special\nheaders will be included in the request.headers object. Care must be taken not\nto inadvertently modify these special headers or errors may occur. For instance,\nremoving all headers from the request will cause errors to occur:
:
request.headers
removeAllHeaders(request.headers);\nassert(request.url); // Fails because the :path header has been removed\n
In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server. Returns\n'2.0'.
'2.0'
Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.
message.httpVersionMajor
message.httpVersionMinor
The request method as a string. Read-only. Examples: 'GET', 'DELETE'.
'DELETE'
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n
The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.
The request scheme pseudo header field indicating the scheme\nportion of the target URL.
Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.
destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.
destroyed
readable
writable
request.stream
destroy, emit, end, on and once methods will be called on\nrequest.stream.
on
once
setTimeout method will be called on request.stream.session.
request.stream.session
pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.
All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.
request.socket.getPeerCertificate()
The Http2Stream object backing the request.
The request/response trailers object. Only populated at the 'end' event.
Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
Then request.url will be:
request.url
'/status?name=ryan'\n
To parse the url into its parts, new URL() can be used:
new URL()
$ node\n> new URL('/status?name=ryan', 'http://example.com')\nURL {\n href: 'http://example.com/status?name=ryan',\n origin: 'http://example.com',\n protocol: 'http:',\n username: '',\n password: '',\n host: 'example.com',\n hostname: 'example.com',\n port: '',\n pathname: '/status',\n search: '?name=ryan',\n searchParams: URLSearchParams { 'name' => 'ryan' },\n hash: ''\n}\n
Calls destroy() on the Http2Stream that received\nthe Http2ServerRequest. If error is provided, an 'error' event\nis emitted and error is passed as an argument to any listeners on the event.
destroy()
It does nothing if the stream was already destroyed.
Sets the Http2Stream's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.
If no 'timeout' listener is added to the request, the response, or\nthe server, then Http2Streams are destroyed when they time out. If a\nhandler is assigned to the request, the response, or the server's 'timeout'\nevents, timed out sockets must be handled explicitly.
This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.
Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.
response.end()
Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the HTTP/2 multiplexing for transmission over the network. It\ndoes not imply that the client has received anything yet.
After this event, no more events will be emitted on the response object.
This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
TypeError
Call http2stream.pushStream() with the given headers, and wrap the\ngiven Http2Stream on a newly created Http2ServerResponse as the callback\nparameter if successful. When Http2ServerRequest is closed, the callback is\ncalled with an error ERR_HTTP2_INVALID_STREAM.
ERR_HTTP2_INVALID_STREAM
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.
If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).
data
response.write(data, encoding)
response.end(callback)
If callback is specified, it will be called when the response stream\nis finished.
Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.
const contentType = response.getHeader('content-type');\n
Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
The object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
response.getHeaders()
obj.toString()
obj.hasOwnProperty()
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n
Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
name
const hasContentType = response.hasHeader('content-type');\n
Removes a header that has been queued for implicit sending.
response.removeHeader('Content-Encoding');\n
See response.socket.
response.socket
Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.
A reference to the original HTTP2 request object.
request
When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
This should only be disabled for testing; HTTP requires the Date header\nin responses.
destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.
response.stream
destroy, emit, end, on and once methods will be called on\nresponse.stream.
setTimeout method will be called on response.stream.session.
response.stream.session
const http2 = require('node:http2');\nconst server = http2.createServer((req, res) => {\n const ip = req.socket.remoteAddress;\n const port = req.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n
When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
response.writeHead()
response.statusCode = 404;\n
After response header was sent to the client, this property indicates the\nstatus code which was sent out.
Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns\nan empty string.
The Http2Stream object backing the response.
Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.
writable.writableFinished
Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name.
response.setHeader('Content-Type', 'text/html; charset=utf-8');\n
or
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
response.setHeader()
// Returns content-type = text/plain\nconst server = http2.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });\n res.end('ok');\n});\n
If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
In the node:http module, the response body is omitted when the\nrequest is a HEAD request. Similarly, the 204 and 304 responses\nmust not include a message body.
node:http
204
chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'. callback will be called when this chunk\nof data is flushed.
chunk
encoding
'utf8'
This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.
The first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
response.write()
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
'drain'
Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.
Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.
404
Returns a reference to the Http2ServerResponse, so that calls can be chained.
For compatibility with HTTP/1, a human-readable statusMessage may be\npassed as the second argument. However, because the statusMessage has no\nmeaning within HTTP/2, the argument will have no effect and a process warning\nwill be emitted.
statusMessage
const body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain; charset=utf-8',\n});\n
Content-Length is given in bytes not characters. The\nBuffer.byteLength() API may be used to determine the number of bytes in a\ngiven encoding. On outbound messages, Node.js does not check if Content-Length\nand the length of the body being transmitted are equal or not. However, when\nreceiving messages, Node.js will automatically reject messages when the\nContent-Length does not match the actual payload size.
Content-Length
Buffer.byteLength()
This method may be called at most one time on a message before\nresponse.end() is called.
If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.
const { PerformanceObserver } = require('node:perf_hooks');\n\nconst obs = new PerformanceObserver((items) => {\n const entry = items.getEntries()[0];\n console.log(entry.entryType); // prints 'http2'\n if (entry.name === 'Http2Session') {\n // Entry contains statistics about the Http2Session\n } else if (entry.name === 'Http2Stream') {\n // Entry contains statistics about the Http2Stream\n }\n});\nobs.observe({ entryTypes: ['http2'] });\n
The entryType property of the PerformanceEntry will be equal to 'http2'.
entryType
PerformanceEntry
'http2'
The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.
'Http2Stream'
'Http2Session'
If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:
bytesRead
bytesWritten
timeToFirstByte
startTime
timeToFirstByteSent
timeToFirstHeader
If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:
framesReceived
framesSent
pingRTT
streamAverageDuration
streamCount
type
'server'
'client'
HTTP/2 requires requests to have either the :authority pseudo-header\nor the host header. Prefer :authority when constructing an HTTP/2\nrequest directly, and host when converting from HTTP/1 (in proxies,\nfor instance).
The compatibility API falls back to host if :authority is not\npresent. See request.authority for more information. However,\nif you don't use the compatibility API (or use req.headers directly),\nyou need to implement any fall-back behavior yourself.
request.authority
req.headers