WebSocket SocketIO connection not working with NestJS server on Heroku and react client on Vercel

Viewed 1728

I have #NestJS server running on herokou.com and a react CRA app running on vercel.com I am trying to connect the frontend and backend with websockets (socket.io) However the connection is not getting made. In the console the network requests show up no error, but the GET requests corresponding to socket.io timeout. There is no response. This is how nestjs gateway is written. I can see the log of the gateway getting initialized. However no log of connection/disconnection even when i try to open up clients.

@WebSocketGateway()
export class AppGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  users: Record<string, any> = {};
  @WebSocketServer() server;
  afterInit(server: any) {
    this.logger.log('Initialized');
  }
  handleConnection(client: any, ...args: any[]) {
    console.log('connected.');
    if (!this.users[client.id]) {
      this.users[client.id] = client.id;
    }
    client.emit('yourID', client.id);
    this.server.emit('allUsers', this.users);
  }

In the client i am connect like this

    socket.current = io.connect(
      "https://server.herokuapp.com:" + props.port
    );

I have checked props.port is fine. Just that the GET requests in the network requests of developer tools window, time out, there is no response. Example: https://server.herokuapp.com:43030/socket.io/?EIO=3&transport=polling&t=NAq8j0w This GET responds nothing and timeout.

1 Answers

I think in the client-side, the way to initilize the socket.io is by

import io from "socket.io-client";

const socket = io("http://DOMAIN:IP"); // or https

or if you want it in a react Ref hook:

const socket = useRef();
socket.currect = io("http://DOMAIN:IP");  // or https

or in one line I think: const socket = useRef(io("http://DOMAIN:IP")); // or https

Related