honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.52k stars 522 forks source link

createBunWebSocket and Hono error. `server.upgrade` is not a function? #3013

Closed Blankeos closed 2 months ago

Blankeos commented 2 months ago

What version of Hono are you using?

4.4.7

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

Bun createBunWebSocket Hono error:

Error: server.upgrade is not a function. (In 'server.upgrade(c.req.raw, {
          data: {
            connId,
            url: new URL(c.req.url),
            protocol: c.req.url
          }
        })', 'server.upgrade' is undefined

Code:

// websocket.ts

import { Hono } from 'hono';
import { createBunWebSocket } from 'hono/bun';
const { upgradeWebSocket, websocket } = createBunWebSocket();

const wsRouter = new Hono();

wsRouter.get(
  '/',
  upgradeWebSocket((c) => {
    return {
      onMessage: (event, ws) => {
        console.log('[ws onMessage]', event.data);
        ws.send('Reply message from the server.');
      },
      onOpen: (event, ws) => {
        console.log('[ws onOpen]', event, ws);
        ws.send('Opening hello from the server.');
      },
      onClose: (event, ws) => {
        console.log('[ws onClose]', event);
      },
    };
  })
);

export { websocket, wsRouter };
// index.ts

import { websocket, wsRouter } from './websocket';
import { Hono } from 'hono';

const app = new Hono();

app.route('/ws', wsRouter);

export default {
  port: 3000,
  fetch: app.fetch,
  websocket: websocket,
};

What is the expected behavior?

No response

What do you see instead?

No response

Additional information

No response

EdamAme-x commented 2 months ago

hi @Blankeos it works in my enviroment. (Ubuntu latest) image

EdamAme-x commented 2 months ago

Linux? Windows? Mac? Other?

EdamAme-x commented 2 months ago

Please try to upgrade Bun

Blankeos commented 2 months ago

On a mac, I tried a minimal example as well. It actually worked lol. Thanks for the quick reply @EdamAme-x !

The issue was actually because of Vite Custom Dev Server. Was using @hono/vite-dev-server. Basically I think the HMR from Vite (uses ws under the hood), conflicts with the WS that I have in the same origin.

In any case, I fixed this by using concurrently and just running two servers during development:

Works out pretty fine actually.

Then in prod, I just reuse them back into a single server with a couple of if statements. :D

Let me know if you have other suggestions though. I might just be missing something. Will close the ticket if there's no other solutions besides the workaround. Thanks for the help!