Bun

Node.js module

node:quic

  • namespace constants

  • namespace QuicEndpoint

    • class Stats

      A view of the collected statistics for an endpoint.

      • readonly bytesReceived: bigint

        The total number of bytes received by this endpoint. Read only.

      • readonly bytesSent: bigint

        The total number of bytes sent by this endpoint. Read only.

      • readonly clientSessions: bigint

        The total number of sessions initiated by this endpoint. Read only.

      • readonly createdAt: bigint

        A timestamp indicating the moment the endpoint was created. Read only.

      • readonly destroyedAt: bigint

        A timestamp indicating the moment the endpoint was destroyed. Read only.

      • readonly immediateCloseCount: bigint

        The total number of sessions that were closed before handshake completed. Read only.

      • readonly packetsReceived: bigint

        The total number of QUIC packets successfully received by this endpoint. Read only.

      • readonly packetsSent: bigint

        The total number of QUIC packets successfully sent by this endpoint. Read only.

      • readonly retryCount: bigint

        The total number of QUIC retry attempts on this endpoint. Read only.

      • readonly serverBusyCount: bigint

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

      • readonly serverSessions: bigint

        The total number of peer-initiated sessions received by this endpoint. Read only.

      • readonly statelessResetCount: bigint

        The total number of stateless resets handled by this endpoint. Read only.

      • readonly versionNegotiationCount: bigint

        The total number sessions rejected due to QUIC version mismatch. Read only.

  • namespace QuicSession

  • namespace QuicStream

  • class QuicEndpoint

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

    • readonly address: undefined | SocketAddress

      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.

    • busy: boolean

      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.

    • readonly closed: Promise<void>

      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.

    • readonly closing: boolean

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

    • readonly destroyed: boolean

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

    • readonly listening: boolean

      True if the endpoint is actively listening for incoming connections. Read only.

    • readonly stats: Stats

      The statistics collected for an active session. Read only.

    • [Symbol.asyncDispose](): Promise<void>;

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

    • close(): Promise<void>;

      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.

    • error?: any
      ): void;

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

    • entries: Record<string, SNIEntry>,
      ): void;

      Replaces or updates the SNI TLS contexts for this endpoint. This allows changing the TLS identity (key/certificate) used for specific host names without restarting the endpoint. Existing sessions are unaffected — only new sessions will use the updated contexts.

      endpoint.setSNIContexts({
        'api.example.com': { keys: [newApiKey], certs: [newApiCert] },
      });
      
      // Replace the entire SNI map
      endpoint.setSNIContexts({
        'api.example.com': { keys: [newApiKey], certs: [newApiCert] },
      }, { replace: true });
      
      @param entries

      An object mapping host names to TLS identity options. Each entry must include keys and certs.

  • class QuicSession

    A QuicSession represents the local side of a QUIC connection.

    • readonly closed: Promise<void>

      A promise that is fulfilled once the session is destroyed.

    • readonly destroyed: boolean

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

    • readonly endpoint: QuicEndpoint

      The endpoint that created this session. Read only.

    • ondatagram: undefined | OnDatagramCallback

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

    • ondatagramstatus: undefined | OnDatagramStatusCallback

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

    • onhandshake: undefined | OnHandshakeCallback

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

    • onpathvalidation: undefined | OnPathValidationCallback

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

    • onsessionticket: undefined | OnSessionTicketCallback

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

    • onstream: undefined | OnStreamCallback

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

    • onversionnegotiation: undefined | OnVersionNegotiationCallback

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

    • path: undefined | SessionPath

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

    • readonly stats: Stats

      Return the current statistics for the session. Read only.

    • [Symbol.asyncDispose](): Promise<void>;

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

    • close(): Promise<void>;

      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.

    • ): Promise<QuicStream>;

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

    • ): Promise<QuicStream>;

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

    • error?: any
      ): void;

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

    • datagram: string | ArrayBufferView<ArrayBufferLike>
      ): bigint;

      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 transferred to the underlying stream.

    • updateKey(): void;

      Initiate a key update for the session.

    • readonly closed: Promise<void>

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

    • readonly destroyed: boolean

      True if stream.destroy() has been called.

    • readonly direction: 'bidi' | 'uni'

      The directionality of the stream. Read only.

    • readonly id: bigint

      The stream ID. Read only.

    • onblocked: undefined | OnBlockedCallback

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

    • onreset: undefined | OnStreamErrorCallback

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

    • readonly readable: ReadableStream<Uint8Array<ArrayBufferLike>>
    • readonly session: QuicSession

      The session that created this stream. Read only.

    • readonly stats: Stats

      The current statistics for the stream. Read only.

    • error?: any
      ): void;

      Immediately and abruptly destroys the stream.

  • function connect(
    address: string | SocketAddress,
    options?: SessionOptions
    ): Promise<QuicSession>;

    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 });
    
  • function listen(
    onsession: OnSessionCallback,
    options?: SessionOptions
    ): Promise<QuicEndpoint>;

    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.

Type definitions

  • interface CreateStreamOptions

  • interface EndpointOptions

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

    • address?: string | SocketAddress

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

    • addressLRUSize?: number | bigint

      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.

    • ipv6Only?: boolean

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

    • maxConnectionsPerHost?: number | bigint

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

    • maxConnectionsTotal?: number | bigint

      Specifies the maximum total number of concurrent sessions.

    • maxRetries?: number | bigint

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

    • maxStatelessResetsPerHost?: number | bigint

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

    • resetTokenSecret?: ArrayBufferView<ArrayBufferLike>

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

    • retryTokenExpiration?: number | bigint

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

    • tokenExpiration?: number | bigint

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

    • tokenSecret?: ArrayBufferView<ArrayBufferLike>

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

    • udpTTL?: number
    • validateAddress?: boolean

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

  • interface SessionOptions

    • alpn?: string | readonly string[]

      The ALPN (Application-Layer Protocol Negotiation) identifier(s).

      For client sessions, this is a single string specifying the protocol the client wants to use (e.g. 'h3').

      For server sessions, this is an array of protocol names in preference order that the server supports (e.g. ['h3', 'h3-29']). During the TLS handshake, the server selects the first protocol from its list that the client also supports.

      The negotiated ALPN determines which Application implementation is used for the session. 'h3' and 'h3-*' variants select the HTTP/3 application; all other values select the default application.

    • ca?: ArrayBuffer | ArrayBufferView<ArrayBufferLike> | readonly unknown[]

      The CA certificates to use for client sessions. For server sessions, CA certificates are specified per-identity in the sessionOptions.sni map.

    • cc?: 'reno' | 'cubic' | 'bbr'

      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.

    • certs?: ArrayBuffer | ArrayBufferView<ArrayBufferLike> | readonly unknown[]

      The TLS certificates to use for client sessions. For server sessions, certificates are specified per-identity in the sessionOptions.sni map.

    • ciphers?: string

      The list of supported TLS 1.3 cipher algorithms.

    • crl?: ArrayBuffer | ArrayBufferView<ArrayBufferLike> | readonly unknown[]

      The CRL to use for client sessions. For server sessions, CRLs are specified per-identity in the sessionOptions.sni map.

    • endpoint?: QuicEndpoint | EndpointOptions

      An endpoint to use.

    • groups?: string

      The list of support TLS 1.3 cipher groups.

    • handshakeTimeout?: number | bigint

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

    • keylog?: boolean

      True to enable TLS keylogging output.

    • keys?: KeyObject | readonly KeyObject[]

      The TLS crypto keys to use for client sessions. For server sessions, keys are specified per-identity in the sessionOptions.sni map.

    • maxPayloadSize?: number | bigint

      Specifies the maximum UDP packet payload size.

    • maxStreamWindow?: number | bigint

      Specifies the maximum stream flow-control window size.

    • maxWindow?: number | bigint

      Specifies the maximum session flow-control window size.

    • minVersion?: number

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

    • preferredAddressPolicy?: 'ignore' | 'default' | 'use'

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

    • qlog?: boolean

      True if qlog output should be enabled.

    • servername?: string

      The peer server name to target (SNI). Defaults to 'localhost'.

    • sessionTicket?: ArrayBufferView<ArrayBufferLike>

      A session ticket to use for 0RTT session resumption.

    • sni?: Record<string, SNIEntry>

      An object mapping host names to TLS identity options for Server Name Indication (SNI) support. This is required for server sessions. The special key '*' specifies the default/fallback identity used when no other host name matches. Each entry may contain:

      const endpoint = await listen(callback, {
        sni: {
          '*': { keys: [defaultKey], certs: [defaultCert] },
          'api.example.com': { keys: [apiKey], certs: [apiCert] },
          'www.example.com': { keys: [wwwKey], certs: [wwwCert], ca: [customCA] },
        },
      });
      

      Shared TLS options (such as ciphers, groups, keylog, and verifyClient) are specified at the top level of the session options and apply to all identities. Each SNI entry overrides only the per-identity certificate fields.

      The SNI map can be replaced at runtime using endpoint.setSNIContexts(), which atomically swaps the map for new sessions while existing sessions continue to use their original identity.

    • tlsTrace?: boolean

      True to enable TLS tracing output.

    • transportParams?: TransportParams

      The QUIC transport parameters to use for the session.

    • unacknowledgedPacketThreshold?: number | bigint

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

    • verifyClient?: boolean

      True to require verification of TLS client certificate.

    • verifyPrivateKey?: boolean

      True to require private key verification for client sessions. For server sessions, this option is specified per-identity in the sessionOptions.sni map.

    • version?: number

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

  • interface SetSNIContextsOptions

  • interface SNIEntry

  • interface TransportParams

  • type OnBlockedCallback = (this: QuicStream) => void
  • type OnDatagramCallback = (this: QuicSession, datagram: Uint8Array, early: boolean) => void
  • type OnDatagramStatusCallback = (this: QuicSession, id: bigint, status: 'lost' | 'acknowledged') => void
  • type OnHandshakeCallback = (this: QuicSession, sni: string, alpn: string, cipher: string, cipherVersion: string, validationErrorReason: string, validationErrorCode: number, earlyDataAccepted: boolean) => void
  • type OnPathValidationCallback = (this: QuicSession, result: 'success' | 'failure' | 'aborted', newLocalAddress: SocketAddress, newRemoteAddress: SocketAddress, oldLocalAddress: SocketAddress, oldRemoteAddress: SocketAddress, preferredAddress: boolean) => void
  • type OnSessionCallback = (this: QuicEndpoint, session: QuicSession) => void
  • type OnSessionTicketCallback = (this: QuicSession, ticket: object) => void
  • type OnStreamCallback = (this: QuicSession, stream: QuicStream) => void
  • type OnStreamErrorCallback = (this: QuicStream, error: any) => void
  • type OnVersionNegotiationCallback = (this: QuicSession, version: number, requestedVersions: number[], supportedVersions: number[]) => void