Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns

Node.js http2.connect() method

Reference for http2.connect() in Node.js: open an HTTP/2 session, send multiplexed requests over streams, read response headers and data, and close cleanly.

http2.connect(authority[, options][, listener]) opens one HTTP/2 connection and returns a ClientHttp2Session. You then call session.request(headers) once per request; each call returns a ClientHttp2Stream, a duplex stream that carries the request body (you write) and the response (you read). Many streams share the one connection at the same time, which is the main advantage of HTTP/2: no head-of-line blocking at the HTTP level and no new handshake per request.

authority is a URL such as 'https://example.com' or, for plain-text h2c, 'http://127.0.0.1:8080'. With an https: URL, the protocol is negotiated through TLS and ALPN, and the TLS options of https.request() (ca, servername, rejectUnauthorized) apply.

NODE
const session = http2.connect('https://example.com');
const stream = session.request({ ':path': '/' });
stream.on('response', (headers) => console.log(headers[':status']));
stream.resume();
stream.on('end', () => session.close());

Try it

Node.js Several requests on one connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js HTTP/2 over TLS with ALPN

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
http2.connect(authority[, options][, listener])  // ClientHttp2Session
session.request(headers[, options])             // ClientHttp2Stream
Name Description
authority A string or URL, http:// (h2c) or https://. Only the origin is used; the path comes from :path in each request.
options.settings, options.maxSessionMemory, options.maxHeaderListPairs Same session options as the server side.
TLS options ca, servername, rejectUnauthorized, key, cert, minVersion and so on, for https: authorities.
options.createConnection(url, options) Provide your own socket (for tunnels or tests).
listener One-time 'connect' listener.
headers (in request()) Object with pseudo-headers :method (default GET), :path (default /), and ordinary lower-case headers.
options (in request()) endStream (end the request immediately; default true for GET), weight, parent, exclusive, waitForTrailers, signal.

Session events: 'connect', 'error', 'close', 'goaway', 'remoteSettings', 'localSettings', 'stream', 'timeout', 'ping'. Stream events: 'response' (headers, flags), 'data', 'end', 'trailers', 'push', 'error', 'close', 'timeout'.

Methods: session.close() finishes existing streams and then closes; session.destroy([err]) closes at once; session.ping(), session.settings(obj), session.setTimeout(ms), session.ref() and session.unref().

Errors: a failed connection or TLS check emits 'error' on the session (ECONNREFUSED, DEPTH_ZERO_SELF_SIGNED_CERT, ERR_HTTP2_ERROR). Calling request() on a closed session throws ERR_HTTP2_INVALID_SESSION; a stream the server resets closes with a non-zero stream.rstCode and may emit ERR_HTTP2_STREAM_ERROR.

Usage notes

  • Reuse the session. Opening a session per request throws away the benefit of HTTP/2. Keep one per origin and call request() on it.
  • Always close. An open session keeps the process alive. Call session.close() when the work is done (or unref() it for long-lived pools).
  • Listen for 'error' on session and stream. Both can fail independently, and an unhandled one crashes the process.
  • Read the response. A stream you do not consume (resume() or a data listener) stalls and holds flow-control window.
  • Request bodies: for POST, pass :method and call stream.end(body); with endStream: false you can write incrementally.
  • Pseudo-headers come first and in lower case; connection-specific headers such as Connection and Keep-Alive are rejected.
  • fetch() and http.request() speak HTTP/1.1 to a Node server unless an undici dispatcher with allowH2 is configured; use http2.connect() for explicit HTTP/2.