Course contentsShow
← Node.js
Lesson 1173 of 1,98010. Real-time Communication and WebsocketsFree lesson

Handling WebSocket Upgrades behind Proxies

You will configure headers correctly for proxies like Cloudflare that terminate or buffer socket connections.

In this lesson, you will learn how to configure your headers and server expectations to ensure WebSocket upgrade requests successfully navigate through proxies like Cloudflare or Nginx.

When you deploy a WebSocket server behind a proxy, the proxy acts as an intermediary that often terminates or buffers the initial HTTP request. A WebSocket connection begins as an HTTP request with an Upgrade header. If a proxy doesn't recognize this header or isn't configured to forward it, the "handshake" fails before a persistent socket connection can even be established.

The Role of Headers

Proxies often strip or modify headers, which can cause the underlying Node.js server to reject the connection. To support a seamless transition from HTTP to WebSocket, your proxy must explicitly support the following headers:

  • Upgrade: Set to websocket.
  • Connection: Set to Upgrade.
  • Sec-WebSocket-Key and Sec-WebSocket-Version: These allow the client and server to verify the handshake.

If you are using Nginx as a reverse proxy, you must explicitly instruct it to pass these headers through to your Node.js application. Without these, the proxy will treat the request as a standard HTTP request and return a 404 or 400 error.

Example Configuration Snippet

When configuring your proxy layer, ensure your routing logic looks similar to this:

location /socket/ {
    proxy_pass http://your_node_app;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

Why Buffering Matters

Some proxies, particularly global CDNs like Cloudflare, may attempt to buffer the incoming request. Because WebSockets require a low-latency, "always-on" pipe, buffering can cause the proxy to think the request has stalled, leading to premature termination. Ensure your proxy settings for the WebSocket path have buffering disabled and timeouts set to a duration long enough to accommodate idle socket connections.

By passing the Upgrade and Connection headers directly to your Node.js server, you ensure that the server receives the necessary signal to "upgrade" the connection to a persistent duplex channel.

Key Takeaway: To successfully proxy WebSockets, you must explicitly configure your load balancer or gateway to pass the Upgrade and Connection headers to the backend and disable request buffering for those routes.