Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocket is closed before the connection is established. Socket.io and React

I want to make an Chat application with Socket.io and I've followed this tutorial: https://youtu.be/ZwFA3YMfkoc. I am using React and Node.js

Everything works fine while using it locally and even on different devices on my Network. However if I am hosting my Backend on Heroku it doesn't work.

The error Message is: WebSocket connection to 'URL' failed: WebSocket is closed before the connection is established. (URL is the URL of my Backend with the Port). I am using SSL.

I've already tried to enable session affinity but it already was enabled.

My backend code is: (atleast the code that I think is important to the Problem)

const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use(cors()); 
server.listen(PORT, () => console.log("Server started on " + PORT));

My frontend code is written in React and is:

var connectionOptions = {
  "force new connection": true,
  reconnectionAttempts: "Infinity",
  timeout: 10000,
  transports: ["websocket"],
};
const ENDPOINT = "URL"; 
socket = io(ENDPOINT, connectionOptions);
like image 381
Xaver Drabik Avatar asked Oct 20 '25 13:10

Xaver Drabik


1 Answers

So I've fixed my Problem.

The URL on the client side had to be without the Port. So for example: const ENDPOINT = "https://web.site.com";

and not: const ENDPOINT = "https://web.site.com:1337";

like image 62
Xaver Drabik Avatar answered Oct 22 '25 02:10

Xaver Drabik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!