connect

Bun

Symbol

connect

function connect<Data = undefined>(options: TCPSocketConnectOptions<Data>): Promise<Socket<Data>>

Create a TCP client that connects to a server via a TCP socket

function connect<Data = undefined>(options: UnixSocketOptions<Data>): Promise<Socket<Data>>

Create a TCP client that connects to a server via a unix socket

Referenced types

interface TCPSocketConnectOptions<Data = undefined>

  • allowHalfOpen?: boolean

    Whether to allow half-open connections.

    A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

    • The socket won't automatically send FIN when the remote side closes its end
    • The local side can continue sending data even after the remote side has closed
    • The application must explicitly call end() to fully close the connection

    When false (default), the socket automatically closes both ends of the connection when either side closes.

  • data?: Data

    The per-instance data context

  • exclusive?: boolean

    Whether to use exclusive mode.

    When set to true, the socket binds exclusively to the specified address:port combination, preventing other processes from binding to the same port.

    When false (default), other sockets may be able to bind to the same port depending on the operating system's socket sharing capabilities and settings.

    Exclusive mode is useful in scenarios where you want to ensure only one instance of your server can bind to a specific port at a time.

  • hostname: string

    The hostname to connect to

  • port: number

    The port to connect to

  • socket: SocketHandler<Data>

    Handlers for socket events

  • tls?: boolean

    TLS Configuration with which to create the socket

interface Socket<Data = undefined>

  • readonly alpnProtocol: null | string | false

    String containing the selected ALPN protocol. Before a handshake has completed, this value is always null. When a handshake is completed but not ALPN protocol was selected, socket.alpnProtocol equals false.

  • readonly authorized: boolean

    This property is true if the peer certificate was signed by one of the CAs specified when creating the Socket instance, otherwise false.

  • readonly bytesWritten: number

    The number of bytes written to the socket.

  • data: Data

    The data context for the socket.

  • readonly listener?: SocketListener<undefined>

    Get the server that created this socket

    This will return undefined if the socket was created by Bun.connect or if the listener has already closed.

  • readonly localAddress: string
  • readonly localFamily: 'IPv4' | 'IPv6'
  • readonly localPort: number

    local port connected to the socket

  • readonly readyState: 'open' | 'closed' | 'closing'
  • readonly remoteAddress: string

    Remote IP address connected to the socket

  • readonly remoteFamily: 'IPv4' | 'IPv6'
  • readonly remotePort: number
  • Disables TLS renegotiation for this Socket instance. Once called, attempts to renegotiate will trigger an error handler on the Socket.

    There is no support for renegotiation as a server. (Attempts by clients will result in a fatal alert so that ClientHello messages cannot be used to flood a server and escape higher-level limits.)

  • end(data?: string | BufferSource, byteOffset?: number, byteLength?: number): number

    Like Socket.write except it includes a TCP FIN packet

    Use it to send your last message and close the connection.

    end(): void

    Close the socket immediately

  • exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer

    Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.

    Example

    const keyingMaterial = socket.exportKeyingMaterial(
      128,
      'client finished');
    
    /*
     Example return value of keyingMaterial:
     <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
        12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
        74 ef 2c ... 78 more bytes>
    
    
    @param length

    number of bytes to retrieve from keying material

    @param label
    @param context

    Optionally provide a context.

    @returns

    requested bytes of the keying material

  • flush(): void

    Flush any buffered data to the socket

  • Returns the reason why the peer's certificate was not been verified. This property is set only when socket.authorized === false.

  • getCertificate(): null | object | PeerCertificate

    Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

    If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

  • getCipher(): CipherNameAndProtocol

    Returns an object containing information on the negotiated cipher suite.

    For example, a TLSv1.2 protocol with AES256-SHA cipher:

    {
        "name": "AES256-SHA",
        "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
        "version": "SSLv3"
    }
    
  • getEphemeralKeyInfo(): null | object | EphemeralKeyInfo

    Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. Thename property is available only when type is 'ECDH'.

    For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

  • getPeerCertificate(): PeerCertificate

    Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

    If the full certificate chain was requested, each certificate will include anissuerCertificate property containing an object representing its issuer's certificate.

    @returns

    A certificate object.

  • getPeerX509Certificate(): X509Certificate
  • getSharedSigalgs(): string[]
    @returns

    List of signature algorithms shared between the server and the client in the order of decreasing preference.

  • getTLSFinishedMessage(): undefined | Buffer<ArrayBufferLike>

    As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

    @returns

    The latest Finished message that has been sent to the socket as part of a SSL/TLS handshake, or undefined if no Finished message has been sent yet.

  • getTLSPeerFinishedMessage(): undefined | Buffer<ArrayBufferLike>

    As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

    @returns

    The latest Finished message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or undefined if there is no Finished message so far.

  • getTLSTicket(): undefined | Buffer<ArrayBufferLike>

    For a client, returns the TLS session ticket if one is available, orundefined. For a server, always returns undefined.

    It may be useful for debugging.

    See Session Resumption for more information.

  • getTLSVersion(): string

    Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.

    Protocol versions are:

    • 'SSLv3'
    • 'TLSv1'
    • 'TLSv1.1'
    • 'TLSv1.2'
    • 'TLSv1.3'
  • getX509Certificate(): undefined | X509Certificate
  • isSessionReused(): boolean

    See Session Resumption for more information.

    @returns

    true if the session was reused, false otherwise.

  • ref(): void

    Keep Bun's process alive at least until this socket is closed

    After the socket has closed, the socket is unref'd, the process may exit, and this becomes a no-op

  • reload(handler: SocketHandler): void

    Reset the socket's callbacks. This is useful with bun --hot to facilitate hot reloading.

    This will apply to all sockets from the same Listener. it is per socket only for Bun.connect.

  • setKeepAlive(enable?: boolean, initialDelay?: number): boolean

    Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Only available for already connected sockets, will return false otherwise.

    Enabling the keep-alive functionality will set the following socket options: SO_KEEPALIVE=1 TCP_KEEPIDLE=initialDelay TCP_KEEPCNT=10 TCP_KEEPINTVL=1

    @param enable

    Default: false

    @param initialDelay

    Default: 0

    @returns

    true if is able to setNoDelay and false if it fails.

  • setMaxSendFragment(size?: number): boolean

    The socket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.

    Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.

    @param size

    The maximum TLS fragment size. The maximum value is 16384.

  • setNoDelay(noDelay?: boolean): boolean

    Enable/disable the use of Nagle's algorithm. Only available for already connected sockets, will return false otherwise

    @param noDelay

    Default: true

    @returns

    true if is able to setNoDelay and false if it fails.

  • shutdown(halfClose?: boolean): void

    Shutdown writes to a socket

    This makes the socket a half-closed socket. It can still receive data.

    This calls shutdown(2) internally

  • terminate(): void

    Forcefully close the socket. The other end may not receive all data, and the socket will be closed immediately.

    This passes SO_LINGER with l_onoff set to 1 and l_linger set to 0 and then calls close(2).

  • timeout(seconds: number): void

    Set a timeout until the socket automatically closes.

    To reset the timeout, call this function again.

    When a timeout happens, the timeout callback is called and the socket is closed.

  • unref(): void

    Allow Bun's process to exit even if this socket is still open

    After the socket has closed, this function does nothing.

  • write(data: string | BufferSource, byteOffset?: number, byteLength?: number): number

    Write data to the socket

    @param data

    The data to write to the socket

    @param byteOffset

    The offset in the buffer to start writing from (defaults to 0)

    @param byteLength

    The number of bytes to write (defaults to the length of the buffer)

    When passed a string, byteOffset and byteLength refer to the UTF-8 offset, not the string character offset.

    This is unbuffered as of Bun v0.2.2. That means individual write() calls will be slow. In the future, Bun will buffer writes and flush them at the end of the tick, when the event loop is idle, or sooner if the buffer is full.

interface UnixSocketOptions<Data = undefined>

  • data?: Data

    The per-instance data context

  • socket: SocketHandler<Data>

    Handlers for socket events

  • tls?: TLSOptions

    TLS Configuration with which to create the socket

  • unix: string

    The unix socket to listen on or connect to