Skip to main content
Bun provides fast, built-in WebSocket support via Bun.serve(). WebSocket connections are upgraded from HTTP requests and support pub/sub messaging, backpressure handling, and compression.

Basic WebSocket Server

WebSocket Handler Configuration

Message Handler

Binary Type

Upgrading HTTP Connections

Basic Upgrade

Upgrade with Custom Data

Upgrade with Custom Headers

Sending Messages

Send Text or Binary

Explicit Text/Binary

Send Status

All send methods return a status number:

Pub/Sub Messaging

Subscribe to Topics

Check Subscriptions

Unsubscribe

Publish from HTTP Handler

Subscriber Count

Ping/Pong

Automatic Pings

Connection Management

Closing Connections

Close Codes

  • 1000 - Normal closure (default)
  • 1009 - Message too big
  • 1011 - Server error
  • 1012 - Server restarting
  • 1013 - Try again later
  • 4000-4999 - Application-specific codes

Ready State

Remote Address

Backpressure and Buffering

Check Buffered Amount

Drain Handler

Called when backpressure is relieved:

Backpressure Limits

Corking

Batch multiple send operations:

Configuration Options

Compression

Compression levels: "disable", "shared", "dedicated", "3KB", "4KB", "8KB", "16KB", "32KB", "64KB", "128KB", "256KB"

Type Signatures