Square CloudSquare Cloud

WebSocket connection failed: causes behind a proxy and HTTPS

The browser could not complete the WebSocket handshake, or lost the connection right after it. The usual causes are ws:// on an HTTPS page, a proxy that drops the Upgrade headers, and idle connections cut by a timeout.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Read the console message and the handshake status in the Network tab
  • Configure the reverse proxy and a heartbeat so the connection stays up
  • Test the endpoint with wscat, websocat and curl, outside the browser
On this page

The chat, the live scoreboard or the game works on localhost. After the deploy, the browser console shows a line with WebSocket connection to 'wss://...' failed and little else. Sometimes it fails at once; sometimes it connects and drops after a minute.

A WebSocket starts as an HTTP request and then switches to another protocol, so it breaks in places where plain HTTP gets through fine: TLS, the proxy and load balancing across instances. The way to find the cause is to look at the handshake.

What does the error look like?#

In Chrome and other Chromium-based browsers, the message always starts the same way, and the reason comes after failed::

text
WebSocket connection to 'wss://example.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 502
WebSocket connection to 'wss://example.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 404
WebSocket connection to 'wss://example.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 200
WebSocket connection to 'ws://localhost:3000/ws' failed: WebSocket is closed before the connection is established.

Firefox reports the failure without a reason:

text
Firefox can’t establish a connection to the server at wss://example.com/ws.

When the page is HTTPS and the code tries ws://, Chrome logs a mixed content block, and the constructor throws a SecurityError:

text
Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://example.com/ws'. This request has been blocked; this endpoint must be available over WSS.
Uncaught SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

Apart from that SecurityError, your JavaScript learns none of this. The error event carries no details, and close almost always arrives with code 1006 (abnormal closure, no close frame). The standard forbids the browser from telling the script whether the host did not resolve, the connection was refused or TLS failed, so a page cannot probe the user's network. The reason lives in the console and the Network tab.

WebSocket is closed before the connection is established often has a harmless cause in development: with React in StrictMode, every Effect runs an extra setup and cleanup cycle, and the first connection is closed by the cleanup before it opens. That extra cycle does not happen in production.

How do you diagnose it in the Network tab?#

Open DevTools, go to the Network tab, filter by WebSocket (the filter is called WS or Socket, depending on the browser) and reload. The connection's row shows the status the server returned to the handshake:

Status What it means
101 Switching Protocols The handshake worked. If the connection drops later, it is a timeout or the server closing it; check the frames in the Messages tab.
200, 400 or 426 The request arrived as plain HTTP: the proxy stripped the Upgrade headers, or the path lands on an HTTP route.
403 The server rejected the origin or the authentication.
404 Wrong path.
502 or 504 The proxy could not reach the app: wrong port, app down, or too slow to answer.
No status The request never left or never finished: mixed content, DNS, an invalid certificate or a closed port.

If the connection opens and always drops after the same amount of time (60 seconds, for instance), note the interval. It almost always matches the timeout of some layer along the way.

What causes it, from most to least common?#

ws:// on an HTTPS page#

A page served over HTTPS can only open wss://: it is the same mixed content block that stops images and scripts loaded over HTTP. The typical case is a URL hardcoded in the code or in a build variable, such as VITE_WS_URL=ws://localhost:3000, that ended up in the production bundle (see build-time vs runtime variables). Build the URL from the page instead:

js
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const socket = new WebSocket(`${protocol}//${location.host}/ws`);

With wss://, the certificate also has to be valid for that host. An expired certificate, or one for another domain, kills the handshake with no status in the Network tab.

A reverse proxy without the Upgrade and Connection headers#

Upgrade and Connection are hop-by-hop headers: they apply to a single hop, and a reverse proxy does not forward them by default. Without them, the app receives a plain GET and answers it as HTTP. In nginx, the configuration from the official docs looks like this:

nginx
# in the http block
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 443 ssl;
    server_name example.com;
    # ssl_certificate and ssl_certificate_key here

    location /ws {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 120s;
    }
}

Upgrade is an HTTP/1.1 mechanism, and older nginx releases talk HTTP/1.0 to the upstream server by default. Keep proxy_http_version 1.1 explicit so the config works on any release.

Idle timeout without ping and pong#

By default, nginx closes the connection if the server sends no data for 60 seconds. Load balancers, mobile networks and corporate proxies have similar limits, and the websockets library docs cite 30 to 120 seconds as a common range. A chat that stays quiet for a minute drops even when everything is configured correctly.

The protocol already has the answer: ping and pong frames. Under RFC 6455, an endpoint that receives a ping must answer with a pong. The browser API does not expose ping, but the browser answers server pings by itself, so the heartbeat starts on the server. With the ws library (npm install ws, with "type": "module" in package.json):

js
import { WebSocketServer } from "ws";

const wss = new WebSocketServer({
  host: "0.0.0.0",
  port: Number(process.env.PORT) || 3000,
  path: "/ws",
});

wss.on("connection", (socket) => {
  socket.isAlive = true;
  socket.on("pong", () => {
    socket.isAlive = true;
  });
  socket.on("error", console.error);
  socket.on("message", (data) => socket.send(data)); // echo, just for the example
});

// Every 30 s: drop whoever missed the last ping, ping everyone else
const heartbeat = setInterval(() => {
  for (const socket of wss.clients) {
    if (!socket.isAlive) {
      socket.terminate();
      continue;
    }
    socket.isAlive = false;
    socket.ping();
  }
}, 30_000);

wss.on("close", () => clearInterval(heartbeat));

The ping interval must be shorter than the shortest timeout on the path. In Python, the websockets library already sends a ping every 20 seconds and closes the connection if the pong does not arrive within 20 seconds. Socket.IO has its own heartbeat.

Wrong path or port#

The server listens on /ws and the client connects to /, or the other way around. Another common one: the client points at the internal port (wss://example.com:3000), which is not exposed, instead of the public address on the default port. And a plain WebSocket client cannot connect to a Socket.IO server, nor the reverse: Socket.IO has its own protocol and is not a WebSocket implementation.

Several instances without shared state#

Each connection lives in a single process. With two instances behind a load balancer, a message sent on instance A never reaches clients on instance B, and a reconnect can land on the other instance, without the session that lived in the first one's memory.

Socket.IO has it worse: with long-polling, every request of a session must reach the same process, which requires sticky sessions. Without them, requests land on processes that do not know the session, and the connection never gets established. The Socket.IO docs offer two ways out: sticky sessions, or WebSocket as the only transport on the client, with io(url, { transports: ["websocket"] }), which loses the fallback for restrictive networks. To broadcast across instances, use an adapter, such as the Redis one, and keep session state outside the process.

How do you test it outside the browser?#

Test layer by layer: first straight at the app, then through the proxy, then through the public URL. The layer where the test starts failing is the culprit.

bash
# wscat: interactive client (-o sends the Origin, like the browser)
npx wscat -c wss://example.com/ws -o https://example.com

# websocat: the same, with a verbose log
websocat -v wss://example.com/ws

# curl: the handshake only (Ctrl+C to quit)
curl -i -N --http1.1 \
  -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  -H "Sec-WebSocket-Version: 13" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  https://example.com/ws

The answer you want from curl is HTTP/1.1 101 Switching Protocols. Any other status takes you back to the Network tab table. --http1.1 matters: over HTTPS, curl may negotiate HTTP/2, and the WebSocket Upgrade only exists in HTTP/1.1. wscat with -P prints every ping and pong it receives, handy to confirm the heartbeat. For the complete server, with client reconnection, follow how to host a WebSocket server.

How to do this on Square Cloud#

On Square Cloud, a web application's traffic is published over HTTPS and WSS on the *.squareweb.app subdomain (or on your own domain, from the Standard plan up). The client connects with wss:// to the public address, with no port in the URL; the app listens on 0.0.0.0 on the port from the PORT variable, and only port 80 receives traffic. The proxy does not cut long-lived connections: WebSocket and SSE pass through without buffering. Keep the heartbeat anyway: it detects clients that vanished and avoids idle cuts on networks on the user's side.

For more than one instance, load balancing (from the Standard plan up) puts the same custom domain on two or more applications, round-robin and with no sticky sessions. A reconnect can land on another application, so keep state in a database or in Redis. Redis hosting supports PUBLISH/SUBSCRIBE and can act as the bus between instances, as Socket.IO's Redis adapter does. On the Socket.IO client, set transports: ["websocket"].

The real-time logs show what your server logs on each connection. See how to publish your server on the API hosting page.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

What does close code 1006 mean?

The connection closed abnormally, without a close frame. For security, the browser uses 1006 for any network, TLS or handshake failure without saying which one. The real cause shows up in the console and the Network tab.

Why does my WebSocket drop every 60 seconds?

It is almost always the read timeout of a proxy along the way. nginx, by default, closes the connection after 60 seconds without data from the server. Send pings from the server more often, or raise proxy_read_timeout.

Can I use ws:// on an HTTPS page?

No. The browser blocks it as mixed content. Use wss://, which is WebSocket over TLS, on an address with a valid certificate.

Can the browser send a WebSocket ping?

The browser's WebSocket API does not expose ping or pong. The browser answers server pings on its own, so the heartbeat starts on the server, or you send an application message, such as a JSON ping, with send.

Next articleExpress, Fastify, NestJS or Hono: which Node.js framework to useExpress is the best known, Fastify focuses on speed and validation, NestJS gives teams structure and Hono runs on many runtimes. See code and which to pick.