Real time socket.io messaging worked with localhost testing but not after deployment to render.com

43 views Asked by At

I'm new to web development and started with the MERN stack. A portion of my project includes a messages page in which once the user clicks on it should establish a connection to the socket.io server. During development with localhost the real-time messaging worked perfectly fine, however, after deployment I'm getting this error:

GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=OmGJLG6 net::ERR_BLOCKED_BY_CLIENT

I'm using render.com to deploy my backend as a web service and my frontend as a static site.

Here is some snippets of my backend server code that deal with socket.io:


const express = require('express')
const http = require('http')
const port = process.env.PORT || 5000
const {Server} = require("socket.io")

const cors = require('cors')
const app = express()
const server = http.createServer(app)



app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use(cors({
  methods:['GET', 'POST', 'DELETE']
}))



const io = new Server(server, {
  cors:{
    origin: 'https://m-recruitmentfrontend.onrender.com/',
    methods: ["GET", "POST"]
  }
  
})

let users = []

const addUser = (userId, socketId) => {
  !users.some(user=>user.userId === userId) && 
      users.push({userId, socketId})
}

const removeUser = (socketId) => {
  users = users.filter(user=>user.socketId !== socketId)
}

const getUser = (userId) => {
  return users.find(user=>user.userId === userId)
}

io.on('connection', (socket)=>{
  console.log('connected to socket.io')

  socket.on("addUser", userId=>{
    addUser(userId, socket.id)
    io.emit("getUsers", users)
  })

  socket.on("sendMessage", ({conversationID, sender, receiverId, text}) => {
    
    const other = getUser(receiverId)
    if(other){
      io.to(other.socketId).emit("getMessage", {
        conversationID: conversationID,
        sender: sender,
        text: text
      })
      
    }
    
  })

  socket.on("disconnect", () => {
    console.log("a user disconnect")
    removeUser(socket.id)
    io.emit("getUsers", users)
  })
})

server.listen(port, '0.0.0.0', () => console.log(`Server started on port ${port}`))

And here is the useEffect in my frontend code that executes when the Messages page mounts:

useEffect(() => {
    socket.current = io(ENDPOINT);
    return () => {
      socket.current.disconnect();
    };
  }, []);

Could this be an https error? Any help or ideas would be greatly appreciated!

I've tried changing port numbers to see if that was causing the issue. Ultimately, I'm the most curious as to why the error includes localhost in the URL if my project is currently deployed. I also have no hardcoded localhost addresses anywhere left in my code.

1

There are 1 answers

0
Akeel Ahmed Qureshi On

Update your backend and frontend code and try this :

In backend:
    const io = new Server(server, {
      cors: {
        origin: 'https://m-recruitmentfrontend.onrender.com', // Removed trailing slash
        methods: ['GET', 'POST']
      }
    });

and in frontend:

 const ENDPOINT = '//your-backend-url'; 
  const socket = useRef(null);

  useEffect(() => {
    socket.current = io(ENDPOINT);
    return () => {
      socket.current.disconnect();
    };
  }, [ENDPOINT]);