How to fix socket.io cors error in React with Node

Share

What is a web socket?

A web socket is a protocol that provides bidirectional and full-duplex communication channels.

Traditionally, when we are on a web page, we communicate with the server through one-way communication. However, with web sockets, communication can be done by both us and the server. Hence, it is no longer us talking to the server alone.

Example

One example of a web socket is a website that tells you the number of people online. Another example of a web socket is real-time chat applications.

Fixing cors error in socket.io

1. The React code

Below is the Feact code that emits an event that will be fired in the server. It establishes a two-way connection with the server running on http://localhost:5000.

import {io} from "socket.io-client";
const ENDPOINT = "http://localhost:5000";
const socket = io(ENDPOINT);
useEffect(() => {
// ... other codes
// Emitting an event that will trigger in the backend
socket.emit("reply");
// ... other codes
}, [])

2. The NodeJs code

The code below is the server-side implementation of the socket.io. We require the socket.io, and pass the Express server application without some options or configuration.

// ... other codes
const io = require('socket.io')(server);
io.on('connection', client => {
client.on('reply', () => { console.log("a reply detected!")}); // listen to the event
});
server.listen(PORT, ()=>{
console.log("Application running successfully on port: "+PORT);
});

When we run the code above, the following error will be thrown in the console:

The reason for this is that there was no configuration for cors in the socket.io implementation of the server-side.
Even with the cors enabled on the server-side, there will still be an error unless there are cors configured along with the socket.io implementation.

var cors = require('cors');
app.use(cors());

How to fix the error

The error is simple to fix. Add cors and the origin that can communicate with the server, and that’s all!

const io = require('socket.io')(server, {cors: {origin: "*"}});

In the code above, I added a wildcard as my origin because I would like any origin to access it.