Skip to main content
This is a low-level API intended for library authors and for advanced use cases.

Start a server (Bun.listen())

To start a TCP server with Bun.listen:
server.ts
In Bun, a set of handlers are declared once per server instead of assigning callbacks to each socket, as with Node.js EventEmitters or the web-standard WebSocket API.
server.ts
For performance-sensitive servers, assigning listeners to each socket can cause significant garbage collector pressure and increase memory usage. By contrast, Bun only allocates one handler function for each event and shares it among all sockets. This is a small optimization, but it adds up.
Contextual data can be attached to a socket in the open handler.
server.ts
To enable TLS, pass a tls object containing key and cert fields.
server.ts
The key and cert fields expect the contents of your TLS key and certificate. This can be a string, BunFile, TypedArray, or Buffer.
server.ts
The result of Bun.listen is a server that conforms to the TCPSocket interface.
server.ts

Create a connection (Bun.connect())

Use Bun.connect to connect to a TCP server. Specify the server to connect to with hostname and port. TCP clients can define the same set of handlers as Bun.listen, plus a couple client-specific handlers.
server.ts
To require TLS, specify tls: true.

Hot reloading

Both TCP servers and sockets can be hot reloaded with new handlers.

Buffering

Currently, TCP sockets in Bun do not buffer data. For performance-sensitive code, it’s important to consider buffering carefully. For example, this:
…performs significantly worse than this:
To simplify this for now, consider using Bun’s ArrayBufferSink with the {stream: true} option:
server.ts
CorkingSupport for corking is planned, but in the meantime backpressure must be managed manually with the drain handler.