See More

{ "type": "module", "source": "doc/api/http2.md", "modules": [ { "textRaw": "HTTP/2", "name": "http/2", "introduced_in": "v8.4.0", "type": "module", "meta": { "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." } ] }, "stability": 2, "stabilityText": "Stable", "desc": "

The node:http2 module provides an implementation of the HTTP/2 protocol.\nIt can be accessed using:

\n
const http2 = require('node:http2');\n
", "modules": [ { "textRaw": "Determining if crypto support is unavailable", "name": "determining_if_crypto_support_is_unavailable", "type": "module", "desc": "

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.

\n

When using CommonJS, the error thrown can be caught using try/catch:

\n
let http2;\ntry {\n  http2 = require('node:http2');\n} catch (err) {\n  console.error('http2 support is disabled!');\n}\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).

\n

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:

\n
let http2;\ntry {\n  http2 = await import('node:http2');\n} catch (err) {\n  console.error('http2 support is disabled!');\n}\n
", "displayName": "Determining if crypto support is unavailable" }, { "textRaw": "Core API", "name": "core_api", "type": "module", "desc": "

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.

\n

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.

", "modules": [ { "textRaw": "Server-side example", "name": "server-side_example", "type": "module", "desc": "

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.

\n
import { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst server = createSecureServer({\n  key: readFileSync('localhost-privkey.pem'),\n  cert: readFileSync('localhost-cert.pem'),\n});\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
\n
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
\n

To generate the certificate and key for this example, run:

\n
openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \\\n  -keyout localhost-privkey.pem -out localhost-cert.pem\n
", "displayName": "Server-side example" }, { "textRaw": "Client-side example", "name": "client-side_example", "type": "module", "desc": "

The following illustrates an HTTP/2 client:

\n
import { connect } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst client = connect('https://localhost:8443', {\n  ca: 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
\n
const http2 = require('node:http2');\nconst fs = require('node:fs');\n\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
", "displayName": "Client-side example" }, { "textRaw": "Headers object", "name": "headers_object", "type": "module", "desc": "

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).

\n
const headers = {\n  ':status': '200',\n  'content-type': 'text-plain',\n  'ABC': ['has', 'more', 'than', 'one', 'value'],\n};\n\nstream.respond(headers);\n
\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.

\n

For incoming headers:

\n\n
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream, headers) => {\n  console.log(headers[':path']);\n  console.log(headers.ABC);\n});\n
\n
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
", "modules": [ { "textRaw": "Raw headers", "name": "raw_headers", "type": "module", "desc": "

In some APIs, in addition to object format, headers can also be passed or\naccessed as a raw flat array, preserving details of ordering and\nduplicate keys to match the raw transmission format.

\n

In this format 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. Duplicate headers are\nnot merged and so each key-value pair will appear separately.

\n

This can be useful for cases such as proxies, where existing headers\nshould be exactly forwarded as received, or as a performance\noptimization when the headers are already available in raw format.

\n
const rawHeaders = [\n  ':status',\n  '404',\n  'content-type',\n  'text/plain',\n];\n\nstream.respond(rawHeaders);\n
", "displayName": "Raw headers" }, { "textRaw": "Sensitive headers", "name": "sensitive_headers", "type": "module", "desc": "

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:

\n
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
\n

For some headers, such as Authorization and short Cookie headers,\nthis flag is set automatically.

\n

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.

\n

For raw headers, this should still be set as a property on the array, like\nrawHeadersArray[http2.sensitiveHeaders] = ['cookie'], not as a separate key\nand value pair within the array itself.

", "displayName": "Sensitive headers" } ], "displayName": "Headers object" }, { "textRaw": "Settings object", "name": "settings_object", "type": "module", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/29833", "description": "The `maxConcurrentStreams` setting is stricter." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "The `maxHeaderListSize` setting is now strictly enforced." } ] }, "desc": "

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.

\n\n

All additional properties on the settings object are ignored.

", "displayName": "Settings object" }, { "textRaw": "Error handling", "name": "error_handling", "type": "module", "desc": "

There are several types of error conditions that may arise when using the\nnode:http2 module:

\n

Validation errors occur when an incorrect argument, option, or setting value is\npassed in. These will always be reported by a synchronous throw.

\n

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.

\n

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.

\n

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.

", "displayName": "Error handling" }, { "textRaw": "Invalid character handling in header names and values", "name": "invalid_character_handling_in_header_names_and_values", "type": "module", "desc": "

The HTTP/2 implementation applies stricter handling of invalid characters in\nHTTP header names and values than the HTTP/1 implementation.

\n

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.

\n

Header field-names must only contain one or more of the following ASCII\ncharacters: a-z, A-Z, 0-9, !, #, $, %, &, ', *, +,\n-, ., ^, _, ` (backtick), |, and ~.

\n

Using invalid characters within an HTTP header field name will cause the\nstream to be closed with a protocol error being reported.

\n

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.

", "displayName": "Invalid character handling in header names and values" }, { "textRaw": "Push streams on the client", "name": "push_streams_on_the_client", "type": "module", "desc": "

To receive pushed streams on the client, set a listener for the 'stream'\nevent on the ClientHttp2Session:

\n
import { connect } from 'node:http2';\n\nconst client = 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
\n
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
", "displayName": "Push streams on the client" }, { "textRaw": "Supporting the `CONNECT` method", "name": "supporting_the_`connect`_method", "type": "module", "desc": "

The CONNECT method is used to allow an HTTP/2 server to be used as a proxy\nfor TCP/IP connections.

\n

A simple TCP Server:

\n
import { createServer } from 'node:net';\n\nconst server = 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
\n
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
\n

An HTTP/2 CONNECT proxy:

\n
import { createServer, constants } from 'node:http2';\nconst { NGHTTP2_REFUSED_STREAM, NGHTTP2_CONNECT_ERROR } = constants;\nimport { connect } from 'node:net';\n\nconst proxy = 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 = 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(NGHTTP2_CONNECT_ERROR);\n  });\n});\n\nproxy.listen(8001);\n
\n
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
\n

An HTTP/2 CONNECT client:

\n
import { connect, constants } from 'node:http2';\n\nconst client = 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:8000',\n});\n\nreq.on('response', (headers) => {\n  console.log(headers[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
\n
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:8000',\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
", "displayName": "Supporting the `CONNECT` method" }, { "textRaw": "The extended `CONNECT` protocol", "name": "the_extended_`connect`_protocol", "type": "module", "desc": "

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).

\n

The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using\nthe enableConnectProtocol setting:

\n
import { createServer } from 'node:http2';\nconst settings = { enableConnectProtocol: true };\nconst server = createServer({ settings });\n
\n
const http2 = require('node:http2');\nconst settings = { enableConnectProtocol: true };\nconst server = http2.createServer({ settings });\n
\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:

\n
import { connect } from 'node:http2';\nconst client = 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
\n
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
", "displayName": "The extended `CONNECT` protocol" } ], "classes": [ { "textRaw": "Class: `Http2Session`", "name": "Http2Session", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\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.

\n

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.

\n

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.

", "modules": [ { "textRaw": "`Http2Session` and sockets", "name": "`http2session`_and_sockets", "type": "module", "desc": "

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.

\n

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.

\n

Once a Socket has been bound to an Http2Session, user code should rely\nsolely on the API of the Http2Session.

", "displayName": "`Http2Session` and sockets" } ], "events": [ { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted once the Http2Session has been destroyed. Its\nlistener does not expect any arguments.

" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {Http2Session}", "name": "session", "type": "Http2Session" }, { "textRaw": "`socket` {net.Socket}", "name": "socket", "type": "net.Socket" } ], "desc": "

The 'connect' event is emitted once the Http2Session has been successfully\nconnected to the remote peer and communication may begin.

\n

User code will typically not listen for this event directly.

" }, { "textRaw": "Event: `'error'`", "name": "error", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "

The 'error' event is emitted when an error occurs during the processing of\nan Http2Session.

" }, { "textRaw": "Event: `'frameError'`", "name": "frameError", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {integer} The frame type.", "name": "type", "type": "integer", "desc": "The frame type." }, { "textRaw": "`code` {integer} The error code.", "name": "code", "type": "integer", "desc": "The error code." }, { "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", "name": "id", "type": "integer", "desc": "The stream id (or `0` if the frame isn't associated with a stream)." } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'goaway'`", "name": "goaway", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame.", "name": "errorCode", "type": "number", "desc": "The HTTP/2 error code specified in the `GOAWAY` frame." }, { "textRaw": "`lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified).", "name": "lastStreamID", "type": "number", "desc": "The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified)." }, { "textRaw": "`opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data.", "name": "opaqueData", "type": "Buffer", "desc": "If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data." } ], "desc": "

The 'goaway' event is emitted when a GOAWAY frame is received.

\n

The Http2Session instance will be shut down automatically when the 'goaway'\nevent is emitted.

" }, { "textRaw": "Event: `'localSettings'`", "name": "localSettings", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'localSettings' event is emitted when an acknowledgment SETTINGS frame\nhas been received.

\n

When using http2session.settings() to submit new settings, the modified\nsettings do not take effect until the 'localSettings' event is emitted.

\n
session.settings({ enablePush: false });\n\nsession.on('localSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: `'ping'`", "name": "ping", "type": "event", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`payload` {Buffer} The `PING` frame 8-byte payload", "name": "payload", "type": "Buffer", "desc": "The `PING` frame 8-byte payload" } ], "desc": "

The 'ping' event is emitted whenever a PING frame is received from the\nconnected peer.

" }, { "textRaw": "Event: `'remoteSettings'`", "name": "remoteSettings", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "A copy of the `SETTINGS` frame received." } ], "desc": "

The 'remoteSettings' event is emitted when a new SETTINGS frame is received\nfrom the connected peer.

\n
session.on('remoteSettings', (settings) => {\n  /* Use the new settings */\n});\n
" }, { "textRaw": "Event: `'stream'`", "name": "stream", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`stream` {Http2Stream} A reference to the stream", "name": "stream", "type": "Http2Stream", "desc": "A reference to the stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers} An array containing the raw headers", "name": "rawHeaders", "type": "HTTP/2 Raw Headers", "desc": "An array containing the raw headers" } ], "desc": "

The 'stream' event is emitted when a new Http2Stream is created.

\n
session.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
\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:

\n
import { createServer } from 'node:http2';\n\n// Create an unencrypted HTTP/2 server\nconst server = 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(8000);\n
\n
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(8000);\n
\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.

" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

\n
session.setTimeout(2000);\nsession.on('timeout', () => { /* .. */ });\n
" } ], "properties": [ { "textRaw": "Type: {string | undefined}", "name": "alpnProtocol", "type": "string | undefined", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {boolean}", "name": "closed", "type": "boolean", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been closed, otherwise\nfalse.

" }, { "textRaw": "Type: {boolean}", "name": "connecting", "type": "boolean", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {boolean}", "name": "destroyed", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Will be true if this Http2Session instance has been destroyed and must no\nlonger be used, otherwise false.

" }, { "textRaw": "Type: {boolean | undefined}", "name": "encrypted", "type": "boolean | undefined", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {HTTP/2 Settings Object}", "name": "localSettings", "type": "HTTP/2 Settings Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current local settings of this\nHttp2Session. The local settings are local to this Http2Session instance.

" }, { "textRaw": "Type: {string[] | undefined}", "name": "originSet", "type": "string[] | undefined", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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.

\n

The originSet property is only available when using a secure TLS connection.

" }, { "textRaw": "Type: {boolean}", "name": "pendingSettingsAck", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {HTTP/2 Settings Object}", "name": "remoteSettings", "type": "HTTP/2 Settings Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A prototype-less object describing the current remote settings of this\nHttp2Session. The remote settings are set by the connected HTTP/2 peer.

" }, { "textRaw": "Type: {net.Socket | tls.TLSSocket}", "name": "socket", "type": "net.Socket | tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v26.6.0", "pr-url": "https://github.com/nodejs/node/pull/64427", "description": "Calling `destroy` no longer throws and instead destroys the `Http2Session`." } ] }, "desc": "

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.

\n

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.

\n

destroy, setTimeout, ref, and unref methods will be called on this\nHttp2Session.

\n

All other interactions will be routed directly to the socket.

" }, { "textRaw": "Type: {Object}", "name": "state", "type": "Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Session.

\n

An object describing the current status of this Http2Session.

", "options": [ { "textRaw": "`effectiveLocalWindowSize` {number} The current local (receive) flow control window size for the `Http2Session`.", "name": "effectiveLocalWindowSize", "type": "number", "desc": "The current local (receive) flow control window size for the `Http2Session`." }, { "textRaw": "`effectiveRecvDataLength` {number} The current number of bytes that have been received since the last flow control `WINDOW_UPDATE`.", "name": "effectiveRecvDataLength", "type": "number", "desc": "The current number of bytes that have been received since the last flow control `WINDOW_UPDATE`." }, { "textRaw": "`nextStreamID` {number} The numeric identifier to be used the next time a new `Http2Stream` is created by this `Http2Session`.", "name": "nextStreamID", "type": "number", "desc": "The numeric identifier to be used the next time a new `Http2Stream` is created by this `Http2Session`." }, { "textRaw": "`localWindowSize` {number} The number of bytes that the remote peer can send without receiving a `WINDOW_UPDATE`.", "name": "localWindowSize", "type": "number", "desc": "The number of bytes that the remote peer can send without receiving a `WINDOW_UPDATE`." }, { "textRaw": "`lastProcStreamID` {number} The numeric id of the `Http2Stream` for which a `HEADERS` or `DATA` frame was most recently received.", "name": "lastProcStreamID", "type": "number", "desc": "The numeric id of the `Http2Stream` for which a `HEADERS` or `DATA` frame was most recently received." }, { "textRaw": "`remoteWindowSize` {number} The number of bytes that this `Http2Session` may send without receiving a `WINDOW_UPDATE`.", "name": "remoteWindowSize", "type": "number", "desc": "The number of bytes that this `Http2Session` may send without receiving a `WINDOW_UPDATE`." }, { "textRaw": "`outboundQueueSize` {number} The number of frames currently within the outbound queue for this `Http2Session`.", "name": "outboundQueueSize", "type": "number", "desc": "The number of frames currently within the outbound queue for this `Http2Session`." }, { "textRaw": "`deflateDynamicTableSize` {number} The current size in bytes of the outbound header compression state table.", "name": "deflateDynamicTableSize", "type": "number", "desc": "The current size in bytes of the outbound header compression state table." }, { "textRaw": "`inflateDynamicTableSize` {number} The current size in bytes of the inbound header compression state table.", "name": "inflateDynamicTableSize", "type": "number", "desc": "The current size in bytes of the inbound header compression state table." } ] }, { "textRaw": "Type: {number}", "name": "type", "type": "number", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" } ], "methods": [ { "textRaw": "`http2session.close([callback])`", "name": "close", "type": "method", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

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.

\n

If specified, the callback function is registered as a handler for the\n'close' event.

" }, { "textRaw": "`http2session.destroy([error][, code])`", "name": "destroy", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error} An `Error` object if the `Http2Session` is being destroyed due to an error.", "name": "error", "type": "Error", "desc": "An `Error` object if the `Http2Session` is being destroyed due to an error.", "optional": true }, { "textRaw": "`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`.", "name": "code", "type": "number", "desc": "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`.", "optional": true } ] } ], "desc": "

Immediately terminates the Http2Session and the associated net.Socket or\ntls.TLSSocket.

\n

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.

\n

If there are any remaining open Http2Streams associated with the\nHttp2Session, those will also be destroyed.

" }, { "textRaw": "`http2session.goaway([code[, lastStreamID[, opaqueData]]])`", "name": "goaway", "type": "method", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} An HTTP/2 error code", "name": "code", "type": "number", "desc": "An HTTP/2 error code", "optional": true }, { "textRaw": "`lastStreamID` {number} The numeric ID of the last processed `Http2Stream`", "name": "lastStreamID", "type": "number", "desc": "The numeric ID of the last processed `Http2Stream`", "optional": true }, { "textRaw": "`opaqueData` {Buffer | TypedArray | DataView} A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", "name": "opaqueData", "type": "Buffer | TypedArray | DataView", "desc": "A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.", "optional": true } ] } ], "desc": "

Transmits a GOAWAY frame to the connected peer without shutting down the\nHttp2Session.

" }, { "textRaw": "`http2session.ping([payload, ]callback)`", "name": "ping", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`payload` {Buffer | TypedArray | DataView} Optional ping payload.", "name": "payload", "type": "Buffer | TypedArray | DataView", "desc": "Optional ping payload.", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "

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.

\n

The maximum number of outstanding (unacknowledged) pings is determined by the\nmaxOutstandingPings configuration option. The default maximum is 10.

\n

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.

\n

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.

\n
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
\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.

" }, { "textRaw": "`http2session.ref()`", "name": "ref", "type": "method", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls ref() on this Http2Session\ninstance's underlying net.Socket.

" }, { "textRaw": "`http2session.setLocalWindowSize(windowSize)`", "name": "setLocalWindowSize", "type": "method", "meta": { "added": [ "v15.3.0", "v14.18.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`windowSize` {number}", "name": "windowSize", "type": "number" } ] } ], "desc": "

Sets the local endpoint's window size.\nThe windowSize is the total window size to set, not\nthe delta.

\n
import { createServer } from 'node:http2';\n\nconst server = createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('session', (session) => {\n\n  // Set local window size to be 2 ** 20\n  session.setLocalWindowSize(expectedWindowSize);\n});\n
\n
const http2 = require('node:http2');\n\nconst server = http2.createServer();\nconst expectedWindowSize = 2 ** 20;\nserver.on('session', (session) => {\n\n  // Set local window size to be 2 ** 20\n  session.setLocalWindowSize(expectedWindowSize);\n});\n
\n

For http2 clients the proper event is either 'connect' or 'remoteSettings'.

" }, { "textRaw": "`http2session.setTimeout(msecs, callback)`", "name": "setTimeout", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "

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.

" }, { "textRaw": "`http2session.settings([settings][, callback])`", "name": "settings", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object", "optional": true }, { "textRaw": "`callback` {Function} Callback that is called once the session is connected or right away if the session is already connected.", "name": "callback", "type": "Function", "desc": "Callback that is called once the session is connected or right away if the session is already connected.", "options": [ { "textRaw": "`err` {Error | null}", "name": "err", "type": "Error | null" }, { "textRaw": "`settings` {HTTP/2 Settings Object} The updated `settings` object.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The updated `settings` object." }, { "textRaw": "`duration` {integer}", "name": "duration", "type": "integer" } ], "optional": true } ] } ], "desc": "

Updates the current local settings for this Http2Session and sends a new\nSETTINGS frame to the connected HTTP/2 peer.

\n

Once called, the http2session.pendingSettingsAck property will be true\nwhile the session is waiting for the remote peer to acknowledge the new\nsettings.

\n

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.

" }, { "textRaw": "`http2session.unref()`", "name": "unref", "type": "method", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Calls unref() on this Http2Session\ninstance's underlying net.Socket.

" } ] }, { "textRaw": "Class: `ServerHttp2Session`", "name": "ServerHttp2Session", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "", "methods": [ { "textRaw": "`serverhttp2session.altsvc(alt, originOrStream)`", "name": "altsvc", "type": "method", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`alt` {string} A description of the alternative service configuration as defined by RFC 7838.", "name": "alt", "type": "string", "desc": "A description of the alternative service configuration as defined by RFC 7838." }, { "textRaw": "`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.", "name": "originOrStream", "type": "number | string | URL | Object", "desc": "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." } ] } ], "desc": "

Submits an ALTSVC frame (as defined by RFC 7838) to the connected client.

\n
import { createServer } from 'node:http2';\n\nconst server = 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
\n
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
\n

Sending an ALTSVC frame with a specific stream ID indicates that the alternate\nservice is associated with the origin of the given Http2Stream.

\n

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.

\n

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.

\n

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.

" }, { "textRaw": "`serverhttp2session.origin(...origins)`", "name": "origin", "type": "method", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "name": "...origins" } ] } ], "desc": "

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.

\n
import { createSecureServer } from 'node:http2';\nconst options = getSecureOptionsSomehow();\nconst server = 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
\n
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
\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.

\n

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.

\n

Alternatively, the origins option may be used when creating a new HTTP/2\nserver using the http2.createSecureServer() method:

\n
import { createSecureServer } from 'node:http2';\nconst options = getSecureOptionsSomehow();\noptions.origins = ['https://example.com', 'https://example.org'];\nconst server = createSecureServer(options);\nserver.on('stream', (stream) => {\n  stream.respond();\n  stream.end('ok');\n});\n
\n
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
" } ], "modules": [ { "textRaw": "Specifying alternative services", "name": "specifying_alternative_services", "type": "module", "desc": "

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.

\n

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.

\n

Multiple alternatives may be specified, for instance: 'h2=\"example.org:81\", h2=\":82\"'.

\n

The protocol identifier ('h2' in the examples) may be any valid\nALPN Protocol ID.

\n

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.

", "displayName": "Specifying alternative services" } ] }, { "textRaw": "Class: `ClientHttp2Session`", "name": "ClientHttp2Session", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "", "events": [ { "textRaw": "Event: `'altsvc'`", "name": "altsvc", "type": "event", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "params": [ { "textRaw": "`alt` {string}", "name": "alt", "type": "string" }, { "textRaw": "`origin` {string}", "name": "origin", "type": "string" }, { "textRaw": "`streamId` {number}", "name": "streamId", "type": "number" } ], "desc": "

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.

\n
import { connect } from 'node:http2';\nconst client = 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
\n
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
" }, { "textRaw": "Event: `'origin'`", "name": "origin", "type": "event", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "params": [ { "textRaw": "`origins` {string[]}", "name": "origins", "type": "string[]" } ], "desc": "

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.

\n
import { connect } from 'node:http2';\nconst client = 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
\n
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
\n

The 'origin' event is only emitted when using a secure TLS connection.

" } ], "methods": [ { "textRaw": "`clienthttp2session.request(headers[, options])`", "name": "request", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58293", "description": "The `weight` option is now ignored, setting it will trigger a runtime warning." }, { "version": [ "v24.2.0", "v22.17.0", "v20.19.6" ], "pr-url": "https://github.com/nodejs/node/pull/58313", "description": "Following the deprecation of priority signaling as of RFC 9113, `weight` option is deprecated." }, { "version": [ "v24.0.0", "v22.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/57917", "description": "Allow passing headers in raw array format." } ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object | HTTP/2 Raw Headers}", "name": "headers", "type": "HTTP/2 Headers Object | HTTP/2 Raw Headers" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`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.", "name": "endStream", "type": "boolean", "desc": "`true` if the `Http2Stream` _writable_ side should be closed initially, such as when sending a `GET` request that should not expect a payload body." }, { "textRaw": "`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`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "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." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." }, { "textRaw": "`signal` {AbortSignal} An AbortSignal that may be used to abort an ongoing request.", "name": "signal", "type": "AbortSignal", "desc": "An AbortSignal that may be used to abort an ongoing request." } ], "optional": true } ], "return": { "textRaw": "Returns: {ClientHttp2Stream}", "name": "return", "type": "ClientHttp2Stream" } } ], "desc": "

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.

\n

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.

\n

If the session becomes unavailable before the request can be created, the\nreturned stream will emit ERR_HTTP2_GOAWAY_SESSION or\nERR_HTTP2_INVALID_SESSION asynchronously.

\n

This method is only available if http2session.type is equal to\nhttp2.constants.NGHTTP2_SESSION_CLIENT.

\n
import { connect, constants } from 'node:http2';\nconst clientSession = connect('https://localhost:1234');\nconst {\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n} = 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
\n
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
\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.

\n

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.

\n

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.

\n

The :method and :path pseudo-headers are not specified within headers,\nthey respectively default to:

\n" } ] }, { "textRaw": "Class: `Http2Stream`", "name": "Http2Stream", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

\n

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.

\n

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.

\n

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.

\n

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.

\n
stream.respond({\n  'content-type': 'text/html; charset=utf-8',\n  ':status': 200,\n});\n
", "modules": [ { "textRaw": "`Http2Stream` Lifecycle", "name": "`http2stream`_lifecycle", "type": "module", "modules": [ { "textRaw": "Creation", "name": "creation", "type": "module", "desc": "

On the server side, instances of ServerHttp2Stream are created either\nwhen:

\n\n

On the client side, instances of ClientHttp2Stream are created when the\nhttp2session.request() method is called.

\n

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.

", "displayName": "Creation" }, { "textRaw": "Destruction", "name": "destruction", "type": "module", "desc": "

All Http2Stream instances are destroyed either when:

\n\n

When an Http2Stream instance is destroyed, an attempt will be made to send an\nRST_STREAM frame to the connected peer.

\n

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.

\n

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.

", "displayName": "Destruction" } ], "displayName": "`Http2Stream` Lifecycle" } ], "events": [ { "textRaw": "Event: `'aborted'`", "name": "aborted", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2Stream instance is\nabnormally aborted in mid-communication.\nIts listener does not expect any arguments.

\n

The 'aborted' event will only be emitted if the Http2Stream writable side\nhas not been ended.

" }, { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'close' event is emitted when the Http2Stream is destroyed. Once\nthis event is emitted, the Http2Stream instance is no longer usable.

\n

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.

" }, { "textRaw": "Event: `'error'`", "name": "error", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" } ], "desc": "

The 'error' event is emitted when an error occurs during the processing of\nan Http2Stream.

" }, { "textRaw": "Event: `'frameError'`", "name": "frameError", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`type` {integer} The frame type.", "name": "type", "type": "integer", "desc": "The frame type." }, { "textRaw": "`code` {integer} The error code.", "name": "code", "type": "integer", "desc": "The error code." }, { "textRaw": "`id` {integer} The stream id (or `0` if the frame isn't associated with a stream).", "name": "id", "type": "integer", "desc": "The stream id (or `0` if the frame isn't associated with a stream)." } ], "desc": "

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.

" }, { "textRaw": "Event: `'ready'`", "name": "ready", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'trailers'`", "name": "trailers", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers}", "name": "rawHeaders", "type": "HTTP/2 Raw Headers" } ], "desc": "

The 'trailers' event is emitted when a block of headers associated with\ntrailing header fields is received. The listener callback is passed the HTTP/2 Headers Object, flags associated\nwith the headers, and the headers in raw format (see HTTP/2 Raw Headers).

\n

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.

\n
stream.on('trailers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'wantTrailers'`", "name": "wantTrailers", "type": "event", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "params": [], "desc": "

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.

" } ], "properties": [ { "textRaw": "Type: {boolean}", "name": "aborted", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance was aborted abnormally. When set,\nthe 'aborted' event will have been emitted.

" }, { "textRaw": "Type: {number}", "name": "bufferSize", "type": "number", "meta": { "added": [ "v11.2.0", "v10.16.0" ], "changes": [] }, "desc": "

This property shows the number of characters currently buffered to be written.\nSee net.Socket.bufferSize for details.

" }, { "textRaw": "Type: {boolean}", "name": "closed", "type": "boolean", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been closed.

" }, { "textRaw": "Type: {boolean}", "name": "destroyed", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has been destroyed and is no longer\nusable.

" }, { "textRaw": "Type: {boolean}", "name": "endAfterHeaders", "type": "boolean", "meta": { "added": [ "v10.11.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {number | undefined}", "name": "id", "type": "number | undefined", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The numeric stream identifier of this Http2Stream instance. Set to undefined\nif the stream identifier has not yet been assigned.

" }, { "textRaw": "Type: {boolean}", "name": "pending", "type": "boolean", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

Set to true if the Http2Stream instance has not yet been assigned a\nnumeric stream identifier.

" }, { "textRaw": "Type: {number}", "name": "rstCode", "type": "number", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" }, { "textRaw": "Type: {HTTP/2 Headers Object}", "name": "sentHeaders", "type": "HTTP/2 Headers Object", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound headers sent for this Http2Stream.

" }, { "textRaw": "Type: {HTTP/2 Headers Object[]}", "name": "sentInfoHeaders", "type": "HTTP/2 Headers Object[]", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An array of objects containing the outbound informational (additional) headers\nsent for this Http2Stream.

" }, { "textRaw": "Type: {HTTP/2 Headers Object}", "name": "sentTrailers", "type": "HTTP/2 Headers Object", "meta": { "added": [ "v9.5.0" ], "changes": [] }, "desc": "

An object containing the outbound trailers sent for this HttpStream.

" }, { "textRaw": "Type: {Http2Session}", "name": "session", "type": "Http2Session", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

A reference to the Http2Session instance that owns this Http2Stream. The\nvalue will be undefined after the Http2Stream instance is destroyed.

" }, { "textRaw": "Type: {Object}", "name": "state", "type": "Object", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58293", "description": "The `state.weight` property is now always set to 16 and `sumDependencyWeight` is always set to 0." }, { "version": [ "v24.2.0", "v22.17.0", "v20.19.6" ], "pr-url": "https://github.com/nodejs/node/pull/58313", "description": "Following the deprecation of priority signaling as of RFC 9113, `weight` and `sumDependencyWeight` options are deprecated." } ] }, "desc": "

Provides miscellaneous information about the current state of the\nHttp2Stream.

\n

A current state of this Http2Stream.

", "options": [ { "textRaw": "`localWindowSize` {number} The number of bytes the connected peer may send for this `Http2Stream` without receiving a `WINDOW_UPDATE`.", "name": "localWindowSize", "type": "number", "desc": "The number of bytes the connected peer may send for this `Http2Stream` without receiving a `WINDOW_UPDATE`." }, { "textRaw": "`state` {number} A flag indicating the low-level current state of the `Http2Stream` as determined by `nghttp2`.", "name": "state", "type": "number", "desc": "A flag indicating the low-level current state of the `Http2Stream` as determined by `nghttp2`." }, { "textRaw": "`localClose` {number} `1` if this `Http2Stream` has been closed locally.", "name": "localClose", "type": "number", "desc": "`1` if this `Http2Stream` has been closed locally." }, { "textRaw": "`remoteClose` {number} `1` if this `Http2Stream` has been closed remotely.", "name": "remoteClose", "type": "number", "desc": "`1` if this `Http2Stream` has been closed remotely." }, { "textRaw": "`sumDependencyWeight` {number} Legacy property, always set to `0`.", "name": "sumDependencyWeight", "type": "number", "desc": "Legacy property, always set to `0`." }, { "textRaw": "`weight` {number} Legacy property, always set to `16`.", "name": "weight", "type": "number", "desc": "Legacy property, always set to `16`." } ] } ], "methods": [ { "textRaw": "`http2stream.close(code[, callback])`", "name": "close", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`code` {number} Unsigned 32-bit integer identifying the error code. **Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).", "name": "code", "type": "number", "default": "`http2.constants.NGHTTP2_NO_ERROR` (`0x00`)", "desc": "Unsigned 32-bit integer identifying the error code." }, { "textRaw": "`callback` {Function} An optional function registered to listen for the `'close'` event.", "name": "callback", "type": "Function", "desc": "An optional function registered to listen for the `'close'` event.", "optional": true } ] } ], "desc": "

Closes the Http2Stream instance by sending an RST_STREAM frame to the\nconnected HTTP/2 peer.

" }, { "textRaw": "`http2stream.priority(options)`", "name": "priority", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58293", "description": "This method no longer sets the priority of the stream. Using it now triggers a runtime warning." } ], "deprecated": [ "v24.2.0", "v22.17.0", "v20.19.6" ] }, "stability": 0, "stabilityText": "Deprecated: support for priority signaling has been deprecated in the RFC 9113 and is no longer supported in Node.js.", "signatures": [ { "params": [ { "name": "options" } ] } ], "desc": "

Empty method, only there to maintain some backward compatibility.

" }, { "textRaw": "`http2stream.setTimeout(msecs, callback)`", "name": "setTimeout", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ] } ], "desc": "
import { connect, constants } from 'node:http2';\nconst client = connect('http://example.org:8000');\nconst { NGHTTP2_CANCEL } = 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
\n
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
" }, { "textRaw": "`http2stream.sendTrailers(headers)`", "name": "sendTrailers", "type": "method", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ] } ], "desc": "

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.

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
\n

The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header\nfields (e.g. ':method', ':path', etc).

" } ] }, { "textRaw": "Class: `ClientHttp2Stream`", "name": "ClientHttp2Stream", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'continue'`", "name": "continue", "type": "event", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [], "desc": "

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.

" }, { "textRaw": "Event: `'headers'`", "name": "headers", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`flags` {number}", "name": "flags", "type": "number" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers}", "name": "rawHeaders", "type": "HTTP/2 Raw Headers" } ], "desc": "

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, flags associated\nwith the headers, and the headers in raw format (see HTTP/2 Raw Headers).

\n
stream.on('headers', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'push'`", "name": "push", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`flags` {number}", "name": "flags", "type": "number" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers}", "name": "rawHeaders", "type": "HTTP/2 Raw Headers" } ], "desc": "

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, flags associated\nwith the headers, and the headers in raw format (see HTTP/2 Raw Headers).

\n
stream.on('push', (headers, flags) => {\n  console.log(headers);\n});\n
" }, { "textRaw": "Event: `'response'`", "name": "response", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`flags` {number}", "name": "flags", "type": "number" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers}", "name": "rawHeaders", "type": "HTTP/2 Raw Headers" } ], "desc": "

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 three arguments: an Object containing the received\nHTTP/2 Headers Object, flags associated with the headers, and the headers\nin raw format (see HTTP/2 Raw Headers).

\n
import { connect } from 'node:http2';\nconst client = connect('https://localhost');\nconst req = client.request({ ':path': '/' });\nreq.on('response', (headers, flags) => {\n  console.log(headers[':status']);\n});\n
\n
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
" } ] }, { "textRaw": "Class: `ServerHttp2Stream`", "name": "ServerHttp2Stream", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\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.

", "methods": [ { "textRaw": "`http2stream.additionalHeaders(headers)`", "name": "additionalHeaders", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" } ] } ], "desc": "

Sends an additional informational HEADERS frame to the connected HTTP/2 peer.

" }, { "textRaw": "`http2stream.pushStream(headers[, options], callback)`", "name": "pushStream", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`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`.", "name": "exclusive", "type": "boolean", "default": "`false`", "desc": "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." }, { "textRaw": "`parent` {number} Specifies the numeric identifier of a stream the newly created stream is dependent on.", "name": "parent", "type": "number", "desc": "Specifies the numeric identifier of a stream the newly created stream is dependent on." } ], "optional": true }, { "textRaw": "`callback` {Function} Callback that is called once the push stream has been initiated.", "name": "callback", "type": "Function", "desc": "Callback that is called once the push stream has been initiated.", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`pushStream` {ServerHttp2Stream} The returned `pushStream` object.", "name": "pushStream", "type": "ServerHttp2Stream", "desc": "The returned `pushStream` object." }, { "textRaw": "`headers` {HTTP/2 Headers Object} Headers object the `pushStream` was initiated with.", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "Headers object the `pushStream` was initiated with." } ] } ] } ], "desc": "

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.

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
\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.

\n

Calling http2stream.pushStream() from within a pushed stream is not permitted\nand will throw an error.

" }, { "textRaw": "`http2stream.respond([headers[, options]])`", "name": "respond", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": [ "v24.7.0", "v22.20.0" ], "pr-url": "https://github.com/nodejs/node/pull/59455", "description": "Allow passing headers in raw array format." }, { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33160", "description": "Allow explicitly setting date headers." } ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object | HTTP/2 Raw Headers}", "name": "headers", "type": "HTTP/2 Headers Object | HTTP/2 Raw Headers", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`endStream` {boolean} Set to `true` to indicate that the response will not include payload data.", "name": "endStream", "type": "boolean", "desc": "Set to `true` to indicate that the response will not include payload data." }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." } ], "optional": true } ] } ], "desc": "
import { createServer } from 'node:http2';\nconst server = createServer();\nserver.on('stream', (stream) => {\n  stream.respond({ ':status': 200 });\n  stream.end('some data');\n});\n
\n
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
\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 send trailing header fields to the peer.

\n

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.

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
" }, { "textRaw": "`http2stream.respondWithFD(fd[, headers[, options]])`", "name": "respondWithFD", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33160", "description": "Allow explicitly setting date headers." }, { "version": "v12.12.0", "pr-url": "https://github.com/nodejs/node/pull/29876", "description": "The `fd` option may now be a `FileHandle`." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18936", "description": "Any readable file descriptor, not necessarily for a regular file, is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {number | FileHandle} A readable file descriptor.", "name": "fd", "type": "number | FileHandle", "desc": "A readable file descriptor." }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`statCheck` {Function}", "name": "statCheck", "type": "Function" }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." }, { "textRaw": "`offset` {number} The offset position at which to begin reading.", "name": "offset", "type": "number", "desc": "The offset position at which to begin reading." }, { "textRaw": "`length` {number} The amount of data from the fd to send.", "name": "length", "type": "number", "desc": "The amount of data from the fd to send." } ], "optional": true } ] } ], "desc": "

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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\n
import { createServer } from 'node:http2';\nimport { openSync, fstatSync, closeSync } from 'node:fs';\n\nconst server = createServer();\nserver.on('stream', (stream) => {\n  const fd = openSync('/some/file', 'r');\n\n  const stat = 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', () => closeSync(fd));\n});\n
\n
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
\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.

\n

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.

\n

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.

\n

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 send trailing\nheader fields to the peer.

\n

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.

\n
import { createServer } from 'node:http2';\nimport { openSync, fstatSync, closeSync } from 'node:fs';\n\nconst server = createServer();\nserver.on('stream', (stream) => {\n  const fd = openSync('/some/file', 'r');\n\n  const stat = 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', () => closeSync(fd));\n});\n
\n
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
" }, { "textRaw": "`http2stream.respondWithFile(path[, headers[, options]])`", "name": "respondWithFile", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33160", "description": "Allow explicitly setting date headers." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18936", "description": "Any readable file, not necessarily a regular file, is supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string | Buffer | URL}", "name": "path", "type": "string | Buffer | URL" }, { "textRaw": "`headers` {HTTP/2 Headers Object}", "name": "headers", "type": "HTTP/2 Headers Object", "optional": true }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`statCheck` {Function}", "name": "statCheck", "type": "Function" }, { "textRaw": "`onError` {Function} Callback function invoked in the case of an error before send.", "name": "onError", "type": "Function", "desc": "Callback function invoked in the case of an error before send." }, { "textRaw": "`waitForTrailers` {boolean} When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent.", "name": "waitForTrailers", "type": "boolean", "desc": "When `true`, the `Http2Stream` will emit the `'wantTrailers'` event after the final `DATA` frame has been sent." }, { "textRaw": "`offset` {number} The offset position at which to begin reading.", "name": "offset", "type": "number", "desc": "The offset position at which to begin reading." }, { "textRaw": "`length` {number} The amount of data from the fd to send.", "name": "length", "type": "number", "desc": "The amount of data from the fd to send." } ], "optional": true } ] } ], "desc": "

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.

\n

When used, the Http2Stream object's Duplex interface will be closed\nautomatically.

\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 file:

\n

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.

\n

Example using a file path:

\n
import { createServer } from 'node:http2';\nconst server = 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.error(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
\n
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.error(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
\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:

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
\n

The content-length header field will be automatically set.

\n

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.

\n

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.

\n

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 send trailing\nheader fields to the peer.

\n

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.

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
" } ], "properties": [ { "textRaw": "Type: {boolean}", "name": "headersSent", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" }, { "textRaw": "Type: {boolean}", "name": "pushAllowed", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

" } ] }, { "textRaw": "Class: `Http2Server`", "name": "Http2Server", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2Server are created using the http2.createServer()\nfunction. The Http2Server class is not exported directly by the\nnode:http2 module.

", "events": [ { "textRaw": "Event: `'checkContinue'`", "name": "checkContinue", "type": "event", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'connection'`", "name": "connection", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'request'`", "name": "request", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: `'session'`", "name": "session", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2Server.

" }, { "textRaw": "Event: `'sessionError'`", "name": "sessionError", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" }, { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2Server.

" }, { "textRaw": "Event: `'stream'`", "name": "stream", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`stream` {Http2Stream} A reference to the stream", "name": "stream", "type": "Http2Stream", "desc": "A reference to the stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers} An array containing the raw headers", "name": "rawHeaders", "type": "HTTP/2 Raw Headers", "desc": "An array containing the raw headers" } ], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n

See also Http2Session's 'stream' event.

\n
import { createServer, constants } from 'node:http2';\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE,\n} = constants;\n\nconst server = 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
\n
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
" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27558", "description": "The default timeout changed from 120s to 0 (no timeout)." } ] }, "params": [], "desc": "

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)

" } ], "methods": [ { "textRaw": "`server.close([callback])`", "name": "close", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Stops the server from establishing new sessions and streams.

\n

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.

" }, { "textRaw": "`server[Symbol.asyncDispose]()`", "name": "[Symbol.asyncDispose]", "type": "method", "meta": { "added": [ "v20.4.0" ], "changes": [ { "version": "v24.2.0", "pr-url": "https://github.com/nodejs/node/pull/58467", "description": "No longer experimental." } ] }, "signatures": [ { "params": [] } ], "desc": "

Calls server.close() and returns a promise that fulfills when the\nserver has closed.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "name": "setTimeout", "type": "method", "meta": { "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`." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27558", "description": "The default timeout changed from 120s to 0 (no timeout)." } ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} **Default:** 0 (no timeout)", "name": "msecs", "type": "number", "default": "0 (no timeout)", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" } } ], "desc": "

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.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case if callback is not a function, a new ERR_INVALID_ARG_TYPE\nerror will be thrown.

" }, { "textRaw": "`server.updateSettings([settings])`", "name": "updateSettings", "type": "method", "meta": { "added": [ "v15.1.0", "v14.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object", "optional": true } ] } ], "desc": "

Used to update the server with the provided settings.

\n

Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.

\n

Throws ERR_INVALID_ARG_TYPE for invalid settings argument.

" } ], "properties": [ { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** 0 (no timeout)", "name": "timeout", "type": "number", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27558", "description": "The default timeout changed from 120s to 0 (no timeout)." } ] }, "default": "0 (no timeout)", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

A value of 0 will disable the timeout behavior on incoming connections.

\n

The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

", "shortDesc": "Timeout in milliseconds." } ] }, { "textRaw": "Class: `Http2SecureServer`", "name": "Http2SecureServer", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

Instances of Http2SecureServer are created using the\nhttp2.createSecureServer() function. The Http2SecureServer class is not\nexported directly by the node:http2 module.

", "events": [ { "textRaw": "Event: `'checkContinue'`", "name": "checkContinue", "type": "event", "meta": { "added": [ "v8.5.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

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.

\n

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.

\n

When this event is emitted and handled, the 'request' event will\nnot be emitted.

" }, { "textRaw": "Event: `'connection'`", "name": "connection", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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.

\n

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.

" }, { "textRaw": "Event: `'request'`", "name": "request", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http2.Http2ServerRequest}", "name": "request", "type": "http2.Http2ServerRequest" }, { "textRaw": "`response` {http2.Http2ServerResponse}", "name": "response", "type": "http2.Http2ServerResponse" } ], "desc": "

Emitted each time there is a request. There may be multiple requests\nper session. See the Compatibility API.

" }, { "textRaw": "Event: `'session'`", "name": "session", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "

The 'session' event is emitted when a new Http2Session is created by the\nHttp2SecureServer.

" }, { "textRaw": "Event: `'sessionError'`", "name": "sessionError", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error" }, { "textRaw": "`session` {ServerHttp2Session}", "name": "session", "type": "ServerHttp2Session" } ], "desc": "

The 'sessionError' event is emitted when an 'error' event is emitted by\nan Http2Session object associated with the Http2SecureServer.

" }, { "textRaw": "Event: `'stream'`", "name": "stream", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [ { "textRaw": "`stream` {Http2Stream} A reference to the stream", "name": "stream", "type": "Http2Stream", "desc": "A reference to the stream" }, { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`flags` {number} The associated numeric flags", "name": "flags", "type": "number", "desc": "The associated numeric flags" }, { "textRaw": "`rawHeaders` {HTTP/2 Raw Headers} An array containing the raw headers", "name": "rawHeaders", "type": "HTTP/2 Raw Headers", "desc": "An array containing the raw headers" } ], "desc": "

The 'stream' event is emitted when a 'stream' event has been emitted by\nan Http2Session associated with the server.

\n

See also Http2Session's 'stream' event.

\n
import { createSecureServer, constants } from 'node:http2';\nconst {\n  HTTP2_HEADER_METHOD,\n  HTTP2_HEADER_PATH,\n  HTTP2_HEADER_STATUS,\n  HTTP2_HEADER_CONTENT_TYPE,\n} = constants;\n\nconst options = getOptionsSomehow();\n\nconst server = 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
\n
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
" }, { "textRaw": "Event: `'timeout'`", "name": "timeout", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27558", "description": "The default timeout changed from 120s to 0 (no timeout)." } ] }, "params": [], "desc": "

The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2secureServer.setTimeout().\nDefault: 0 (no timeout)

" }, { "textRaw": "Event: `'unknownProtocol'`", "name": "unknownProtocol", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v19.0.0", "pr-url": "https://github.com/nodejs/node/pull/44031", "description": "This event will only be emitted if the client did not transmit an ALPN extension during the TLS handshake." } ] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "

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().

\n

In earlier versions of Node.js, this event would be emitted if allowHTTP1 is\nfalse and, during the TLS handshake, the client either does not send an ALPN\nextension or sends an ALPN extension that does not include HTTP/2 (h2). Newer\nversions of Node.js only emit this event if allowHTTP1 is false and the\nclient does not send an ALPN extension. If the client sends an ALPN extension\nthat does not include HTTP/2 (or HTTP/1.1 if allowHTTP1 is true), the TLS\nhandshake will fail and no secure connection will be established.

\n

See the Compatibility API.

" } ], "methods": [ { "textRaw": "`server.close([callback])`", "name": "close", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ] } ], "desc": "

Stops the server from establishing new sessions and streams.

\n

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.

" }, { "textRaw": "`server.setTimeout([msecs][, callback])`", "name": "setTimeout", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number} **Default:** `120000` (2 minutes)", "name": "msecs", "type": "number", "default": "`120000` (2 minutes)", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {Http2SecureServer}", "name": "return", "type": "Http2SecureServer" } } ], "desc": "

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.

\n

The given callback is registered as a listener on the 'timeout' event.

\n

In case if callback is not a function, a new ERR_INVALID_ARG_TYPE\nerror will be thrown.

" }, { "textRaw": "`server.updateSettings([settings])`", "name": "updateSettings", "type": "method", "meta": { "added": [ "v15.1.0", "v14.17.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object", "optional": true } ] } ], "desc": "

Used to update the server with the provided settings.

\n

Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.

\n

Throws ERR_INVALID_ARG_TYPE for invalid settings argument.

" } ], "properties": [ { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** 0 (no timeout)", "name": "timeout", "type": "number", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/27558", "description": "The default timeout changed from 120s to 0 (no timeout)." } ] }, "default": "0 (no timeout)", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.

\n

A value of 0 will disable the timeout behavior on incoming connections.

\n

The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.

", "shortDesc": "Timeout in milliseconds." } ] } ], "methods": [ { "textRaw": "`http2.createServer([options][, onRequestHandler])`", "name": "createServer", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/59917", "description": "Added the `strictSingleValueFields` option." }, { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/61713", "description": "Added `http1Options` option. The `Http1IncomingMessage` and `Http1ServerResponse` options are now deprecated." }, { "version": [ "v23.0.0", "v22.10.0" ], "pr-url": "https://github.com/nodejs/node/pull/54875", "description": "Added `streamResetBurst` and `streamResetRate`." }, { "version": [ "v15.10.0", "v14.16.0", "v12.21.0", "v10.24.0" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/246", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": [ "v14.4.0", "v12.18.0", "v10.21.0" ], "commit": "3948830ce6408be620b09a70bf66158623022af0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionRejectedStreams` option with a default of 100." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionInvalidFrames` option with a default of 1000." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29144", "description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed." }, { "version": "v12.4.0", "pr-url": "https://github.com/nodejs/node/pull/27782", "description": "The `options` parameter now supports `net.createServer()` options." }, { "version": "v9.6.0", "pr-url": "https://github.com/nodejs/node/pull/15752", "description": "Added the `Http1IncomingMessage` and `Http1ServerResponse` option." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." }, { "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. While this sets the maximum allowed size to the entire block of headers, `nghttp2` (the internal http2 library) has a limit of `65536` for each decompressed key/value pair.", "name": "maxSendHeaderBlockLength", "type": "number", "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed. While this sets the maximum allowed size to the entire block of headers, `nghttp2` (the internal http2 library) has a limit of `65536` for each decompressed key/value pair." }, { "textRaw": "`paddingStrategy` {number} The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "The strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "options": [ { "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.", "name": "http2.constants.PADDING_STRATEGY_NONE", "desc": "No padding is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.", "name": "http2.constants.PADDING_STRATEGY_MAX", "desc": "The maximum amount of padding, determined by the internal implementation, is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.", "name": "http2.constants.PADDING_STRATEGY_ALIGNED", "desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes." } ] }, { "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", "name": "peerMaxConcurrentStreams", "type": "number", "default": "`100`", "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." }, { "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", "name": "maxSessionInvalidFrames", "type": "integer", "default": "`1000`", "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." }, { "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", "name": "maxSessionRejectedStreams", "type": "integer", "default": "`100`", "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." }, { "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The initial settings to send to the remote peer upon connection." }, { "textRaw": "`streamResetBurst` {number} and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively.", "name": "streamResetBurst", "type": "number", "desc": "and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively." }, { "textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.", "name": "remoteCustomSettings", "type": "Array", "desc": "The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types." }, { "textRaw": "`Http1IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`. **Deprecated.** Use `http1Options.IncomingMessage` instead. See DEP0202.", "name": "Http1IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`. **Deprecated.** Use `http1Options.IncomingMessage` instead. See DEP0202", "desc": "Specifies the `IncomingMessage` class to used for HTTP/1 fallback. Useful for extending the original `http.IncomingMessage`." }, { "textRaw": "`Http1ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`. **Default:** `http.ServerResponse`. **Deprecated.** Use `http1Options.ServerResponse` instead. See DEP0202.", "name": "Http1ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`. **Deprecated.** Use `http1Options.ServerResponse` instead. See DEP0202", "desc": "Specifies the `ServerResponse` class to used for HTTP/1 fallback. Useful for extending the original `http.ServerResponse`." }, { "textRaw": "`http1Options` {Object} An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "name": "http1Options", "type": "Object", "desc": "An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "options": [ { "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to use for HTTP/1 fallback. **Default:** `http.IncomingMessage`.", "name": "IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`", "desc": "Specifies the `IncomingMessage` class to use for HTTP/1 fallback." }, { "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to use for HTTP/1 fallback. **Default:** `http.ServerResponse`.", "name": "ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`", "desc": "Specifies the `ServerResponse` class to use for HTTP/1 fallback." }, { "textRaw": "`keepAliveTimeout` {number} The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. **Default:** `5000`.", "name": "keepAliveTimeout", "type": "number", "default": "`5000`", "desc": "The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed." } ] }, { "textRaw": "`Http2ServerRequest` {http2.Http2ServerRequest} Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`. **Default:** `Http2ServerRequest`.", "name": "Http2ServerRequest", "type": "http2.Http2ServerRequest", "default": "`Http2ServerRequest`", "desc": "Specifies the `Http2ServerRequest` class to use. Useful for extending the original `Http2ServerRequest`." }, { "textRaw": "`Http2ServerResponse` {http2.Http2ServerResponse} Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`. **Default:** `Http2ServerResponse`.", "name": "Http2ServerResponse", "type": "http2.Http2ServerResponse", "default": "`Http2ServerResponse`", "desc": "Specifies the `Http2ServerResponse` class to use. Useful for extending the original `Http2ServerResponse`." }, { "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` is emitted. If the socket has not been destroyed by that time the server will destroy it." }, { "textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.", "name": "strictFieldWhitespaceValidation", "type": "boolean", "default": "`true`", "desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113." }, { "textRaw": "`strictSingleValueFields` {boolean} If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided. **Default:** `true`.", "name": "strictSingleValueFields", "type": "boolean", "default": "`true`", "desc": "If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided." }, { "textRaw": "`...options` {Object} Any `net.createServer()` option can be provided.", "name": "...options", "type": "Object", "desc": "Any `net.createServer()` option can be provided." } ], "optional": true }, { "textRaw": "`onRequestHandler` {Function} See Compatibility API", "name": "onRequestHandler", "type": "Function", "desc": "See Compatibility API", "optional": true } ], "return": { "textRaw": "Returns: {Http2Server}", "name": "return", "type": "Http2Server" } } ], "desc": "

Returns a net.Server instance that creates and manages Http2Session\ninstances.

\n

Since there are no browsers known that support\nunencrypted HTTP/2, the use of\nhttp2.createSecureServer() is necessary when communicating\nwith browser clients.

\n
import { createServer } from '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 `createSecureServer()`\n// is necessary when communicating with browser clients.\nconst server = 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(8000);\n
\n
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(8000);\n
" }, { "textRaw": "`http2.createSecureServer(options[, onRequestHandler])`", "name": "createSecureServer", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/59917", "description": "Added the `strictSingleValueFields` option." }, { "version": "v25.7.0", "pr-url": "https://github.com/nodejs/node/pull/61713", "description": "Added `http1Options` option." }, { "version": [ "v15.10.0", "v14.16.0", "v12.21.0", "v10.24.0" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/246", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": [ "v14.4.0", "v12.18.0", "v10.21.0" ], "commit": "3948830ce6408be620b09a70bf66158623022af0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionRejectedStreams` option with a default of 100." }, { "version": [ "v13.3.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/30534", "description": "Added `maxSessionInvalidFrames` option with a default of 1000." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29144", "description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed." }, { "version": "v10.12.0", "pr-url": "https://github.com/nodejs/node/pull/22956", "description": "Added the `origins` option to automatically send an `ORIGIN` frame on `Http2Session` startup." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the `'unknownProtocol'` event. See ALPN negotiation. **Default:** `false`.", "name": "allowHTTP1", "type": "boolean", "default": "`false`", "desc": "Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. See the `'unknownProtocol'` event. See ALPN negotiation." }, { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." }, { "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `4`." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", "name": "maxSendHeaderBlockLength", "type": "number", "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." }, { "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "options": [ { "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.", "name": "http2.constants.PADDING_STRATEGY_NONE", "desc": "No padding is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.", "name": "http2.constants.PADDING_STRATEGY_MAX", "desc": "The maximum amount of padding, determined by the internal implementation, is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.", "name": "http2.constants.PADDING_STRATEGY_ALIGNED", "desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes." } ] }, { "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", "name": "peerMaxConcurrentStreams", "type": "number", "default": "`100`", "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." }, { "textRaw": "`maxSessionInvalidFrames` {integer} Sets the maximum number of invalid frames that will be tolerated before the session is closed. **Default:** `1000`.", "name": "maxSessionInvalidFrames", "type": "integer", "default": "`1000`", "desc": "Sets the maximum number of invalid frames that will be tolerated before the session is closed." }, { "textRaw": "`maxSessionRejectedStreams` {integer} Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer. **Default:** `100`.", "name": "maxSessionRejectedStreams", "type": "integer", "default": "`100`", "desc": "Sets the maximum number of rejected upon creation streams that will be tolerated before the session is closed. Each rejection is associated with an `NGHTTP2_ENHANCE_YOUR_CALM` error that should tell the peer to not open any more streams, continuing to open streams is therefore regarded as a sign of a misbehaving peer." }, { "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The initial settings to send to the remote peer upon connection." }, { "textRaw": "`streamResetBurst` {number} and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively.", "name": "streamResetBurst", "type": "number", "desc": "and `streamResetRate` {number} Sets the rate limit for the incoming stream reset (RST_STREAM frame). Both settings must be set to have any effect, and default to 1000 and 33 respectively." }, { "textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `customSettings`-property of the received remoteSettings. Please see the `customSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.", "name": "remoteCustomSettings", "type": "Array", "desc": "The array of integer values determines the settings types, which are included in the `customSettings`-property of the received remoteSettings. Please see the `customSettings`-property of the `Http2Settings` object for more information, on the allowed setting types." }, { "textRaw": "`...options` {Object} Any `tls.createServer()` options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required.", "name": "...options", "type": "Object", "desc": "Any `tls.createServer()` options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." }, { "textRaw": "`origins` {string[]} An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`.", "name": "origins", "type": "string[]", "desc": "An array of origin strings to send within an `ORIGIN` frame immediately following creation of a new server `Http2Session`." }, { "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it." }, { "textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.", "name": "strictFieldWhitespaceValidation", "type": "boolean", "default": "`true`", "desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113." }, { "textRaw": "`strictSingleValueFields` {boolean} If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided. **Default:** `true`.", "name": "strictSingleValueFields", "type": "boolean", "default": "`true`", "desc": "If `true`, strict validation is used for headers and trailers defined as having only a single value, such that an error is thrown if multiple values are provided." }, { "textRaw": "`http1Options` {Object} An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "name": "http1Options", "type": "Object", "desc": "An options object for configuring the HTTP/1 fallback when `allowHTTP1` is `true`. These options are passed to the underlying HTTP/1 server. See `http.createServer()` for available options. Among others, the following are supported:", "options": [ { "textRaw": "`IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` class to use for HTTP/1 fallback. **Default:** `http.IncomingMessage`.", "name": "IncomingMessage", "type": "http.IncomingMessage", "default": "`http.IncomingMessage`", "desc": "Specifies the `IncomingMessage` class to use for HTTP/1 fallback." }, { "textRaw": "`ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class to use for HTTP/1 fallback. **Default:** `http.ServerResponse`.", "name": "ServerResponse", "type": "http.ServerResponse", "default": "`http.ServerResponse`", "desc": "Specifies the `ServerResponse` class to use for HTTP/1 fallback." }, { "textRaw": "`keepAliveTimeout` {number} The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. **Default:** `5000`.", "name": "keepAliveTimeout", "type": "number", "default": "`5000`", "desc": "The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed." } ] } ] }, { "textRaw": "`onRequestHandler` {Function} See Compatibility API", "name": "onRequestHandler", "type": "Function", "desc": "See Compatibility API", "optional": true } ], "return": { "textRaw": "Returns: {Http2SecureServer}", "name": "return", "type": "Http2SecureServer" } } ], "desc": "

Returns a tls.Server instance that creates and manages Http2Session\ninstances.

\n
import { createSecureServer } from 'node:http2';\nimport { readFileSync } from 'node:fs';\n\nconst options = {\n  key: readFileSync('server-key.pem'),\n  cert: readFileSync('server-cert.pem'),\n};\n\n// Create a secure HTTP/2 server\nconst server = 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(8443);\n
\n
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(8443);\n
" }, { "textRaw": "`http2.connect(authority[, options][, listener])`", "name": "connect", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": [ "v15.10.0", "v14.16.0", "v12.21.0", "v10.24.0" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/246", "description": "Added `unknownProtocolTimeout` option with a default of 10000." }, { "version": [ "v14.4.0", "v12.18.0", "v10.21.0" ], "commit": "3948830ce6408be620b09a70bf66158623022af0", "pr-url": "https://github.com/nodejs-private/node-private/pull/204", "description": "Added `maxSettings` option with a default of 32." }, { "version": "v13.0.0", "pr-url": "https://github.com/nodejs/node/pull/29144", "description": "The `PADDING_STRATEGY_CALLBACK` has been made equivalent to providing `PADDING_STRATEGY_ALIGNED` and `selectPadding` has been removed." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/17105", "description": "Added the `maxOutstandingPings` option with a default limit of 10." }, { "version": "v8.9.3", "pr-url": "https://github.com/nodejs/node/pull/16676", "description": "Added the `maxHeaderListPairs` option with a default limit of 128 header pairs." } ] }, "signatures": [ { "params": [ { "textRaw": "`authority` {string | URL} The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored.", "name": "authority", "type": "string | URL", "desc": "The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. **Default:** `4Kib`.", "name": "maxDeflateDynamicTableSize", "type": "number", "default": "`4Kib`", "desc": "Sets the maximum dynamic table size for deflating header fields." }, { "textRaw": "`maxSettings` {number} Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`. **Default:** `32`.", "name": "maxSettings", "type": "number", "default": "`32`", "desc": "Sets the maximum number of settings entries per `SETTINGS` frame. The minimum value allowed is `1`." }, { "textRaw": "`maxSessionMemory`{number} Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit. **Default:** `10`.", "name": "maxSessionMemory", "type": "number", "default": "`10`", "desc": "Sets the maximum memory that the `Http2Session` is permitted to use. The value is expressed in terms of number of megabytes, e.g. `1` equal 1 megabyte. The minimum value allowed is `1`. This is a credit based limit, existing `Http2Stream`s may cause this limit to be exceeded, but new `Http2Stream` instances will be rejected while this limit is exceeded. The current number of `Http2Stream` sessions, the current memory use of the header compression tables, header blocks retained by open streams, current data queued to be sent, and unacknowledged `PING` and `SETTINGS` frames are all counted towards the current limit." }, { "textRaw": "`maxHeaderListPairs` {number} Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `1`. **Default:** `128`.", "name": "maxHeaderListPairs", "type": "number", "default": "`128`", "desc": "Sets the maximum number of header entries. This is similar to `server.maxHeadersCount` or `request.maxHeadersCount` in the `node:http` module. The minimum value is `1`." }, { "textRaw": "`maxOriginSetSize` {number} Sets the maximum number of uniq origin the sever can send via ORIGIN frames. **Default:** `128`.", "name": "maxOriginSetSize", "type": "number", "default": "`128`", "desc": "Sets the maximum number of uniq origin the sever can send via ORIGIN frames." }, { "textRaw": "`maxOutstandingPings` {number} Sets the maximum number of outstanding, unacknowledged pings. **Default:** `10`.", "name": "maxOutstandingPings", "type": "number", "default": "`10`", "desc": "Sets the maximum number of outstanding, unacknowledged pings." }, { "textRaw": "`maxReservedRemoteStreams` {number} Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value. **Default:** `200`.", "name": "maxReservedRemoteStreams", "type": "number", "default": "`200`", "desc": "Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected. The minimum allowed value is 0. The maximum allowed value is 232-1. A negative value sets this option to the maximum allowed value." }, { "textRaw": "`maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed.", "name": "maxSendHeaderBlockLength", "type": "number", "desc": "Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a `'frameError'` event being emitted and the stream being closed and destroyed." }, { "textRaw": "`paddingStrategy` {number} Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames. **Default:** `http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "name": "paddingStrategy", "type": "number", "default": "`http2.constants.PADDING_STRATEGY_NONE`. Value may be one of:", "desc": "Strategy used for determining the amount of padding to use for `HEADERS` and `DATA` frames.", "options": [ { "textRaw": "`http2.constants.PADDING_STRATEGY_NONE`: No padding is applied.", "name": "http2.constants.PADDING_STRATEGY_NONE", "desc": "No padding is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_MAX`: The maximum amount of padding, determined by the internal implementation, is applied.", "name": "http2.constants.PADDING_STRATEGY_MAX", "desc": "The maximum amount of padding, determined by the internal implementation, is applied." }, { "textRaw": "`http2.constants.PADDING_STRATEGY_ALIGNED`: Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes.", "name": "http2.constants.PADDING_STRATEGY_ALIGNED", "desc": "Attempts to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum is used and the total frame length is not necessarily aligned at 8 bytes." } ] }, { "textRaw": "`peerMaxConcurrentStreams` {number} Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`. **Default:** `100`.", "name": "peerMaxConcurrentStreams", "type": "number", "default": "`100`", "desc": "Sets the maximum number of concurrent streams for the remote peer as if a `SETTINGS` frame had been received. Will be overridden if the remote peer sets its own value for `maxConcurrentStreams`." }, { "textRaw": "`protocol` {string} The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`. **Default:** `'https:'`", "name": "protocol", "type": "string", "default": "`'https:'`", "desc": "The protocol to connect with, if not set in the `authority`. Value may be either `'http:'` or `'https:'`." }, { "textRaw": "`settings` {HTTP/2 Settings Object} The initial settings to send to the remote peer upon connection.", "name": "settings", "type": "HTTP/2 Settings Object", "desc": "The initial settings to send to the remote peer upon connection." }, { "textRaw": "`remoteCustomSettings` {Array} The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types.", "name": "remoteCustomSettings", "type": "Array", "desc": "The array of integer values determines the settings types, which are included in the `CustomSettings`-property of the received remoteSettings. Please see the `CustomSettings`-property of the `Http2Settings` object for more information, on the allowed setting types." }, { "textRaw": "`createConnection` {Function} An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any `Duplex` stream that is to be used as the connection for this session.", "name": "createConnection", "type": "Function", "desc": "An optional callback that receives the `URL` instance passed to `connect` and the `options` object, and returns any `Duplex` stream that is to be used as the connection for this session." }, { "textRaw": "`...options` {Object} Any `net.connect()` or `tls.connect()` options can be provided.", "name": "...options", "type": "Object", "desc": "Any `net.connect()` or `tls.connect()` options can be provided." }, { "textRaw": "`unknownProtocolTimeout` {number} Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it. **Default:** `10000`.", "name": "unknownProtocolTimeout", "type": "number", "default": "`10000`", "desc": "Specifies a timeout in milliseconds that a server should wait when an `'unknownProtocol'` event is emitted. If the socket has not been destroyed by that time the server will destroy it." }, { "textRaw": "`strictFieldWhitespaceValidation` {boolean} If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113. **Default:** `true`.", "name": "strictFieldWhitespaceValidation", "type": "boolean", "default": "`true`", "desc": "If `true`, it turns on strict leading and trailing whitespace validation for HTTP/2 header field names and values as per RFC-9113." } ], "optional": true }, { "textRaw": "`listener` {Function} Will be registered as a one-time listener of the `'connect'` event.", "name": "listener", "type": "Function", "desc": "Will be registered as a one-time listener of the `'connect'` event.", "optional": true } ], "return": { "textRaw": "Returns: {ClientHttp2Session}", "name": "return", "type": "ClientHttp2Session" } } ], "desc": "

Returns a ClientHttp2Session instance.

\n
import { connect } from 'node:http2';\nconst client = connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
\n
const http2 = require('node:http2');\nconst client = http2.connect('https://localhost:1234');\n\n/* Use the client */\n\nclient.close();\n
" }, { "textRaw": "`http2.getDefaultSettings()`", "name": "getDefaultSettings", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {HTTP/2 Settings Object}", "name": "return", "type": "HTTP/2 Settings Object" } } ], "desc": "

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.

" }, { "textRaw": "`http2.getPackedSettings([settings])`", "name": "getPackedSettings", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`settings` {HTTP/2 Settings Object}", "name": "settings", "type": "HTTP/2 Settings Object", "optional": true } ], "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" } } ], "desc": "

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.

\n
import { getPackedSettings } from 'node:http2';\n\nconst packed = getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
\n
const http2 = require('node:http2');\n\nconst packed = http2.getPackedSettings({ enablePush: false });\n\nconsole.log(packed.toString('base64'));\n// Prints: AAIAAAAA\n
" }, { "textRaw": "`http2.getUnpackedSettings(buf)`", "name": "getUnpackedSettings", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`buf` {Buffer | TypedArray} The packed settings.", "name": "buf", "type": "Buffer | TypedArray", "desc": "The packed settings." } ], "return": { "textRaw": "Returns: {HTTP/2 Settings Object}", "name": "return", "type": "HTTP/2 Settings Object" } } ], "desc": "

Returns a HTTP/2 Settings Object containing the deserialized settings from\nthe given Buffer as generated by http2.getPackedSettings().

" }, { "textRaw": "`http2.performServerHandshake(socket[, options])`", "name": "performServerHandshake", "type": "method", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" }, { "textRaw": "`options` {Object} Any `http2.createServer()` option can be provided.", "name": "options", "type": "Object", "desc": "Any `http2.createServer()` option can be provided.", "optional": true } ], "return": { "textRaw": "Returns: {ServerHttp2Session}", "name": "return", "type": "ServerHttp2Session" } } ], "desc": "

Create an HTTP/2 server session from an existing socket.

" } ], "properties": [ { "textRaw": "`http2.constants`", "name": "constants", "type": "property", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "modules": [ { "textRaw": "Header name constants", "name": "header_name_constants", "type": "module", "desc": "

The HTTP2_HEADER_* constants provide names for HTTP/2 pseudo-headers and\nknown HTTP header names. Using these string constants is optional. For example,\nhttp2.constants.HTTP2_HEADER_CONTENT_TYPE is equal to 'content-type'.\nFor APIs that accept regular header names,\nhttp2.constants.HTTP2_HEADER_CONTENT_TYPE, 'content-type', and\n'Content-Type' have the same effect; Node.js serializes the name in\nlower-case.

\n

Regular header constants can be used with the compatibility API wherever the\ncorresponding literal header name is accepted. In compatibility API request\nhandlers, prefer request.method, request.authority, request.scheme, and\nrequest.url for the corresponding pseudo-headers. Other incoming\npseudo-headers remain available through request.headers. Set response status\nthrough response.statusCode or the statusCode argument to\nresponse.writeHead(). Passing HTTP2_HEADER_STATUS (':status') to\nresponse.setHeader() or in response.writeHead()'s headers object throws\nERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED. HTTP2_HEADER_PROTOCOL is a request\npseudo-header and cannot be sent in a response.

\n

Incoming header object keys are lower-case, so use a constant or a lower-case\nliteral when accessing them as object properties. Using a constant does not\nchange header validation, and the availability of a constant does not imply\nthat the header is valid in every HTTP/2 context. See HTTP/2 Headers Object\nand Invalid character handling in header names and values for details about\nheader casing and validation.

", "modules": [ { "textRaw": "Pseudo-header constants", "name": "pseudo-header_constants", "type": "module", "desc": "

HTTP2_HEADER_METHOD, HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_SCHEME, and\nHTTP2_HEADER_PATH identify request pseudo-headers. HTTP2_HEADER_STATUS\nidentifies the response pseudo-header. HTTP2_HEADER_PROTOCOL identifies the\nextended CONNECT request pseudo-header. Pseudo-headers are not permitted in\ntrailers.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ConstantValue
http2.constants.HTTP2_HEADER_STATUS':status'
http2.constants.HTTP2_HEADER_METHOD':method'
http2.constants.HTTP2_HEADER_AUTHORITY':authority'
http2.constants.HTTP2_HEADER_SCHEME':scheme'
http2.constants.HTTP2_HEADER_PATH':path'
http2.constants.HTTP2_HEADER_PROTOCOL':protocol'
", "displayName": "Pseudo-header constants" }, { "textRaw": "Regular header constants", "name": "regular_header_constants", "type": "module", "desc": "

The HTTP2_HEADER_CONNECTION, HTTP2_HEADER_UPGRADE,\nHTTP2_HEADER_HTTP2_SETTINGS, HTTP2_HEADER_KEEP_ALIVE,\nHTTP2_HEADER_PROXY_CONNECTION, and HTTP2_HEADER_TRANSFER_ENCODING\nconstants identify connection-specific headers that HTTP/2 does not permit.\nHTTP2_HEADER_TE is permitted only when its value is 'trailers'.

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ConstantValue
http2.constants.HTTP2_HEADER_ACCEPT_ENCODING'accept-encoding'
http2.constants.HTTP2_HEADER_ACCEPT_LANGUAGE'accept-language'
http2.constants.HTTP2_HEADER_ACCEPT_RANGES'accept-ranges'
http2.constants.HTTP2_HEADER_ACCEPT'accept'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS'access-control-allow-credentials'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS'access-control-allow-headers'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS'access-control-allow-methods'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN'access-control-allow-origin'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS'access-control-expose-headers'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS'access-control-request-headers'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD'access-control-request-method'
http2.constants.HTTP2_HEADER_AGE'age'
http2.constants.HTTP2_HEADER_AUTHORIZATION'authorization'
http2.constants.HTTP2_HEADER_CACHE_CONTROL'cache-control'
http2.constants.HTTP2_HEADER_CONNECTION'connection'
http2.constants.HTTP2_HEADER_CONTENT_DISPOSITION'content-disposition'
http2.constants.HTTP2_HEADER_CONTENT_ENCODING'content-encoding'
http2.constants.HTTP2_HEADER_CONTENT_LENGTH'content-length'
http2.constants.HTTP2_HEADER_CONTENT_TYPE'content-type'
http2.constants.HTTP2_HEADER_COOKIE'cookie'
http2.constants.HTTP2_HEADER_DATE'date'
http2.constants.HTTP2_HEADER_ETAG'etag'
http2.constants.HTTP2_HEADER_FORWARDED'forwarded'
http2.constants.HTTP2_HEADER_HOST'host'
http2.constants.HTTP2_HEADER_IF_MODIFIED_SINCE'if-modified-since'
http2.constants.HTTP2_HEADER_IF_NONE_MATCH'if-none-match'
http2.constants.HTTP2_HEADER_IF_RANGE'if-range'
http2.constants.HTTP2_HEADER_LAST_MODIFIED'last-modified'
http2.constants.HTTP2_HEADER_LINK'link'
http2.constants.HTTP2_HEADER_LOCATION'location'
http2.constants.HTTP2_HEADER_RANGE'range'
http2.constants.HTTP2_HEADER_REFERER'referer'
http2.constants.HTTP2_HEADER_SERVER'server'
http2.constants.HTTP2_HEADER_SET_COOKIE'set-cookie'
http2.constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY'strict-transport-security'
http2.constants.HTTP2_HEADER_TRANSFER_ENCODING'transfer-encoding'
http2.constants.HTTP2_HEADER_TE'te'
http2.constants.HTTP2_HEADER_UPGRADE_INSECURE_REQUESTS'upgrade-insecure-requests'
http2.constants.HTTP2_HEADER_UPGRADE'upgrade'
http2.constants.HTTP2_HEADER_USER_AGENT'user-agent'
http2.constants.HTTP2_HEADER_VARY'vary'
http2.constants.HTTP2_HEADER_X_CONTENT_TYPE_OPTIONS'x-content-type-options'
http2.constants.HTTP2_HEADER_X_FRAME_OPTIONS'x-frame-options'
http2.constants.HTTP2_HEADER_KEEP_ALIVE'keep-alive'
http2.constants.HTTP2_HEADER_PROXY_CONNECTION'proxy-connection'
http2.constants.HTTP2_HEADER_X_XSS_PROTECTION'x-xss-protection'
http2.constants.HTTP2_HEADER_ALT_SVC'alt-svc'
http2.constants.HTTP2_HEADER_CONTENT_SECURITY_POLICY'content-security-policy'
http2.constants.HTTP2_HEADER_EARLY_DATA'early-data'
http2.constants.HTTP2_HEADER_EXPECT_CT'expect-ct'
http2.constants.HTTP2_HEADER_ORIGIN'origin'
http2.constants.HTTP2_HEADER_PURPOSE'purpose'
http2.constants.HTTP2_HEADER_TIMING_ALLOW_ORIGIN'timing-allow-origin'
http2.constants.HTTP2_HEADER_X_FORWARDED_FOR'x-forwarded-for'
http2.constants.HTTP2_HEADER_PRIORITY'priority'
http2.constants.HTTP2_HEADER_ACCEPT_CHARSET'accept-charset'
http2.constants.HTTP2_HEADER_ACCESS_CONTROL_MAX_AGE'access-control-max-age'
http2.constants.HTTP2_HEADER_ALLOW'allow'
http2.constants.HTTP2_HEADER_CONTENT_LANGUAGE'content-language'
http2.constants.HTTP2_HEADER_CONTENT_LOCATION'content-location'
http2.constants.HTTP2_HEADER_CONTENT_MD5'content-md5'
http2.constants.HTTP2_HEADER_CONTENT_RANGE'content-range'
http2.constants.HTTP2_HEADER_DNT'dnt'
http2.constants.HTTP2_HEADER_EXPECT'expect'
http2.constants.HTTP2_HEADER_EXPIRES'expires'
http2.constants.HTTP2_HEADER_FROM'from'
http2.constants.HTTP2_HEADER_IF_MATCH'if-match'
http2.constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE'if-unmodified-since'
http2.constants.HTTP2_HEADER_MAX_FORWARDS'max-forwards'
http2.constants.HTTP2_HEADER_PREFER'prefer'
http2.constants.HTTP2_HEADER_PROXY_AUTHENTICATE'proxy-authenticate'
http2.constants.HTTP2_HEADER_PROXY_AUTHORIZATION'proxy-authorization'
http2.constants.HTTP2_HEADER_REFRESH'refresh'
http2.constants.HTTP2_HEADER_RETRY_AFTER'retry-after'
http2.constants.HTTP2_HEADER_TRAILER'trailer'
http2.constants.HTTP2_HEADER_TK'tk'
http2.constants.HTTP2_HEADER_VIA'via'
http2.constants.HTTP2_HEADER_WARNING'warning'
http2.constants.HTTP2_HEADER_WWW_AUTHENTICATE'www-authenticate'
http2.constants.HTTP2_HEADER_HTTP2_SETTINGS'http2-settings'
", "displayName": "Regular header constants" } ], "displayName": "Header name constants" }, { "textRaw": "Error codes for `RST_STREAM` and `GOAWAY`", "name": "error_codes_for_`rst_stream`_and_`goaway`", "type": "module", "desc": "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ValueNameConstant
0x00No Errorhttp2.constants.NGHTTP2_NO_ERROR
0x01Protocol Errorhttp2.constants.NGHTTP2_PROTOCOL_ERROR
0x02Internal Errorhttp2.constants.NGHTTP2_INTERNAL_ERROR
0x03Flow Control Errorhttp2.constants.NGHTTP2_FLOW_CONTROL_ERROR
0x04Settings Timeouthttp2.constants.NGHTTP2_SETTINGS_TIMEOUT
0x05Stream Closedhttp2.constants.NGHTTP2_STREAM_CLOSED
0x06Frame Size Errorhttp2.constants.NGHTTP2_FRAME_SIZE_ERROR
0x07Refused Streamhttp2.constants.NGHTTP2_REFUSED_STREAM
0x08Cancelhttp2.constants.NGHTTP2_CANCEL
0x09Compression Errorhttp2.constants.NGHTTP2_COMPRESSION_ERROR
0x0aConnect Errorhttp2.constants.NGHTTP2_CONNECT_ERROR
0x0bEnhance Your Calmhttp2.constants.NGHTTP2_ENHANCE_YOUR_CALM
0x0cInadequate Securityhttp2.constants.NGHTTP2_INADEQUATE_SECURITY
0x0dHTTP/1.1 Requiredhttp2.constants.NGHTTP2_HTTP_1_1_REQUIRED
\n

The 'timeout' event is emitted when there is no activity on the Server for\na given number of milliseconds set using http2server.setTimeout().

", "displayName": "Error codes for `RST_STREAM` and `GOAWAY`" } ] }, { "textRaw": "Type: {symbol}", "name": "sensitiveHeaders", "type": "symbol", "meta": { "added": [ "v15.0.0", "v14.18.0" ], "changes": [] }, "desc": "

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.

" } ], "displayName": "Core API" }, { "textRaw": "Compatibility API", "name": "compatibility_api", "type": "module", "desc": "

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.

\n

The following example creates an HTTP/2 server using the compatibility\nAPI:

\n
import { createServer } from 'node:http2';\nconst server = createServer((req, res) => {\n  res.writeHead(200, {\n    'Content-Type': 'text/plain; charset=utf-8',\n    'X-Foo': 'bar',\n  });\n  res.end('ok');\n});\n
\n
const http2 = require('node:http2');\nconst server = http2.createServer((req, res) => {\n  res.writeHead(200, {\n    'Content-Type': 'text/plain; charset=utf-8',\n    'X-Foo': 'bar',\n  });\n  res.end('ok');\n});\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.

\n

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.

", "modules": [ { "textRaw": "ALPN negotiation", "name": "alpn_negotiation", "type": "module", "desc": "

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.

\n

The following example creates a server that supports both protocols:

\n
import { createSecureServer } from 'node:http2';\nimport { readFileSync } from '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(8000);\n\nfunction onRequest(req, res) {\n  // Detects if it is an 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
\n
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 an 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
\n

The 'request' event works identically on both HTTPS and\nHTTP/2.

", "displayName": "ALPN negotiation" } ], "classes": [ { "textRaw": "Class: `http2.Http2ServerRequest`", "name": "http2.Http2ServerRequest", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

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.

", "events": [ { "textRaw": "Event: `'aborted'`", "name": "aborted", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

The 'aborted' event is emitted whenever a Http2ServerRequest instance is\nabnormally aborted in mid-communication.

\n

The 'aborted' event will only be emitted if the Http2ServerRequest writable\nside has not been ended.

" }, { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was closed.\nJust like 'end', this event occurs only once per response.

" } ], "properties": [ { "textRaw": "Type: {boolean}", "name": "aborted", "type": "boolean", "meta": { "added": [ "v10.1.0" ], "changes": [] }, "desc": "

The request.aborted property will be true if the request has\nbeen aborted.

" }, { "textRaw": "Type: {string}", "name": "authority", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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'].

" }, { "textRaw": "Type: {boolean}", "name": "complete", "type": "boolean", "meta": { "added": [ "v12.10.0" ], "changes": [] }, "desc": "

The request.complete property will be true if the request has\nbeen completed, aborted, or destroyed.

" }, { "textRaw": "Type: {net.Socket | tls.TLSSocket}", "name": "connection", "type": "net.Socket | tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [], "deprecated": [ "v13.0.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `request.socket`.", "desc": "

See request.socket.

" }, { "textRaw": "Type: {Object}", "name": "headers", "type": "Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response headers object.

\n

Key-value pairs of header names and values. Header names are lower-cased.

\n
// 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
\n

See HTTP/2 Headers Object.

\n

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:

\n
removeAllHeaders(request.headers);\nassert(request.url);   // Fails because the :path header has been removed\n
" }, { "textRaw": "Type: {string}", "name": "httpVersion", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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'.

\n

Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.

" }, { "textRaw": "Type: {string}", "name": "method", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request method as a string. Read-only. Examples: 'GET', 'DELETE'.

" }, { "textRaw": "Type: {HTTP/2 Raw Headers}", "name": "rawHeaders", "type": "HTTP/2 Raw Headers", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The raw request/response headers list exactly as they were received.

\n
// 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
" }, { "textRaw": "Type: {string[]}", "name": "rawTrailers", "type": "string[]", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.

" }, { "textRaw": "Type: {string}", "name": "scheme", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request scheme pseudo header field indicating the scheme\nportion of the target URL.

" }, { "textRaw": "Type: {net.Socket | tls.TLSSocket}", "name": "socket", "type": "net.Socket | tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on request.stream.

\n

destroy, emit, end, on and once methods will be called on\nrequest.stream.

\n

setTimeout method will be called on request.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket. With TLS support,\nuse request.socket.getPeerCertificate() to obtain the client's\nauthentication details.

" }, { "textRaw": "Type: {Http2Stream}", "name": "stream", "type": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the request.

" }, { "textRaw": "Type: {Object}", "name": "trailers", "type": "Object", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The request/response trailers object. Only populated at the 'end' event.

" }, { "textRaw": "Type: {string}", "name": "url", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Request URL string. This contains only the URL that is present in the actual\nHTTP request. If the request is:

\n
GET /status?name=ryan HTTP/1.1\nAccept: text/plain\n
\n

Then request.url will be:

\n
\"/status?name=ryan\"\n
\n

To parse the url into its parts, new URL() can be used:

\n
$ 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
" } ], "methods": [ { "textRaw": "`request.destroy([error])`", "name": "destroy", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error", "optional": true } ] } ], "desc": "

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.

\n

It does nothing if the stream was already destroyed.

" }, { "textRaw": "`request.setTimeout(msecs, callback)`", "name": "setTimeout", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function" } ], "return": { "textRaw": "Returns: {http2.Http2ServerRequest}", "name": "return", "type": "http2.Http2ServerRequest" } } ], "desc": "

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.

\n

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.

" } ] }, { "textRaw": "Class: `http2.Http2ServerResponse`", "name": "http2.Http2ServerResponse", "type": "class", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "\n

This object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.

", "events": [ { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

Indicates that the underlying Http2Stream was terminated before\nresponse.end() was called or able to flush.

" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "params": [], "desc": "

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.

\n

After this event, no more events will be emitted on the response object.

" } ], "methods": [ { "textRaw": "`response.addTrailers(headers)`", "name": "addTrailers", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" }, { "textRaw": "`response.appendHeader(name, value)`", "name": "appendHeader", "type": "method", "meta": { "added": [ "v21.7.0", "v20.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {string | string[]}", "name": "value", "type": "string | string[]" } ] } ], "desc": "

Append a single header value to the header object.

\n

If the value is an array, this is equivalent to calling this method multiple\ntimes.

\n

If there were no previous values for the header, this is equivalent to calling\nresponse.setHeader().

\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

\n
// Returns headers including \"set-cookie: a\" and \"set-cookie: b\"\nconst server = http2.createServer((req, res) => {\n  res.setHeader('set-cookie', 'a');\n  res.appendHeader('set-cookie', 'b');\n  res.writeHead(200);\n  res.end('ok');\n});\n
" }, { "textRaw": "`response.createPushResponse(headers, callback)`", "name": "createPushResponse", "type": "method", "meta": { "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`." } ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {HTTP/2 Headers Object} An object describing the headers", "name": "headers", "type": "HTTP/2 Headers Object", "desc": "An object describing the headers" }, { "textRaw": "`callback` {Function} Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", "name": "callback", "type": "Function", "desc": "Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`res` {http2.Http2ServerResponse} The newly-created `Http2ServerResponse` object", "name": "res", "type": "http2.Http2ServerResponse", "desc": "The newly-created `Http2ServerResponse` object" } ] } ] } ], "desc": "

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.

" }, { "textRaw": "`response.end([data[, encoding]][, callback])`", "name": "end", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `ServerResponse`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string | Buffer | Uint8Array}", "name": "data", "type": "string | Buffer | Uint8Array", "optional": true }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" } } ], "desc": "

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.

\n

If data is specified, it is equivalent to calling\nresponse.write(data, encoding) followed by response.end(callback).

\n

If callback is specified, it will be called when the response stream\nis finished.

" }, { "textRaw": "`response.getHeader(name)`", "name": "getHeader", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ], "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" } } ], "desc": "

Reads out a header that has already been queued but not sent to the client.\nThe name is case-insensitive.

\n
const contentType = response.getHeader('content-type');\n
" }, { "textRaw": "`response.getHeaderNames()`", "name": "getHeaderNames", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {string[]}", "name": "return", "type": "string[]" } } ], "desc": "

Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.

\n
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n
" }, { "textRaw": "`response.getHeaders()`", "name": "getHeaders", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" } } ], "desc": "

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.

\n

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.

\n
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
" }, { "textRaw": "`response.hasHeader(name)`", "name": "hasHeader", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "

Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.

\n
const hasContentType = response.hasHeader('content-type');\n
" }, { "textRaw": "`response.removeHeader(name)`", "name": "removeHeader", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

Removes a header that has been queued for implicit sending.

\n
response.removeHeader('Content-Encoding');\n
" }, { "textRaw": "`response.setHeader(name, value)`", "name": "setHeader", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`value` {string | string[]}", "name": "value", "type": "string | string[]" } ] } ], "desc": "

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.

\n
response.setHeader('Content-Type', 'text/html; charset=utf-8');\n
\n

or

\n
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

\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.

\n
// 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
" }, { "textRaw": "`response.setTimeout(msecs[, callback])`", "name": "setTimeout", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`msecs` {number}", "name": "msecs", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" } } ], "desc": "

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.

\n

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.

" }, { "textRaw": "`response.write(chunk[, encoding][, callback])`", "name": "write", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {string | Buffer | Uint8Array}", "name": "chunk", "type": "string | Buffer | Uint8Array" }, { "textRaw": "`encoding` {string}", "name": "encoding", "type": "string", "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "optional": true } ], "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" } } ], "desc": "

If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.

\n

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.

\n

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.

\n

This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.

\n

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.

\n

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.

" }, { "textRaw": "`response.writeContinue()`", "name": "writeContinue", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

Sends a status 100 Continue to the client, indicating that the request body\nshould be sent. See the 'checkContinue' event on Http2Server and\nHttp2SecureServer.

" }, { "textRaw": "`response.writeEarlyHints(hints)`", "name": "writeEarlyHints", "type": "method", "meta": { "added": [ "v18.11.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`hints` {Object}", "name": "hints", "type": "Object" } ] } ], "desc": "

Sends a status 103 Early Hints to the client with a Link header,\nindicating that the user agent can preload/preconnect the linked resources.\nThe hints is an object containing the values of headers to be sent with\nearly hints message.

\n

Example

\n
const earlyHintsLink = '</styles.css>; rel=preload; as=style';\nresponse.writeEarlyHints({\n  'link': earlyHintsLink,\n});\n\nconst earlyHintsLinks = [\n  '</styles.css>; rel=preload; as=style',\n  '</scripts.js>; rel=preload; as=script',\n];\nresponse.writeEarlyHints({\n  'link': earlyHintsLinks,\n});\n
" }, { "textRaw": "`response.writeInformation(statusCode[, headers])`", "name": "writeInformation", "type": "method", "meta": { "added": [ "v26.2.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`statusCode` {number} An HTTP 1xx informational status code, between `100` and `199` inclusive, excluding `101` (Switching Protocols) which is not allowed in HTTP/2.", "name": "statusCode", "type": "number", "desc": "An HTTP 1xx informational status code, between `100` and `199` inclusive, excluding `101` (Switching Protocols) which is not allowed in HTTP/2." }, { "textRaw": "`headers` {Object} An optional object of headers to send with the informational response.", "name": "headers", "type": "Object", "desc": "An optional object of headers to send with the informational response.", "optional": true } ] } ], "desc": "

Sends an arbitrary HTTP 1xx informational response, equivalent in HTTP/2 to a\nHEADERS frame whose :status pseudo-header is a 1xx code. May be called\nmultiple times before the final response. After the final response headers\nhave been sent, this method is a no-op and returns false.

\n

This is the generic equivalent of response.writeContinue() and\nresponse.writeEarlyHints().

\n
response.writeInformation(110, { 'X-Progress': '50%' });\n
" }, { "textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`", "name": "writeHead", "type": "method", "meta": { "added": [ "v8.4.0" ], "changes": [ { "version": [ "v11.10.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/25974", "description": "Return `this` from `writeHead()` to allow chaining with `end()`." } ] }, "signatures": [ { "params": [ { "textRaw": "`statusCode` {number}", "name": "statusCode", "type": "number" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string", "optional": true }, { "textRaw": "`headers` {HTTP/2 Headers Object | HTTP/2 Raw Headers}", "name": "headers", "type": "HTTP/2 Headers Object | HTTP/2 Raw Headers", "optional": true } ], "return": { "textRaw": "Returns: {http2.Http2ServerResponse}", "name": "return", "type": "http2.Http2ServerResponse" } } ], "desc": "

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.

\n

Returns a reference to the Http2ServerResponse, so that calls can be chained.

\n

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.

\n
const body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': Buffer.byteLength(body),\n  'Content-Type': 'text/plain; charset=utf-8',\n});\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.

\n

This method may be called at most one time on a message before\nresponse.end() is called.

\n

If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.

\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.

\n
// 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
\n

Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.

" } ], "properties": [ { "textRaw": "Type: {net.Socket | tls.TLSSocket}", "name": "connection", "type": "net.Socket | tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [], "deprecated": [ "v13.0.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `response.socket`.", "desc": "

See response.socket.

" }, { "textRaw": "Type: {boolean}", "name": "finished", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [], "deprecated": [ "v13.4.0", "v12.16.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `response.writableEnded`.", "desc": "

Boolean value that indicates whether the response has completed. Starts\nas false. After response.end() executes, the value will be true.

" }, { "textRaw": "Type: {boolean}", "name": "headersSent", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

True if headers were sent, false otherwise (read-only).

" }, { "textRaw": "Type: {http2.Http2ServerRequest}", "name": "req", "type": "http2.Http2ServerRequest", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "

A reference to the original HTTP2 request object.

" }, { "textRaw": "Type: {boolean}", "name": "sendDate", "type": "boolean", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.

" }, { "textRaw": "Type: {net.Socket | tls.TLSSocket}", "name": "socket", "type": "net.Socket | tls.TLSSocket", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Returns a Proxy object that acts as a net.Socket (or tls.TLSSocket) but\napplies getters, setters, and methods based on HTTP/2 logic.

\n

destroyed, readable, and writable properties will be retrieved from and\nset on response.stream.

\n

destroy, emit, end, on and once methods will be called on\nresponse.stream.

\n

setTimeout method will be called on response.stream.session.

\n

pause, read, resume, and write will throw an error with code\nERR_HTTP2_NO_SOCKET_MANIPULATION. See Http2Session and Sockets for\nmore information.

\n

All other interactions will be routed directly to the socket.

\n
import { createServer } from 'node:http2';\nconst server = 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
\n
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
" }, { "textRaw": "Type: {number}", "name": "statusCode", "type": "number", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

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.

\n
response.statusCode = 404;\n
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.

" }, { "textRaw": "Type: {string}", "name": "statusMessage", "type": "string", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns\nan empty string.

" }, { "textRaw": "Type: {Http2Stream}", "name": "stream", "type": "Http2Stream", "meta": { "added": [ "v8.4.0" ], "changes": [] }, "desc": "

The Http2Stream object backing the response.

" }, { "textRaw": "Type: {boolean}", "name": "writableEnded", "type": "boolean", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "

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.

" } ] } ], "displayName": "Compatibility API" }, { "textRaw": "Collecting HTTP/2 performance metrics", "name": "collecting_http/2_performance_metrics", "type": "module", "desc": "

The Performance Observer API can be used to collect basic performance\nmetrics for each Http2Session and Http2Stream instance.

\n
import { PerformanceObserver } from '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
\n
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
\n

The entryType property of the PerformanceEntry will be equal to 'http2'.

\n

The name property of the PerformanceEntry will be equal to either\n'Http2Stream' or 'Http2Session'.

\n

If name is equal to Http2Stream, the PerformanceEntry will contain the\nfollowing additional properties:

\n\n

If name is equal to Http2Session, the PerformanceEntry will contain the\nfollowing additional properties:

\n", "displayName": "Collecting HTTP/2 performance metrics" }, { "textRaw": "Note on `:authority` and `host`", "name": "note_on_`:authority`_and_`host`", "type": "module", "desc": "

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).

\n

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.

", "displayName": "Note on `:authority` and `host`" } ], "displayName": "HTTP/2" } ] }