Networking

http2.connect() and stream lifecycle

HTTP/2 represents HTTP requests and responses as streams inside a connection. A client can have multiple concurrent streams in one session, reducing the need for separate TCP connections. Node provides low-level stream and session APIs in `node:http2`. Create a cleartext lab server with `createServer` and a matching `connect` client. This is prior-knowledge HTTP/2 on loopback, not a browser HTTPS example. For TLS use `createSecureServer` and verify certificates and ALPN (Application-Layer Protocol Negotiation); the selected protocol depends on both peers. HTTP/2 uses pseudo-headers such as `:method` and `:path`. A stream can fail independently, while session failure can affect many requests. HTTP/2 still runs over TCP, so multiplexing does not remove all transport-level blocking. HTTP/3 is a different QUIC-based protocol and is outside this tested API scope. Do not close a shared session when only one request finishes. Consume response bodies, close the session after all streams settle, and handle both stream and session errors. Cleartext h2 is not a production substitute for TLS. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/http2.html.

Formal Syntax & Structure

nodejs syntaxnodejs
http2.connect(authority[, options][, listener])

Working Example

Example Snippetnodejs
import http2 from 'node:http2';import { once } from 'node:events';const server=http2.createServer();server.on('stream',(stream,headers)=>{stream.respond({':status':200});stream.end('item '+headers[':path']);});server.listen(0,'127.0.0.1');await once(server,'listening');const session=http2.connect('http://127.0.0.1:'+server.address().port);session.setTimeout(1500,()=>session.destroy(new Error('timeout')));await once(session,'connect');async function request(path){  const stream=session.request({':path':path});stream.end();  let body=''; for await(const chunk of stream)body+=chunk;  return body;}try {const results=await Promise.all([request('/a'),request('/b')]);console.log(results.join(' | '));}finally {session.close();await once(session,'close');await new Promise(r=>server.close(r));}
Node.js Reference