Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns
Node.js http2.createServer() method
Reference for http2.createServer() and createSecureServer() in Node.js: the stream event, the compatibility request listener, pseudo-headers, settings and push.
http2.createServer([options][, onRequestHandler]) creates an HTTP/2 server that speaks the protocol in plain text (often called h2c). http2.createSecureServer() is the TLS version that browsers need, because browsers only use HTTP/2 over TLS. Both return an Http2Server (or Http2SecureServer) that emits events per HTTP/2 stream, not per connection.
HTTP/2 multiplexes many requests over one connection. In Node you can work at two levels. The core API handles the 'stream' event and calls stream.respond(); the compatibility API gives you the familiar (req, res) pair that works like node:http. Passing a listener to createServer() selects the compatibility API; listening for 'stream' selects the core one.
import http2 from 'node:http2'; const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ ':status': 200 }); stream.end('hello'); }); server.listen(8080);
Try it
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.
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
http2.createServer([options][, onRequestHandler]) http2.createSecureServer(options[, onRequestHandler])
| Name | Description |
|---|---|
options.settings |
Initial HTTP/2 settings: maxConcurrentStreams, initialWindowSize, maxFrameSize, headerTableSize, enablePush, enableConnectProtocol, maxHeaderListSize. |
options.maxSessionMemory |
Memory limit per session, in megabytes. A session that exceeds it is closed. Default 10. |
options.maxHeaderListPairs, options.maxOutstandingPings, options.maxSendHeaderBlockLength, options.paddingStrategy |
Resource limits and padding policy. |
options.unknownProtocolTimeout |
Milliseconds a TLS server waits for ALPN negotiation of an unknown protocol before closing. |
options.allowHTTP1 |
Secure server only: also serve HTTP/1.x clients on the same port. |
options.key, options.cert, other TLS options |
Used by createSecureServer(); see https.createServer(). |
onRequestHandler |
Optional (req, res) listener; this selects the compatibility API. |
Events on the server: 'stream' (stream, headers, flags, rawHeaders), 'request' (req, res) for compatibility mode, 'session', 'sessionError', 'timeout', 'checkContinue', and 'unknownProtocol' on the secure server.
Returns: an Http2Server or Http2SecureServer.
Errors: invalid options throw ERR_INVALID_ARG_TYPE or ERR_HTTP2_INVALID_SETTING_VALUE. Protocol violations by a client reset the stream or close the session; look at 'sessionError' and stream.on('error').
Usage notes
- Browsers need TLS.
createServer()only works for clients that explicitly use h2c (such as Node's own client,curl --http2-prior-knowledge, or tools behind a proxy). UsecreateSecureServer()for the public internet, or terminate TLS at a proxy. - Header names are lower-case and request metadata appears as pseudo-headers:
:method,:path,:scheme,:authority. Responses must send:status. stream.respond()must be called once before writing data, unless you usestream.respondWithFile()orrespondWithFD(), which do both.- Handle errors on each stream. A client that resets a stream causes an
'error'or'close'on it; an unhandled'error'on a session crashes the process. - One connection, many streams.
maxConcurrentStreamsbounds parallel requests per client. Do not hold per-request state on the connection object. - Server push (
stream.pushStream()) exists but browsers have removed support for it; preferres.writeEarlyHints()and preload links. - Compatibility mode has gaps: no
statusMessageon the wire, noTransfer-Encoding, no connection-specific headers (Connection,Keep-Aliveare forbidden in HTTP/2). - Closing:
server.close()stops accepting sessions; usesession.close()orsession.destroy()on open ones.