skip to content

How does a Node.js node:http2 server differ from a node:http server in its objects and events, and when do you need createSecureServer and allowHTTP1?

level: middleimportance: nice to knowfreq 25%

answer

  1. one session, many streams
  2. the 'stream' event and pseudo-headers
  3. a compatibility layer with req and res
  4. browsers require TLS for HTTP/2
  5. ALPN fallback on one port

basics

~20 s

node:http2 gives each connection an Http2Session carrying many Http2Streams; the core API answers a 'stream' event with stream.respond(), while a compatibility API offers req and res. Browsers need createSecureServer; allowHTTP1 lets HTTP/1.1 clients share the port.

solid answer

~40 s

In `node:http`, a connection is a socket and each request is a `req`/`res` pair. In `node:http2`, each connection becomes an `Http2Session`, and every request on it is an `Http2Stream`, a `Duplex`. The **core API** emits `'stream'` with `(stream, headers)`, where headers include pseudo-headers such as `':method'` and `':path'`, and you answer with `stream.respond({ ':status': 200 })` plus `stream.end()`. The **Compatibility API** passes a handler `Http2ServerRequest` and `Http2ServerResponse` objects that mimic the public HTTP/1 API, so `writeHead` and `end` still work, though code relying on `node:http` internals does not. Browsers do not speak unencrypted HTTP/2, so serving them means `http2.createSecureServer` with a key and certificate; `http2.createServer` is cleartext for internal hops. `allowHTTP1: true` (default `false`) lets clients that negotiate HTTP/1.1 through ALPN use the same port.

code

javascript · 18 lines
javascript
import { createSecureServer } from 'node:http2';
import { readFileSync } from 'node:fs';

const server = createSecureServer({
  key: readFileSync('server-key.pem'),
  cert: readFileSync('server-cert.pem'),
  allowHTTP1: true,
});

server.on('error', (err) => console.error(err));

// Compatibility API: one handler for HTTP/2 streams and HTTP/1.1 requests.
server.on('request', (req, res) => {
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ httpVersion: req.httpVersion }));
});

server.listen(8443);

go deeper

for a junior

Know that node:http2 exists, that browsers need a TLS server for HTTP/2, and that a handler can still use req and res through the Compatibility API.

for a middle

Map the objects: Http2Session per connection, Http2Stream per request, the 'stream' event and stream.respond with pseudo-headers, and what allowHTTP1 changes.

for a senior

Anticipate porting breakage: dropped connection headers, ignored status messages, libraries using node:http internals, and stream resets that make a late respond() throw.

for a principal

Decide whether Node should speak HTTP/2 at all or leave it to a proxy, weighing per-session limits and operational familiarity against end-to-end HTTP/2.

## Same job, different objects Both modules turn bytes from the network into requests for your code, but they model the connection differently. HTTP/2 carries many concurrent requests over one connection, and `node:http2` exposes that structure instead of hiding it. | Concept | `node:http` | `node:http2` core API | |---|---|---| | One connection | a `net.Socket` | an `Http2Session` | | One request/response | `http.IncomingMessage` + `http.ServerResponse` | one `Http2Stream`, a `Duplex` | | Server event per request | `'request'` | `'stream'` (and `'request'` for the Compatibility API) | | Request metadata | `req.method`, `req.url`, `req.headers` | a headers object with `':method'`, `':path'`, `':authority'`, `':scheme'` | | Sending status and headers | `res.writeHead(200, {...})` | `stream.respond({ ':status': 200, ... })` | The server creates sessions itself when a connection arrives and emits `'session'`; the docs note that server code rarely needs to touch the session directly. Session-level settings, though, are where you tune limits: `maxConcurrentStreams` defaults to 4294967295 (effectively unlimited) and `maxSessionMemory` to 10 megabytes, after which new streams are refused. ## Core API or Compatibility API **Core API.** Listen for `'stream'`, read the request headers from the second argument, and answer on the stream: - `stream.respond(headers)` sends the response headers, with `':status'` as a pseudo-header; - `stream.write()` and `stream.end()` send the body, because the stream is a `Duplex`; - `stream.respondWithFile()` sends a file without reading it into memory yourself. The peer can reset an individual stream at any moment, and the docs warn that `stream.respond()` can then throw, so error paths that respond late should guard the call. **Compatibility API.** Pass a handler to `http2.createSecureServer(options, handler)` or listen for `'request'`, and you receive `Http2ServerRequest` and `Http2ServerResponse`, built to resemble the HTTP/1 objects. `setHeader`, `writeHead`, `write` and `end` behave much as they do in `node:http`. The docs are explicit that the layer targets only the **public** HTTP/1 API; libraries that reach into `node:http` internals are not supported. A few HTTP/1 habits also change meaning: - `statusMessage` does not exist in HTTP/2; passing one to `writeHead` has no effect and emits a warning, and `response.statusMessage` returns an empty string. - Connection-specific headers are forbidden in HTTP/2. In the Compatibility API, `setHeader('Connection', ...)` is dropped with an `UnsupportedWarning`; passing such a header (`connection`, `keep-alive`, `transfer-encoding`, `upgrade` and similar) to the core `stream.respond()` throws `ERR_HTTP2_INVALID_CONNECTION_HEADERS`. - Header names are lower-case on the wire, matching how `req.headers` already presents them in `node:http`. ## Secure or cleartext - `http2.createSecureServer(options)` takes the TLS options (`key`, `cert` and the rest) and negotiates HTTP/2 through **ALPN** during the TLS handshake. The docs state that no browser is known to support unencrypted HTTP/2, so anything serving browsers directly needs this. - `http2.createServer()` speaks cleartext HTTP/2 (`h2c`). It suits hops where both ends are under your control and known to speak HTTP/2 without TLS. ## Serving HTTP/1.1 clients too With the default `allowHTTP1: false`, a secure server only accepts HTTP/2. Clients that offer only HTTP/1.1 through ALPN fail the TLS handshake, and a client that sends no ALPN at all triggers the `'unknownProtocol'` event, whose default terminates the connection. Setting `allowHTTP1: true` lets those HTTP/1.1 clients use the same port: the Compatibility API handler then receives ordinary HTTP/1 `req` and `res` objects for them. The docs give the rule that follows: the handler **must** restrict itself to the public HTTP/1 API and detect HTTP/2 before using HTTP/2-only features, for example by checking `req.httpVersion === '2.0'`. ## What changes operationally - One connection now carries many requests at once, so per-connection limits matter more than per-request ones. - `server.close()` on an HTTP/2 server stops new sessions and streams, and its callback runs only after every active session has closed. - Errors arrive at more levels: on the server, on each session and on each stream. A client that resets one stream affects that stream rather than the whole session, so per-stream error handling matters alongside the server's `'error'` listener. - Tuning moves to per-session limits, `maxConcurrentStreams` through the `settings` option and `maxSessionMemory` directly in the server options, because one busy client can open many streams on one session. - The protocol details behind this (stream multiplexing, header compression, prioritisation) are covered with HTTP/2 itself; this module is how Node exposes them.

  • A team ports a node:http service to http2.createSecureServer with the Compatibility API, and a response helper that sets Connection: keep-alive stops sending that header. What happened?
    HTTP/2 forbids connection-specific headers. The Compatibility API's `setHeader` drops a `Connection` header and emits an `UnsupportedWarning` instead of sending it; the same header given to the core `stream.respond()` would throw `ERR_HTTP2_INVALID_CONNECTION_HEADERS`. Connection management in HTTP/2 belongs to the session, so the header should simply be removed.
  • With allowHTTP1 left at its default, what happens to a client that offers only HTTP/1.1 during the TLS handshake with a Node http2 secure server?
    `allowHTTP1` defaults to `false`, so the server's ALPN list contains only HTTP/2. Since Node 19, a client whose ALPN offer contains no protocol the server supports fails the TLS handshake. Only a client that sends no ALPN extension at all reaches the `'unknownProtocol'` event, whose default is to terminate the connection.

  • Thinks each HTTP/2 request gets its own socket
  • Expects browsers to connect to http2.createServer without TLS
  • Believes the Compatibility API supports node:http internals
  • Sends a Connection header and expects it on the wire
  • Assumes allowHTTP1 is on by default