Skip to content

WebSocket Connection Failed

Quick summary

Your WebSocket connection fails to open because the server is not running, the URL is wrong, or the protocol is mismatched.

Why this happens

  • The WebSocket server is not running or not listening on the expected port

  • Using ws:// on an HTTPS page (must use wss:// for secure connections)

  • The WebSocket URL is incorrect or the endpoint does not exist

  • A proxy or firewall blocks WebSocket connections

Minimal example

✗ Broken code
// HTTPS page trying to use ws:// (insecure)
const ws = new WebSocket("ws://example.com/ws");
// Error: Mixed content - blocked by browser

// Server not running
const ws = new WebSocket("wss://example.com:8080/ws");
// Error: Connection refused
✓ Fixed code
// Use wss:// on HTTPS pages
const ws = new WebSocket("wss://example.com/ws");
ws.onerror = (err) => console.error("WebSocket error:", err);
ws.onclose = () => console.log("Disconnected - implement reconnect");

On HTTPS pages, use wss:// (secure WebSocket) not ws://. Add error handling for onerror and onclose events, and implement reconnection logic for production reliability.

How to diagnose

  • Check the browser console for WebSocket error messages

  • Verify the WebSocket URL is correct (ws:// or wss:// + host + port + path)

  • Test the WebSocket server independently (e.g., with wscat)

  • Check if the page is HTTPS — it requires wss:// not ws://

How to fix

  • Start the WebSocket server and verify it is listening

  • Use wss:// on HTTPS pages and ws:// on HTTP pages

  • Correct the WebSocket URL path and port

  • Configure the proxy to forward WebSocket connections

How to prevent

  • Always use wss:// on production HTTPS sites

  • Implement reconnection logic for dropped connections

  • Add error handling on the WebSocket onerror and onclose events

Related Resources

Related Glossary

Related Lessons

  • HTTP

    HTTP and WebSocket protocols.

← Back to language