rules/quic-api.md
GitHubnode:quic API reference
Source: doc/api/quic.md at nodejs/node ab476eccd03. The module is
Stability 1.0 (Early development). The --experimental-quic CLI entry says
1.1. Items marked verified were run on main (v28.0.0-pre) built with
./configure --experimental-quic. Everything else is from the docs and was
not run.
Availability
- The module itself is
added: v23.8.0, and most core members carry that version. - The runtime flag
--experimental-quicwas added in v25.0.0 and v24.16.0. v24.19.0 and v26.13.0 accept the flag (verified), but their official binaries are built without QUIC (process.config.variables.node_use_quic === false), sonode:quicis an unknown built-in there. - Even when built in, the module is absent without the runtime flag (verified).
- About 70 members are
added: [v26.2.0, v24.20.0]. These includesession.opened,stream.writer,setBody, async iteration, HTTP/3,rejectUnauthorized,reuseEndpoint,token, andkeepAlive. Check each member's YAML before you target v24.16–24.19. stream.openedis v26.10.0 only.
Module functions
quic.connect(address, sessionOptions)returns a Promise for aQuicSession.addressis a'host:port'string or anet.SocketAddress(verified: passingendpoint.addressworks). By default it reuses or creates a client endpoint; setreuseEndpoint: falseto force a new one. To pin the local address, passendpoint: QuicEndpoint | EndpointOptions.quic.listen(onsession, sessionOptions)returns a Promise for aQuicEndpoint. Each endpoint can listen once. Put the bind address in{ endpoint: { address: '127.0.0.1:0' } }(verified).quic.listEndpoints({ active = true })(v26.4.0, v24.20.0).quic.constantsholdscc.RENO,cc.CUBIC,cc.BBR,DEFAULT_CIPHERSandDEFAULT_GROUPS.- Classes:
QuicEndpoint,QuicSession,QuicStream, andQuicError(message, { errorCode, type }), which exposes.errorCodeand.type.
QuicEndpoint
new QuicEndpoint(endpointOptions). A bare endpoint needs no --allow-net
until it connects or listens.
Members:
address, aSocketAddressorundefined.busy, read/write. When true, the endpoint rejects new sessions.close(), a Promise. It waits for open sessions to finish.closed,closing,destroy([err]),destroyed,listening.maxConnectionsPerHostandmaxConnectionsTotal, read/write. Range 0–65535, where 0 means unlimited.setSNIContexts(entries, { replace = false })hot-swaps the identities used by new sessions.statsand[Symbol.asyncDispose].
endpoint.stats fields (bigint): createdAt, destroyedAt,
bytesReceived, bytesSent, packetsReceived, packetsSent,
serverSessions, clientSessions, serverBusyCount, retryCount,
retryRateLimited, versionNegotiationCount,
versionNegotiationRateLimited, statelessResetCount,
statelessResetRateLimited, immediateCloseCount,
immediateCloseRateLimited, sessionCreationRateLimited, packetsBlocked.
endpointOptions
| Option | Default | Notes |
|---|---|---|
address |
IPv4 localhost, random port | |
blockList, blockListPolicy |
'deny' |
A net.BlockList checked before any QUIC processing. Edits take effect live. 'allow' makes it an allowlist. |
retryRate/retryBurst, statelessResetRate/Burst, versionNegotiationRate/Burst, immediateCloseRate/Burst |
100/s, burst 200 | Global token buckets for stateless responses |
sessionCreationRate/Burst |
50/s, burst 100 | Per validated remote address. Raise these for single-source benchmarks. |
maxConnectionsPerHost, maxConnectionsTotal |
0 (unlimited) | |
idleTimeout (s) |
0 | v26.2.0, v24.20.0 |
reusePort |
false | v26.3.0, v24.18.0 |
disableStatelessReset |
v26.2.0, v24.20.0 | |
ipv6Only, addressLRUSize, validateAddress, retryTokenExpiration, tokenExpiration, resetTokenSecret/tokenSecret (16 bytes), udpReceiveBufferSize, udpSendBufferSize, udpTTL |
v23.8.0 |
QuicSession
Events are callback properties, and each can be sync or async. If a
callback throws or rejects, the session is destroyed (for stream callbacks,
the stream), after onerror is called. If onerror itself throws, the
error becomes an uncaught exception.
- Callbacks:
onstream,ondatagram,ondatagramstatus('acknowledged','lost'or'abandoned'),onearlyrejected,onpathvalidation,onsessionticket,onversionnegotiation,onhandshake,onnewtoken,onorigin,ongoaway,onkeylog,onqlog,onapplication,onerror. - If
onstreamis unset and nothing else consumes the stream, incoming streams are destroyed with a warning. openedresolves to{ local, remote, servername, protocol, cipher, cipherVersion, validationErrorReason, validationErrorCode, earlyDataAttempted, earlyDataAccepted }.- Verified: on success, the two
validationError*keys are absent, not''and0. - Verified: with
verifyPeer: 'manual',validationErrorCodeis a string such as'DEPTH_ZERO_SELF_SIGNED_CERT', not the documented number.
- Verified: on success, the two
close({ code, type: 'transport' | 'application', reason })lets streams finish, then destroys the session. A non-zerocoderejects withERR_QUIC_TRANSPORT_ERRORorERR_QUIC_APPLICATION_ERROR.destroy([err[, opts]])is immediate.closedandclosingtrack the state.createBidirectionalStream(opts)andcreateUnidirectionalStream(opts)return Promises for aQuicStream. Options:bodyheaders,onheaders,ontrailers,oninfo,onwanttrailers(HTTP/3 only)priority('high','default'or'low') andincrementalbudget, default 65536 bytes of writer buffering
sendDatagram(data[, enc])returns a Promise for a bigint id. It resolves to0ninstead of throwing when the datagram is too large, unsupported, empty, or the session closed.maxDatagramSizeandmaxPendingDatagrams.- Also:
path,servername,alpnProtocol,certificate,peerCertificate,ephemeralKeyInfo,localTransportParams,remoteTransportParams,applicationOptions,endpoint,updateKey(),stats, and[Symbol.asyncDispose].
session.stats fields (bigint): createdAt, closingAt,
handshakeCompletedAt, handshakeConfirmedAt, bytesReceived, bytesSent,
bidiInStreamCount, bidiOutStreamCount, uniInStreamCount,
uniOutStreamCount, maxBytesInFlight, bytesInFlight, blockCount,
cwnd, latestRtt, minRtt, rttVar, smoothedRtt, ssthresh,
datagramsReceived, datagramsSent, datagramsAcknowledged,
datagramsLost, streamsIdleTimedOut.
sessionOptions (shared by connect and listen)
TLS (verified):
alpn: a string on the client, a non-empty array on the server. The default is'h3', and'h3'/'h3-*'select HTTP/3. A mismatch fails withERR_QUIC_TRANSPORT_ERROR"no application protocol".sni(server, required):{ host | '*': { keys: [KeyObject], certs: [PEM bytes], verifyPrivateKey, port, authoritative } }. Without'*', an unknown name getsunrecognized_name. Verified: a missingsnithrowsERR_MISSING_ARGS, PEM strings throwERR_INVALID_ARG_TYPE, PEM strings as keys are rejected, and DER bytes incertsfail with "Invalid certificate".ca(bytes),certs/keys(client cert auth),verifyClient,servername(default'localhost').verifyPeer:'strict'aborts in TLS;'auto'(default) rejectsopenedon validation failure (verified for a self-signed cert with noca);'manual'resolves and lets you checkvalidationError*(verified).
TLS (docs only):
rejectUnauthorized(default true).ciphers,groups,crl.certificateCompression(['zlib' | 'brotli' | 'zstd'], v26.6.0, v24.20.0). It helps keep the certificate under the 3× anti-amplification limit. Prefer ECDSA P-256 certificates.keylog,tlsTrace,qlog.
Resumption:
sessionTicket(fromonsessionticket) andtoken(fromonnewtoken).enableEarlyData(default true). On the server, 0-RTT streams havestream.early === true. If the server rejects 0-RTT, it destroys those streams and firesonearlyrejected. Early data can be replayed, so keep it idempotent.
Transport:
transportParams:initialMaxData,initialMaxStreamData{BidiLocal, BidiRemote,Uni},initialMaxStreams{Bidi,Uni},maxIdleTimeout,maxDatagramFrameSize(default 1200; 0 disables datagrams),activeConnectionIDLimit,ackDelayExponent,maxAckDelay,preferredAddressIpv4/6.cc('reno','cubic'or'bbr'),maxPayloadSize,maxWindow,maxStreamWindow,unacknowledgedPacketThreshold,handshakeTimeout.keepAlive(ms, default 0),initialRtt,streamIdleTimeout(default 30000 ms),drainingPeriodMultiplier(default 3).datagramDropPolicy(default'drop-oldest'),maxDatagramSendAttempts(default 5),truncatedReads('error'or'ignore').preferredAddressPolicy(default'ignore'),version,minVersion,reuseEndpoint.
HTTP/3 (application): maxHeaderPairs (128), maxHeaderLength
(8192), maxFieldSectionSize, qpackMaxDTableCapacity (4096),
qpackEncoderMaxDTableCapacity, qpackBlockedStreams (100),
enableConnectProtocol, enableDatagrams. Both peers need
enableDatagrams to use HTTP/3 datagrams.
Listen-level onheaders, ontrailers and similar apply to every incoming
stream. For HTTP/3 you must set them there, because setting them in
onstream is too late.
QuicStream
- Reading (verified): use
for await (const chunks of stream), which yieldsUint8Array[]batches. Only one iterator is allowed per stream. It also works withnode:stream/iterbytes(),text(),pipeTo()anddump(). Reading returns flow-control credit, so always drain a stream. - Writing, one way per stream:
body/setBody(x)takes a string,ArrayBuffer(View),Blob,FileHandle, sync or async iterable,Promise, ornull(FIN at once). Verified with a string. The bytes are copied.stream.writerhaswriteSync(returns false when full),writeandwritev(these reject withERR_INVALID_STATEwhen full; they don't wait),endSync,end,fail(reason)(sendsRESET_STREAMand uses aQuicError'serrorCode), andcanWrite. Wait for space withondrain(writer)fromnode:stream/iter.
- Members:
id,direction,early,budget,session,opened(v26.10.0),closed,destroy([err[, opts]]),destroyed,resetStream([code]),stopSending([code]),priority,setPriority(),headers,pendingTrailers,sendHeaders(h, { terminal }),sendInformationalHeaders,sendTrailers, andstats. - Callbacks:
onerror,onblocked,onreset,onstopsending,onheaders,ontrailers,oninfo,onwanttrailers. stream.statsfields:ackedAt,bytesAccumulated,bytesReceived,bytesSent,createdAt,destroyedAt,finalSize,isConnected,maxBytesAccumulated,maxOffset,maxOffsetAcknowledged,maxOffsetReceived,openedAt,receivedAt.
HTTP/3 (docs)
'h3'is the default ALPN.- A request is
createBidirectionalStream({ headers: { ':method', ':path', ':scheme', ':authority' }, onheaders }). With nobody, the HEADERS frame ends the stream. - Incoming
:statusis converted to a number. - On the server, use
this.sendHeaders({ ':status': '200' })insideonheaders, then write throughthis.writer. - ORIGIN frames come from
snientries.close()sendsGOAWAY. - Not implemented: server push, WebTransport helpers, and any HTTP semantics such as routing, redirects, cookies or content encoding.
Diagnostics and permissions
PerformanceObserverentries useentryType: 'quic', namedQuicEndpoint,QuicSessionorQuicStream(v26.2.0, v24.20.0).- Diagnostics channels:
quic.endpoint.{created,listen,connect,closing,closed,error,busy.change},quic.session.{created.client,created.server,open.stream,received.stream,handshake,closing,closed,error,ticket,new.token,goaway,early.rejected,…}andquic.stream.{closed,headers,trailers,info,reset,blocked}. - With
--permission,connect()andlisten()reject withERR_ACCESS_DENIEDunless you pass--allow-net(verified).