ServerTransportBun WebSockets

Bun WebSockets

Colyseus supports Bun’s native WebSockets implementation through the @colyseus/bun-websockets package. This transport layer is designed for Bun’s built-in HTTP server. The package also provides an Express compatibility layer for easier integration with existing codebases.

⚠️

Bun support on Colyseus is still experimental. Please report any issues you may find.

Installation

Terminal
bun add @colyseus/bun-websockets
app.config.ts
import { defineServer } from "colyseus";
import { BunWebSockets } from "@colyseus/bun-websockets"
 
const server = defineServer({
  // ...
  transport: new BunWebSockets({
    /* Bun WebSocketHandler options (e.g. maxPayloadLength, idleTimeout) */
  }),
 
  //
  // BunWebSockets comes with Express compatibility layer.
  //
  express: (app) => {
    // register routes
    app.get("/hello", (req, res) => {
      res.json({ hello: "world!" });
    });
  },
  // ...
});

Transport options

This transport accepts Bun’s own WebSocketHandler options, plus the option below.

options.beforeUpgrade

Runs before the WebSocket handshake, while the connection is still a plain HTTP request.

beforeUpgrade?: (request: Request, context: AuthContext) => Response | void | Promise<Response | void>;

The callback receives the upgrade request as a standard Request, and the same context object onAuth receives: token, headers, and ip. The context is read-only here, and changes to it do not carry over to onAuth.

Return a Response to answer the request without upgrading, or nothing to accept the handshake. The callback may be async, and the handshake waits for it to resolve.

A callback that throws answers 500 Internal Server Error, and the connection is not upgraded.