vite-plugins icon indicating copy to clipboard operation
vite-plugins copied to clipboard

hono vite dev server doesn't allow websockets to connect

Open benjamine opened this issue 10 months ago • 2 comments

I followed the guide at https://hono.dev/docs/getting-started/cloudflare-pages and then added websockets following https://hono.dev/docs/helpers/websocket see repo here: https://github.com/benjamine/hono-vite-websocket (made to reproduce this)

websocket never connects when running the vite dev server (I think because there's never a server upgrade).

websocket works correclty when using vite build+preview or when deployed to cloudflare.

reproduction steps:

  • clone the repo
  • npm i && npm run dev
  • check the console or network tab, note that the browser's websocket never connects

I noticed connection succeeds adding an upgrade handler at the vite plugin

	configureServer(server) {
                ...
		server.httpServer?.on("upgrade", (request, socket, head) => {
                     ...
                     // handle this similarly to hono-node/ws ?

and confirmed that makes the connecting succeed (but this might not be the right way or place to handle it).

benjamine avatar Apr 03 '25 23:04 benjamine

in case it helps, also a temporary workaround: https://github.com/benjamine/hono-vite-websocket/compare/main...node-secondary-ws-server (starting a secondary node server for websockets, something that can be done conditionally when running in local dev)

benjamine avatar Apr 04 '25 01:04 benjamine

Hi @benjamine

Sorry, I'm late.

If you use Vite for Cloudflare Workers, we currently recommend using @cloudlare/vite-plugin. With it, WebSockets will work well. For example, install it and apply the diff on your repo:

diff --git a/vite.config.ts b/vite.config.ts
index 3dd8bdc..930cb7e 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -3,17 +3,11 @@ import { defineConfig } from 'vite'
 import build from '@hono/vite-cloudflare-pages'
 import devServer from '@hono/vite-dev-server'
 import adapter from '@hono/vite-dev-server/cloudflare'
+import { cloudflare } from '@cloudflare/vite-plugin'

 // import { cloudflare } from '@cloudflare/vite-plugin'
 // import ssrHotReload from 'vite-plugin-ssr-hot-reload'

 export default defineConfig({
-  plugins: [
-    // ssrHotReload(), cloudflare()
-    devServer({
-      entry: 'src/index.tsx',
-      adapter, // Cloudflare Adapter
-    }),
-    build(),
-  ]
+  plugins: [cloudflare()]
 })

@cloudflare/vite-plugin is great!

However, this is only applicable for Cloudflare Workers, so I don't have a solid suggestion for other platforms. Using WebSockets with Vite can be complex. Your workaround is excellent. It would be better if you applied it to other platforms.

yusukebe avatar Jun 23 '25 06:06 yusukebe