WebSocket works local but not in render.com

I have MERN app with WebSocket. App works well in local but not in real site:

server.js:

const httpPort = process.env.PORT || 5000;
const webSocketPort = 8080;
connectDB();

const app = express();

let sessions = [];
let activeConnections = {};

// WebSocket Server Setup
const wss = new WebSocketServer({ port: webSocketPort });

wss.on('connection', (ws, req) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const sessionId = url.searchParams.get('sessionId');
  const clientId = nanoid();

  console.log(`Client connected: ${clientId}, Session: ${sessionId}`);

  if (!sessionId) {
    ws.close();
    return;
  }
....

In client:

  const ws = useRef<WebSocket | null>(null);
...
  useEffect(() => {
    if (!sessionId) return;

    ws.current = new WebSocket(`/ws?sessionId=${sessionId}`);

    ws.current.onopen = () => {
      console.log('WebSocket connected');
      setIsWebSocketOpen(true);
    };

    ws.current.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('Message from server:', data);

      if (data.type === 'clientConnected') {
        setClientConnected(true);
      } else if (data.type === 'clientDisconnected') {
        setClientConnected(false);
      }
    };

    ws.current.onclose = () => {
      console.log('WebSocket disconnected');
      setIsWebSocketOpen(false);
    };

    ws.current.onerror = (error) => {
      console.error('WebSocket error:', error);
      setIsWebSocketOpen(false);
    };

    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, [sessionId]);

In my server I use different ports for http and socket because it doesn’t work if I try to use the same port. And it looks like work in render:

HTTP Server is running on port 10000
WebSocket Server is running on port 8080
MongoDB connected: ....
==> Your service is live 🎉

In site when I try to create connection:


In Render Logs no errors.

I tried a lot of variants to use app with and without port, also test some variants in forum

Hi there,

Render services only open a single port through our public proxy. Your service can’t listen on different ports for HTTP and WebSocket requests. You must do something like this: https://github.com/websockets/ws?tab=readme-ov-file#external-https-server (but a plain HTTP server, not HTTPS).

Regards,

Keith
Render Support, UTC+10 :australia: