socket.io connect failed on production, working in localhost
Asked Answered
J

2

6

I have this in server.js

//socket io config
const server = require('http').createServer(app)
const io = require('socket.io')(server)
io.on('connection', function (socket) {
  socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
    io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
  })
  //and many more
})

In my client (react)

import io from 'socket.io-client'
const socket = io('localhost:3001') // working in localhost

in my prod I do this checking

let socket = io('localhost:3001')
if(process.env.NODE_ENV === 'production') { socket = 
  io('https://api.example.com:3001') 
}

Why is it so? I don't think it's cors issue because I already did

app.use(cors({
  origin: true,
  credentials: true
}))

my package.json deps

"socket.io": "^2.1.1",
"socket.io-client": "^2.1.1",
Jalbert answered 18/9, 2018 at 3:5 Comment(7)
Have you mentioned your port number in port for production?Palliasse
const socket = io('http://{your machine's ip}:4001')Palliasse
@SantoshShinde yeah that's what I did. Do I have to setup reverse proxy or anything like that in node.js?Jalbert
Can you add package.json of your client(react) ?Palliasse
github.com/react-boilerplate/react-boilerplate/issues/1413Palliasse
@SantoshShinde but I'm using create-react-appJalbert
Did you solve this issue?Palliasse
D
1

To know which route you should point in the api, access to the address "/socket.io/". For example, if you are runing on localhost:3001 should be "http://localhost:3001/socket.io/" and the response

{"code":0,"message":"Transport unknown"}

Be sure you are declaring the same server name and route in production. If you use a kind of proxy or sub route like /api you have to add it. This is an example.

SERVER ROUTE DECLARATION

const httpServer = require("http").createServer(app);
const options = {
    path: "/api/socket.io",
    cors: {
        origin: "*"
    }
};
const io = require("socket.io")(httpServer, options);

io.on('connect', function (socket) {
    socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
        io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
    })
});

CLIENT DECLARATION LISTENER (FOR REACT HOOKS)

  let socket = io("https://www.yoursite.com", { path: '/api/socket.io/' });

  React.useEffect(() => {
    socket.on('SOCKET_COMMENT_RECEIVED', function (data) {
      console.log(`RECEIVED`);
    });
    return () => {
      socket.disconnect();
    }
  }, []);
Disclaimer answered 22/8, 2023 at 17:49 Comment(0)
P
0

In your server code please add the following line

io.set('origins', '*:*');

So your code will be

  //socket io config
  const server = require('http').createServer(app)
  const io = require('socket.io')(server)
  io.set('origins', '*:*');
  io.on('connection', function (socket) {
    socket.on('SOCKET_COMMENT_RECEIVED', ({ notification }) => {
      io.emit(`SOCKET_COMMENT_RECEIVED`, notification)
    })
    //and many more
  })

For more help to follow this tutorial & this question.

The source code is available here.

Hope this will help you !!

Palliasse answered 18/9, 2018 at 4:15 Comment(18)
Why io.set('origins', '*:*') is different from app.use(cors({ origin: true, credentials: true })) ??Jalbert
same error I got. In firefox I see this error Cross-Origin Request Blocked: The Same Origin Policy disallowJalbert
Can you please just use app.use(cors())Palliasse
the strange part is I have no issue running it on local, have you tried to publish ur repo to production?Jalbert
Yes it's working but I simply use cors without extra configPalliasse
tried bunch of things, nothing worked, not sure it's my ssl issue.Jalbert
Maybe, do you have repo then give me access or just try with demo on productionPalliasse
I deployed your code github.com/TutorialEdge/react-typescript-real-time-chat with netlify, having the exact same problem with mine, do you familiar with netlify? I don't think it's code level issue now.Jalbert
Okay Can you please share that url with me ?Palliasse
sure. mystifying-fermat-004141.netlify.com in chrome the error message is different than in firefox, in firefox the error msg is cros related.Jalbert
Have you update the code io.set('origins', ':'); ?Palliasse
#24058657Palliasse
I did not touch your code, it is there: github.com/TutorialEdge/react-typescript-real-time-chat/blob/…. I really suspect something is wrong with netlify, it has't been so hard with cors issue, previously I have no problem setup socket.io with reverse proxy in nginx.Jalbert
Actually this is not my repo I just shared sample which I have referred for me, and you have to update the code which I have mentied in my answerPalliasse
What else I need to do? You said io.set('origins', '*:*'); which is already here github.com/TutorialEdge/react-typescript-real-time-chat/blob/…Jalbert
I think this has nothing to do with CORS- it was a problem with the security certificate.Palliasse
You mean the SSL? previously I also have SSL but I didn't do extra step to make it work, the only different is previously I host my client using nginx reverse proxy, this time I try netlify.Jalbert
Maybe you're right because in my localhost it doesn't use ssl.Jalbert

© 2022 - 2025 — McMap. All rights reserved.