Socket.io connection is not working on render but worked on local

Hi i have deployed my node server (both express rest api and socket.io)on web service and my frontend react app on static page.

Problem:
I have set the socket.io cors to 2 origins- local and render frontend app path. However it is only connected when i run the frontend app on local but not from render host.

Server side code:

const supabase = require("./configdb.js");
const express = require("express");

const app = express();
const cors = require("cors");
const port = 3000;

app.use(cors());

app.use(express.json());

//socket.io
const httpServer = require("http").createServer(app);
const options = {
  cors: {
    origin: ["http://localhost:3000", "https://project001-ejm9.onrender.com/"],
  },
};
const io = require("socket.io")(httpServer, options);

//set up socket connection to record online user

// "https://project001db-11.onrender.com",

let onlineUsers = {};

io.on("connection", (socket) => {
  console.log("connected");
  socket.on("userEntered", (user) => {
    onlineUsers[socket.id] = user;
    io.emit("updateUserList", Object.values(onlineUsers));
    console.log(Object.values(onlineUsers));
    console.log(user);
  });

  socket.on("disconnect", () => {
    delete onlineUsers[socket.id];
    io.emit("updateUserList", Object.values(onlineUsers));
    console.log("disconnect");
  });
});

// Set port, listen for requests.
httpServer.listen(port, () => {
  console.log(`Server is running on port ${port}.`);
});

// Add routes routes.
require("./routes/chat.routes.js")(express, app);

Client side code:

import { io } from "socket.io-client";
import { useEffect, useState } from "react";

const socket = io("https://project001db-11.onrender.com/");

export const useSocket = () => {
  useEffect(() => {
    return () => {
      socket.disconnect();
    };
  }, []);

  return useSocket;
};

export const useRegisterOnlineUser = (username) => {
  const [onlineUsers, setOnlineUsers] = useState([]);

  useEffect(() => {
    if (!username) return;

    const user = { username: username };
    socket.emit("userEntered", user, () => {
      console.log("emitted event-userConnected");
    });

    socket.on("updateUserList", (users) => {
      setOnlineUsers(users);
      console.log("updateUserList event received", users);
    });

    // Clean up on component unmount
    return () => {
      socket.off("updateUserList");
    };
  }, [username]);

  return onlineUsers;
};

Hi there,

Hmm, what happens if you remove the / from the end of https://project001-ejm9.onrender.com/. Some CORS frameworks may ignore the trailing slash, I’m not sure if Express CORS does.

Regards,

Keith
Render Support, UTC+10 :australia:

Hi Keith,

thankyou very much for the reply. ya removing the slash fixed it !

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.