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;
};