Home > Mobile >  Socket.IO not working when deployed on Node/Express with React build
Socket.IO not working when deployed on Node/Express with React build

Time:06-15

I have setup a Socket.io instance inside my Node/Express backend. The frontend is React. Everything works fine on my device when I build the React app and deploy it in the backend. However when I move the code to my production server, there is no communication whatsoever. I believe this is because I haven't initialised the client correctly, but I have tried multiple iterations and can't get it to work.

I've tried using the server name, IP address, and localhost, but nothing works. I would expect the below to work:

//SOCKET.IO CLIENT SETUP
import { io } from "socket.io-client";
const socket = io(); //there is NO separation between client and server in the production instance
export default socket;

On the server side, the code to setup the socket.io instance is taken straight from the Express example in the docs.

import express from "express";
const app = express();

//SOCKET.IO SERVER SETUP
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {});
httpServer.listen(8080);

//SOCKET MANAGEMENT
var connections = 0;
io.on("connection", (socket) => {
  connections  ;
  console.log(connections);
});

CodePudding user response:

Here's what has worked:

CLIENT-SIDE: USED THE CORS OPTIONS

//REPLACE 'DOMAINNAME' WITH YOUR DOMAIN/IP ADDRESS
const socket = io("http://domainname:8080", {
    withCredentials: true,
    extraHeaders: {
      "my-custom-header": "abcd"
    }
});

SERVER-SIDE: ADD AN ARRAY OF ORIGINS

As detailed in the Socket.IO docs here (It's not very clear in the docs as the example is commented out)

This means the server code is more resilient against requests originating from multiple sources.

I still don't really understand why I've had to account for CORS given that the server/client is all being served from the same place, so if anyone wants to enlighten this with an answer I will happily mark it as correct.

CodePudding user response:

try this in the nodejs file where the socket server created
io.attach(server);

  • Related