I am making a realtime game application using socket io, react and nodejs. I have deployed backend server and also frontend site. When I am running the frontend site on local host using the deplyed backend server it is running fine, but the problem occurs when I am running it on deployed frontend site. I have deplyed frontend site using render. here is the link to my frontend website - https://gamefront.onrender.com/ here is the link to my backend server - https://gameback-6z3w.onrender.com/ here is link to my frontend repository - https://github.com/Arjit31/gameFront/tree/master here is link to my backend repository - https://github.com/Arjit31/gameBack
Here is a piece of my frontend code -
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import io from "socket.io-client";
import "./home.css"; //imports css file into project not just the component
//for importing into components use import styles from "./home.css"
const socket = io();
export default function Home() {
const [key, setKey] = useState("");
const [inputKey, setInputKey] = useState("");
const navigate = useNavigate();
useEffect(() => {
socket.on("keyGenerated", (generatedKey) => {
setKey(generatedKey);
});
socket.on("userConnected", (param) => {
// setConnectedUserId(otherUserId);
redirect(param);
});
return () => {
socket.off("keyGenerated");
socket.off("userConnected");
};
}, []);
const generateKey = (e) => {
e.preventDefault();
socket.emit("generateKey");
};
const connectByKey = (e) => {
e.preventDefault();
socket.emit("connectByKey", inputKey);
// navigate("/game");
// redirect();
};
const redirect = (param) => {
const key = param[0];
let gameURL = "/game?";
gameURL += `key=${key}&user=${param[1]}`;
// console.log(param);
// console.log(param);
// if({key})
// {
// gameURL += `key=${key}`;
// }
// else{
// gameURL += `key=${inputKey}`;
// }
navigate(gameURL);
}
return (
<div className="homeScreen">
{key ? (
<div className="keyGen">{key}</div>
) : (
<div>
<form className="gameForm">
<input
className="gameKey"
placeholder="Game Key"
value={inputKey}
onChange={(e) => setInputKey(e.target.value)}
></input>
<div className="buttonGroup">
<button className="btn join" onClick={connectByKey}>
Join
</button>
<button className="btn create" onClick={generateKey}>
Create
</button>
</div>
</form>
</div>
)}
</div>
);
}
Here is my problem screenshot - enter image description here
I think the problem may be lies in the deployment part.
Check your realtime socket server if it deployed or not. Seems your socket server is not running or your socket path from client is wrong. Then you can config your client for example:
You may need to re-check the server installation by following the doc: https://socket.io/docs/v4/server-installation/