method
SocketHandler.error
Referenced types
interface Socket<Data = undefined>
A TCP or TLS socket connection.
Sockets are created with Bun.connect() or accepted by a Bun.listen() server.
- readonly alpnProtocol: null | string | false
The selected ALPN protocol.
Before a handshake has completed, this value is always
null. When a handshake has completed but no ALPN protocol was selected, this isfalse. - readonly bytesWritten: number
The total number of bytes successfully written to the socket since it was established. This includes data currently buffered by the OS but not yet acknowledged by the remote peer.
- data: Data
The user-defined data associated with this socket instance. Set it when the socket is created with
Bun.connect({ data: ... }). It can be read or updated at any time.// In a socket handler function open(socket: Socket<{ userId: string }>) { console.log(`Socket opened for user: ${socket.data.userId}`); socket.data.lastActivity = Date.now(); // Update data } - readonly listener?: SocketListener<undefined>
The server that created this socket
This is
undefinedif the socket was created by Bun.connect or if the listener has already closed. - readonly localAddress: string
Local IP address connected to the socket
"192.168.1.100" | "2001:db8::1" - readonly localFamily: 'IPv4' | 'IPv6'
IP protocol family used for the local endpoint of the socket
"IPv4" | "IPv6" - readonly readyState: -2 | -1 | 0 | 1 | 2
The ready state of the socket.
A positive value means the socket is open and usable
-2= Shutdown-1= Detached0= Closed1= Established2= Else
- readonly remoteAddress: string
Remote IP address connected to the socket
"192.168.1.100" | "2001:db8::1" - readonly remoteFamily: 'IPv4' | 'IPv6'
IP protocol family used for the remote endpoint of the socket
"IPv4" | "IPv6" Alias for
socket.end(). Allows the socket to be used withusingdeclarations for automatic resource management.async function processSocket() { using socket = await Bun.connect({ ... }); socket.write("Data"); // socket.end() is called automatically when exiting the scope }Closes the socket.
This is a wrapper around
end()andshutdown().Disables TLS renegotiation for this
Socketinstance. Once called, attempts to renegotiate will trigger anerrorhandler on theSocket.Bun does not support renegotiation as a server. (Attempts by clients result in a fatal alert so that ClientHello messages cannot be used to flood a server and escape higher-level limits.)
- end(byteOffset?: number,byteLength?: number): number;
Sends the final data chunk and initiates a graceful shutdown of the socket's write side. After calling
end(), no more data can be written usingwrite()orend(). The socket remains readable until the remote end also closes its write side or the connection is terminated. This sends a TCP FIN packet after writing the data.@param dataOptional final data to write before closing. Same types as
write().@param byteOffsetOptional offset for buffer data.
@param byteLengthOptional length for buffer data.
@returnsThe number of bytes written for the final chunk. Returns
-1if the socket was already closed or shutting down.// send some data and close the write side socket.end("Goodbye!"); // or close write side without sending final data socket.end();Close the socket immediately
- length: number,label: string,
Keying material is used for validations to prevent different kinds of attacks in network protocols, for example in the specifications of IEEE 802.1X.
@param lengthnumber of bytes to retrieve from keying material
@param labelan application specific label, typically this will be a value from the IANA Exporter Label Registry.
@param contextOptionally provide a context.
@returnsrequested bytes of the keying material
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>length: number,label: string,): void;Exports the keying material of the socket.
@param lengthThe length of the keying material to export.
@param labelThe label of the keying material to export.
@param contextThe context of the keying material to export.
Flush any buffered data to the socket
This attempts to send the data immediately, but success depends on the network conditions and the receiving end. It might be necessary after several
writecalls if immediate sending is critical, though the OS often handles flushing efficiently.writecalls outsideopen/data/drainmight benefit from manualcork/flush.Returns the reason why the peer's certificate was not verified. This is only set when
socket.authorized === false.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 is returned. If the socket has been destroyed,
nullis returned.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" }Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in
perfect forward secrecyon a client connection. It returns an empty object when the key exchange is not ephemeral. This is only supported on a client socket;nullis returned if called on a server socket. The supported types are'DH'and'ECDH'. Thenameproperty is available only when type is'ECDH'.For example:
{ type: 'ECDH', name: 'prime256v1', size: 256 }.Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object is returned. If the socket has been destroyed,
nullis returned.If the full certificate chain was requested, each certificate includes an
issuerCertificateproperty containing an object representing its issuer's certificate.@returnsA certificate object.
Returns the servername of the socket.
As the
Finishedmessages 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.@returnsThe latest
Finishedmessage that has been sent to the socket as part of a SSL/TLS handshake, orundefinedif noFinishedmessage has been sent yet.As the
Finishedmessages 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.@returnsThe latest
Finishedmessage that is expected or has actually been received from the socket as part of a SSL/TLS handshake, orundefinedif there is noFinishedmessage so far.For a client, returns the TLS session ticket if one is available, or
undefined. For a server, always returnsundefined.It may be useful for debugging.
See
Session Resumptionfor more information.Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value
'unknown'is returned for connected sockets that have not completed the handshaking process. The valuenullis returned for server sockets or disconnected client sockets.Protocol versions are:
'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
TLS only: Checks if the current TLS session was resumed from a previous session.
See
Session Resumptionfor more information.@returnstrueif the session was reused,falseotherwiseKeep 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
- ): void;
Reset the socket's callbacks. This is useful with
bun --hotfor hot reloading.This applies to all sockets from the same Listener. It is per socket only for Bun.connect.
If this is a TLS Socket
- 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. Setting0forinitialDelay(the default) will leave the value unchanged from the default (or previous) setting. Only available for already connected sockets; returnsfalseotherwise.Enabling the keep-alive functionality sets the following socket options: SO_KEEPALIVE=1 TCP_KEEPIDLE=initialDelay/1000 TCP_KEEPCNT=10 TCP_KEEPINTVL=1
@param enableDefault:
false@param initialDelayDefault:
0@returnstrueif it succeeds,falseif it fails - size?: number): boolean;
Sets the maximum TLS fragment size. Returns
trueif setting the limit succeeded;falseotherwise.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 sizeThe maximum TLS fragment size. The maximum value is
16384. - noDelay?: boolean): boolean;
Enable/disable the use of Nagle's algorithm. Only available for already connected sockets; returns
falseotherwise@param noDelayDefault:
true@returnstrueif it succeeds,falseif it fails - ): void;
Sets the session of the socket.
@param sessionThe session to set.
- requestCert: boolean,rejectUnauthorized: boolean): void;
Sets the verify mode of the socket.
@param requestCertWhether to request a certificate.
@param rejectUnauthorizedWhether to reject unauthorized certificates.
- halfClose?: boolean): void;
Shuts down the write-half or both halves of the connection. This allows the socket to enter a half-closed state where it can still receive data but can no longer send data (
halfClose = true), or close both read and write (halfClose = false, similar toend()but potentially more immediate depending on OS). Calls theshutdown(2)syscall internally.@param halfCloseIf
true, only shuts down the write side (allows receiving). Iffalseor omitted, shuts down both read and write. Defaults tofalse.// Stop sending data, but allow receiving socket.shutdown(true); // Shutdown both reading and writing socket.shutdown(); Forcefully closes the socket connection immediately. This is an abrupt termination, unlike the graceful shutdown initiated by
end(). It usesSO_LINGERwithl_onoff=1andl_linger=0before callingclose(2). Consider using close() or end() for graceful shutdowns.socket.terminate();- seconds: number): void;
Set a timeout until the socket automatically closes.
To reset the timeout, call this function again.
When a timeout happens, the
timeoutcallback is called and the socket is closed. Allow Bun's process to exit even if this socket is still open
After the socket has closed, this function does nothing.
Upgrades the socket to a TLS socket.
@param optionsThe options for the upgrade.
@returnsA tuple containing the raw socket and the TLS socket.
- byteOffset?: number,byteLength?: number): number;
Writes
datato the socket. This method is unbuffered and non-blocking. It uses thesendto(2)syscall internally.For best performance with many small writes, batch them into a single
socket.write()call.@param dataThe data to write. Can be a string (encoded as UTF-8),
ArrayBuffer,TypedArray, orDataView.@param byteOffsetThe offset in bytes within the buffer to start writing from. Defaults to 0. Ignored for strings.
@param byteLengthThe number of bytes to write from the buffer. Defaults to the remaining length of the buffer from the offset. Ignored for strings.
@returnsThe number of bytes written. Returns
-1if the socket is closed or shutting down. Can return less than the input size if the socket's buffer is full (backpressure).// Send a string const bytesWritten = socket.write("Hello, world!\n"); // Send binary data const buffer = new Uint8Array([0x01, 0x02, 0x03]); socket.write(buffer); // Send part of a buffer const largeBuffer = new Uint8Array(1024); // ... fill largeBuffer ... socket.write(largeBuffer, 100, 50); // Write 50 bytes starting from index 100