QUIC#

Stability: 1.0 - Early development

Source Code: lib/quic.js

The 'node:quic' module provides an implementation of the QUIC protocol. To access it, start Node.js with the --experimental-quic option and:

import quic from 'node:quic';const quic = require('node:quic');

The module is only available under the node: scheme.

quic.connect(address[, options])#

Initiate a new client-side session.

import { connect } from 'node:quic';
import { Buffer } from 'node:buffer';

const enc = new TextEncoder();
const alpn = 'foo';
const client = await connect('123.123.123.123:8888', { alpn });
await client.createUnidirectionalStream({
  body: enc.encode('hello world'),
}); 

By default, every call to connect(...) will create a new local QuicEndpoint instance bound to a new random local IP port. To specify the exact local address to use, or to multiplex multiple QUIC sessions over a single local port, pass the endpoint option with either a QuicEndpoint or EndpointOptions as the argument.

import { QuicEndpoint, connect } from 'node:quic';

const endpoint = new QuicEndpoint({
  address: '127.0.0.1:1234',
});

const client = await connect('123.123.123.123:8888', { endpoint }); 

quic.listen(onsession,[options])#

Configures the endpoint to listen as a server. When a new session is initiated by a remote peer, the given onsession callback will be invoked with the created session.

import { listen } from 'node:quic';

const endpoint = await listen((session) => {
  // ... handle the session
});

// Closing the endpoint allows any sessions open when close is called
// to complete naturally while preventing new sessions from being
// initiated. Once all existing sessions have finished, the endpoint
// will be destroyed. The call returns a promise that is resolved once
// the endpoint is destroyed.
await endpoint.close(); 

By default, every call to listen(...) will create a new local QuicEndpoint instance bound to a new random local IP port. To specify the exact local address to use, or to multiplex multiple QUIC sessions over a single local port, pass the endpoint option with either a QuicEndpoint or EndpointOptions as the argument.

At most, any single QuicEndpoint can only be configured to listen as a server once.

Class: QuicEndpoint#

A QuicEndpoint encapsulates the local UDP-port binding for QUIC. It can be used as both a client and a server.

new QuicEndpoint([options])#

endpoint.address#

The local UDP socket address to which the endpoint is bound, if any.

If the endpoint is not currently bound then the value will be undefined. Read only.

endpoint.busy#

When endpoint.busy is set to true, the endpoint will temporarily reject new sessions from being created. Read/write.

// Mark the endpoint busy. New sessions will be prevented.
endpoint.busy = true;

// Mark the endpoint free. New session will be allowed.
endpoint.busy = false; 

The busy property is useful when the endpoint is under heavy load and needs to temporarily reject new sessions while it catches up.

endpoint.close()#

Gracefully close the endpoint. The endpoint will close and destroy itself when all currently open sessions close. Once called, new sessions will be rejected.

Returns a promise that is fulfilled when the endpoint is destroyed.

endpoint.closed#

A promise that is fulfilled when the endpoint is destroyed. This will be the same promise that is returned by the endpoint.close() function. Read only.

endpoint.closing#

True if endpoint.close() has been called and closing the endpoint has not yet completed. Read only.

endpoint.destroy([error])#

Forcefully closes the endpoint by forcing all open sessions to be immediately closed.

endpoint.destroyed#

True if endpoint.destroy() has been called. Read only.

endpoint.stats#

The statistics collected for an active session. Read only.

endpoint[Symbol.asyncDispose]()#

Calls endpoint.close() and returns a promise that fulfills when the endpoint has closed.

Class: QuicEndpoint.Stats#

A view of the collected statistics for an endpoint.

endpointStats.createdAt#

  • <bigint> A timestamp indicating the moment the endpoint was created. Read only.

endpointStats.destroyedAt#

  • <bigint> A timestamp indicating the moment the endpoint was destroyed. Read only.

endpointStats.bytesReceived#

  • <bigint> The total number of bytes received by this endpoint. Read only.

endpointStats.bytesSent#

  • <bigint> The total number of bytes sent by this endpoint. Read only.

endpointStats.packetsReceived#

  • <bigint> The total number of QUIC packets successfully received by this endpoint. Read only.

endpointStats.packetsSent#

  • <bigint> The total number of QUIC packets successfully sent by this endpoint. Read only.

endpointStats.serverSessions#

  • <bigint> The total number of peer-initiated sessions received by this endpoint. Read only.

endpointStats.clientSessions#

  • <bigint> The total number of sessions initiated by this endpoint. Read only.

endpointStats.serverBusyCount#

  • <bigint> The total number of times an initial packet was rejected due to the endpoint being marked busy. Read only.

endpointStats.retryCount#

  • <bigint> The total number of QUIC retry attempts on this endpoint. Read only.

endpointStats.versionNegotiationCount#

  • <bigint> The total number sessions rejected due to QUIC version mismatch. Read only.

endpointStats.statelessResetCount#

  • <bigint> The total number of stateless resets handled by this endpoint. Read only.

endpointStats.immediateCloseCount#

  • <bigint> The total number of sessions that were closed before handshake completed. Read only.

Class: QuicSession#

A QuicSession represents the local side of a QUIC connection.

session.close()#

Initiate a graceful close of the session. Existing streams will be allowed to complete but no new streams will be opened. Once all streams have closed, the session will be destroyed. The returned promise will be fulfilled once the session has been destroyed.

session.closed#

A promise that is fulfilled once the session is destroyed.

session.destroy([error])#

Immediately destroy the session. All streams will be destroys and the session will be closed.

session.destroyed#

True if session.destroy() has been called. Read only.

session.endpoint#

The endpoint that created this session. Read only.

session.onstream#

The callback to invoke when a new stream is initiated by a remote peer. Read/write.

session.ondatagram#

The callback to invoke when a new datagram is received from a remote peer. Read/write.

session.ondatagramstatus#

The callback to invoke when the status of a datagram is updated. Read/write.

session.onpathvalidation#

The callback to invoke when the path validation is updated. Read/write.

seesion.onsessionticket#

The callback to invoke when a new session ticket is received. Read/write.

session.onversionnegotiation#

The callback to invoke when a version negotiation is initiated. Read/write.

session.onhandshake#

The callback to invoke when the TLS handshake is completed. Read/write.

session.createBidirectionalStream([options])#

Open a new bidirectional stream. If the body option is not specified, the outgoing stream will be half-closed.

session.createUnidirectionalStream([options])#

Open a new unidirectional stream. If the body option is not specified, the outgoing stream will be closed.

session.path#

The local and remote socket addresses associated with the session. Read only.

session.sendDatagram(datagram)#

Sends an unreliable datagram to the remote peer, returning the datagram ID. If the datagram payload is specified as an ArrayBufferView, then ownership of that view will be transfered to the underlying stream.

session.stats#

Return the current statistics for the session. Read only.

session.updateKey()#

Initiate a key update for the session.

session[Symbol.asyncDispose]()#

Calls session.close() and returns a promise that fulfills when the session has closed.

Class: QuicSession.Stats#

sessionStats.createdAt#

sessionStats.closingAt#

sessionStats.handshakeCompletedAt#

sessionStats.handshakeConfirmedAt#

sessionStats.bytesReceived#

sessionStats.bytesSent#

sessionStats.bidiInStreamCount#

sessionStats.bidiOutStreamCount#

sessionStats.uniInStreamCount#

sessionStats.uniOutStreamCount#

sessionStats.maxBytesInFlights#

sessionStats.bytesInFlight#

sessionStats.blockCount#

sessionStats.cwnd#

sessionStats.latestRtt#

sessionStats.minRtt#

sessionStats.rttVar#

sessionStats.smoothedRtt#

sessionStats.ssthresh#

sessionStats.datagramsReceived#

sessionStats.datagramsSent#

sessionStats.datagramsAcknowledged#

sessionStats.datagramsLost#

Class: QuicStream#

stream.closed#

A promise that is fulfilled when the stream is fully closed.

stream.destroy([error])#

Immediately and abruptly destroys the stream.

stream.destroyed#

True if stream.destroy() has been called.

stream.direction#

  • <string> One of either 'bidi' or 'uni'.

The directionality of the stream. Read only.

stream.id#

The stream ID. Read only.

stream.onblocked#

The callback to invoke when the stream is blocked. Read/write.

stream.onreset#

The callback to invoke when the stream is reset. Read/write.

stream.readable#

stream.session#

The session that created this stream. Read only.

stream.stats#

The current statistics for the stream. Read only.

Class: QuicStream.Stats#

streamStats.ackedAt#

streamStats.bytesReceived#

streamStats.bytesSent#

streamStats.createdAt#

streamStats.destroyedAt#

streamStats.finalSize#

streamStats.isConnected#

streamStats.maxOffset#

streamStats.maxOffsetAcknowledged#

streamStats.maxOffsetReceived#

streamStats.openedAt#

streamStats.receivedAt#

Types#

Type: EndpointOptions#

The endpoint configuration options passed when constructing a new QuicEndpoint instance.

endpointOptions.address#

If not specified the endpoint will bind to IPv4 localhost on a random port.

endpointOptions.addressLRUSize#

The endpoint maintains an internal cache of validated socket addresses as a performance optimization. This option sets the maximum number of addresses that are cache. This is an advanced option that users typically won't have need to specify.

endpointOptions.ipv6Only#

When true, indicates that the endpoint should bind only to IPv6 addresses.

endpointOptions.maxConnectionsPerHost#

Specifies the maximum number of concurrent sessions allowed per remote peer address.

endpointOptions.maxConnectionsTotal#

Specifies the maximum total number of concurrent sessions.

endpointOptions.maxRetries#

Specifies the maximum number of QUIC retry attempts allowed per remote peer address.

endpointOptions.maxStatelessResetsPerHost#

Specifies the maximum number of stateless resets that are allowed per remote peer address.

endpointOptions.retryTokenExpiration#

Specifies the length of time a QUIC retry token is considered valid.

endpointOptions.resetTokenSecret#

Specifies the 16-byte secret used to generate QUIC retry tokens.

endpointOptions.tokenExpiration#

Specifies the length of time a QUIC token is considered valid.

endpointOptions.tokenSecret#

Specifies the 16-byte secret used to generate QUIC tokens.

endpointOptions.udpReceiveBufferSize#
endpointOptions.udpSendBufferSize#
endpointOptions.udpTTL#
endpointOptions.validateAddress#

When true, requires that the endpoint validate peer addresses using retry packets while establishing a new connection.

Type: SessionOptions#

sessionOptions.alpn#

The ALPN protocol identifier.

sessionOptions.ca#

The CA certificates to use for sessions.

sessionOptions.cc#

Specifies the congestion control algorithm that will be used . Must be set to one of either 'reno', 'cubic', or 'bbr'.

This is an advanced option that users typically won't have need to specify.

sessionOptions.certs#

The TLS certificates to use for sessions.

sessionOptions.ciphers#

The list of supported TLS 1.3 cipher algorithms.

sessionOptions.crl#

The CRL to use for sessions.

sessionOptions.groups#

The list of support TLS 1.3 cipher groups.

sessionOptions.keylog#

True to enable TLS keylogging output.

sessionOptions.keys#

The TLS crypto keys to use for sessions.

sessionOptions.maxPayloadSize#

Specifies the maximum UDP packet payload size.

sessionOptions.maxStreamWindow#

Specifies the maximum stream flow-control window size.

sessionOptions.maxWindow#

Specifies the maxumum session flow-control window size.

sessionOptions.minVersion#

The minimum QUIC version number to allow. This is an advanced option that users typically won't have need to specify.

sessionOptions.preferredAddressPolicy#
  • <string> One of 'use', 'ignore', or 'default'.

When the remote peer advertises a preferred address, this option specifies whether to use it or ignore it.

sessionOptions.qlog#

True if qlog output should be enabled.

sessionOptions.sessionTicket#
sessionOptions.handshakeTimeout#

Specifies the maximum number of milliseconds a TLS handshake is permitted to take to complete before timing out.

sessionOptions.sni#

The peer server name to target.

sessionOptions.tlsTrace#

True to enable TLS tracing output.

sessionOptions.transportParams#

The QUIC transport parameters to use for the session.

sessionOptions.unacknowledgedPacketThreshold#

Specifies the maximum number of unacknowledged packets a session should allow.

sessionOptions.verifyClient#

True to require verification of TLS client certificate.

sessionOptions.verifyPrivateKey#

True to require private key verification.

sessionOptions.version#

The QUIC version number to use. This is an advanced option that users typically won't have need to specify.

Type: TransportParams#

transportParams.preferredAddressIpv4#
transportParams.preferredAddressIpv6#
transportParams.initialMaxStreamDataBidiLocal#
transportParams.initialMaxStreamDataBidiRemote#
transportParams.initialMaxStreamDataUni#
transportParams.initialMaxData#
transportParams.initialMaxStreamsBidi#
transportParams.initialMaxStreamsUni#
transportParams.maxIdleTimeout#
transportParams.activeConnectionIDLimit#
transportParams.ackDelayExponent#
transportParams.maxAckDelay#
transportParams.maxDatagramFrameSize#

Callbacks#

Callback: OnSessionCallback#

The callback function that is invoked when a new session is initiated by a remote peer.

Callback: OnStreamCallback#

Callback: OnDatagramCallback#

Callback: OnDatagramStatusCallback#

Callback: OnPathValidationCallback#

Callback: OnSessionTicketCallback#

Callback: OnVersionNegotiationCallback#

Callback: OnHandshakeCallback#

Callback: OnBlockedCallback#

Callback: OnStreamErrorCallback#

Diagnostic Channels#

Channel: quic.endpoint.created#

Channel: quic.endpoint.listen#

Channel: quic.endpoint.closing#

Channel: quic.endpoint.closed#

Channel: quic.endpoint.error#

Channel: quic.endpoint.busy.change#

Channel: quic.session.created.client#

Channel: quic.session.created.server#

Channel: quic.session.open.stream#

Channel: quic.session.received.stream#

Channel: quic.session.send.datagram#

Channel: quic.session.update.key#

Channel: quic.session.closing#

Channel: quic.session.closed#

Channel: quic.session.receive.datagram#

Channel: quic.session.receive.datagram.status#

Channel: quic.session.path.validation#

Channel: quic.session.ticket#

Channel: quic.session.version.negotiation#

Channel: quic.session.handshake#