Websocket with Bun

I've tried everything but I can't get WebSockets to work with Bun, also the git issues were not helpful, does anyone have an idea ?

import { createBunWebSocket } from "hono/bun";
import wsApp from "./routes/websocket";

const { websocket } = createBunWebSocket();

type Bindings = {
  ip: SocketAddress;
};

const app = new Hono<{ Bindings: Bindings }>().basePath("/v1");

app.route("/", wsApp);

const server = Bun.serve({
  fetch(req, server) {
    return app.fetch(req, { ip: server.requestIP(req) });
  },
  websocket,
});`

import { Hono } from "hono";
import { createBunWebSocket } from "hono/bun";
import { WSContext } from "hono/ws";

const { upgradeWebSocket, websocket } = createBunWebSocket();

const wsApp = new Hono();

const userSockets = new Map<string, WSContext>();

wsApp.get(
  "/ws/:userId",
  upgradeWebSocket((c) => {
    const userId = c.req.param("userId");
    return {
      onOpen(event, ws) {
        userSockets.set(userId, ws);
        console.log(`WebSocket connection opened for user ${userId}`);
      },
      onMessage(event, ws) {
        const message = JSON.parse(event.data.toString());
        if (message.type === "checkEmailVerified") {
          // ---
        }
        console.log(message);
        ws.send("hi");
      },
      onClose: () => {
        userSockets.delete(userId);
        console.log(`WebSocket connection closed for user ${userId}`);
      },
    };
  })
);

export default wsApp;
Was this page helpful?