honojs / hono

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

Hono app with websockets fails without Bun's hot reload #3240

Closed cybercoder-naj closed 1 month ago

cybercoder-naj commented 1 month ago

What version of Hono are you using?

4.5.1

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

Step 1: Create a simple websocket application

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

const { websocket, upgradeWebSocket } = createBunWebSocket();

const app = new Hono().get(
  "/ws",
  upgradeWebSocket((_) => {
    return {
      onOpen(evt, ws) {
        console.log("Connection open");
        ws.send("Hello, World!");
      },
      onMessage(evt, ws) {
        ws.send("You said: " + evt.data);
      },
      onClose(evt, ws) {
        console.log("Connection closed");
      },
    };
  })
);

Bun.serve({
  fetch: app.fetch,
  port: 3000,
  websocket,
});

export default app;

Step 2: Run the code with hot reload: bun run --hot src/index.ts. The server runs as expected and websocket connection works properly.

Step 3: Run the code without hot reload: bun run src/index.ts. This is the following error:

 6 |    entryNamespace = entryNamespace.then((entryNamespace) => {
 7 |       if(typeof entryNamespace?.default?.fetch === 'function')  {
 8 |         Bun.serve(entryNamespace.default);
 9 |       }
10 |    }, reportError);
11 |    Bun.serve(entryNamespace.default);
     ^
EADDRINUSE: Failed to start server. Is port 3000 in use?
 syscall: "listen"

      at bun:main:11:13

Bun v1.1.18 (Linux x64)

What is the expected behavior?

There shouldn't be a difference between running an application with and without hot reload.

What do you see instead?

When executing the file with hot reload, Bun.serve tries to open the server on port 3000 but Hono is already using that port (or the other way around, not sure).

Additional information

This is a critical bug fix since I cannot build (and minify) my application to ship for production.

yusukebe commented 1 month ago

Hi @cybercoder-naj

Remove export default app at the last line.

cybercoder-naj commented 1 month ago

I think this should be documented properly since it is a bit confusing. I'm happy to edit the page. Thanks nevertheless