← Debugging Guides

阅读中文版本

Vite — WebSocket connection failed for HMR behind a proxy

Fix Vite HMR websocket failures by configuring the dev server host, port and proxy for the environment.

intermediatedebuggingnodevite

Symptoms

  • [vite] failed to connect to websocket
  • HMR does not update the browser and a console error repeats
  • It works locally but fails behind a reverse proxy or in a container
  • The page reloads instead of hot updating

Possible causes

  • The dev server binds to localhost only and is unreachable from the client
  • The reverse proxy does not forward the websocket upgrade
  • Server host and client host differ so the HMR socket targets the wrong address
  • Strict port settings prevent the client from reaching the dev server port

Diagnosis steps

Expose the dev server on the network

vite --host 0.0.0.0 --port 5173

Interpretation

Binding to all interfaces makes the server reachable from containers and other hosts.

Configure the HMR client address

server: { hmr: { clientPort: 443 } }

Interpretation

When a proxy terminates TLS, the client must target the proxy port for the websocket.

Ensure the proxy upgrades websockets

proxy: { "/": { target: "http://localhost:5173", ws: true } }

Interpretation

Without ws:true the proxy drops the upgrade and the HMR connection fails.

Root cause

The browser cannot open the HMR websocket to the dev server because of host binding, port mismatch or a proxy that does not forward the websocket upgrade.

Fix

Bind the dev server to the reachable host, set the HMR client host and port to what the browser uses, and configure the proxy to forward websocket upgrades.

Verify the fix

Reload the page and confirm the websocket connects and edits trigger hot updates without the console error.

Symptom walkthrough

The browser console repeats a failed to connect to websocket message and hot module replacement stops, sometimes falling back to full reloads. The dev server may be up, yet the browser cannot reach the HMR socket because of host binding, a port mismatch, or a proxy that does not forward the websocket upgrade. This is common in containers and behind TLS-terminating proxies.

Fix in practice

Make the dev server reachable by binding it to the right host, and tell Vite which host and port the browser should use for HMR when a proxy sits in front. Configure the proxy to forward websocket upgrades. These settings align the server, the proxy and the browser.

Verification

Reload the page and confirm the websocket connects without the console error, then edit a file and confirm the browser hot-updates rather than fully reloading. Working HMR confirms the alignment.

Diagnostic commands

Check the behavior with commands like these:

vite --host 0.0.0.0 --port 5173
server: { hmr: { clientPort: 443 } }
proxy: { "/": { target: "http://localhost:5173", ws: true } }