0

Hi i am running an express server with a socket.io server attached to it

const { Server } = require("socket.io");
var server = http.createServer(app);

/**
 * Adding Socket io implementation
 */

const io = new Server(server, {
  cors: {
    origin: '*',
  }
});

i ahve no specific path set for the websocket communication, so my web client connects directly with an empty path. the SOCKET_ENDPOINT_URL is set to '/api' so that it connects to my proxied backend server (config below) (but from what i see, it seems to completely ignore that and treat the /api as simply '/')

import { io } from "socket.io-client";
io(env.SOCKET_ENDPOINT_URL, {
            path: ''
        })

here is my nginx config :

 location /api/ {
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_cache_bypass $http_upgrade;

          proxy_pass http://backend_server:3000/;
      }

  # Requests for socket.io are passed on to Node on port 3000
  location ~* \.io {
      proxy_pass http://backend_server:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
    proxy_hide_header 'Access-Control-Allow-Origin';
    }

the /api proxy works perfectly, the only issue is with the websocket which instantly triggers the warning on console : WebSocket connection to 'ws://192.168.1.12/socket.io/?EIO=4&transport=websocket&sid=t6rV5sJp9AX35RNNAAAH' failed: WebSocket is closed before the connection is established

i tried multiple configs but i seem to miss something crucial

1 Answers1

0

I meet a similar problem as you. My case is "wss" instead of "ws". Here is my solution:

Client-side:

const socket = io("https://your-domain-name", {
    path: "/socket.io"
});

Nginx-reverse-proxy:

server{
    listen 443 ssl;
    ssl_certificate  /path/to/fullchain.cer;
    ssl_certificate_key /path/to/domain.key;


    location /socket.io {
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_pass http://127.0.0.1:8088;

# redirect all HTTP traffic to localhost:8088;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


    }
}

Server-side: I find you miss something in the "init server"

const io = new Server(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});