Zernst
Zernst

Reputation: 325

Socket.io application works locally but not on Heroku

I am creating a React application and a Node server that are supposed to communicate with each other through sockets, using socket.io. When I have everything connected on my local computer, I do not run into any issues. However, when I use my deployed server, my React application gets the following error in the console:

Access to XMLHttpRequest at 'https://{URL TO MY HEROKU SERVER}/socket.io/?EIO=4&transport=polling&t=NNjgExO' 
from origin '{URL FOR MY HEROKU REACT APP}' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header contains the invalid value '48506'.

I ran into a similar issue locally when putting the application together, and learned that I needed to use cors within my server to allow connections. When I did that on my local machine, it worked. However, now that I have it deployed, I am getting this type of error again. I know there is some kind of cors settings for this I need to change, but I really don't know what needs to be changed.
Here is the server code:

const server = http.createServer(app);
const io = socketio(server, {
  cors: {
    allRoutes: true,
    origin: PORT,
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true,
  },
});

And here is the React app code for connecting:

socket = io(ENDPOINT, {
      withCredentials: true,
      extraHeaders: {
        "my-custom-header": "abcd",
      },
    });

EDNPOINT refers either to my localhost server or the url for the deployed server, depending on the environment I am working in. Any help will be appreciated!

Upvotes: 0

Views: 241

Answers (1)

Zernst
Zernst

Reputation: 325

I managed to figure out the cors settings with trial and error. For anyone interested, here are the settings below that work for me:

Server:

const cors = require("cors");
const socketio = require("socket.io");

const app = express();
app.use(cors());

const server = http.createServer(app);

const io = socketio(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
    allowedHeaders: ["content-type"],
  },
});

Client:

socket = io(ENDPOINT);

Upvotes: 1

Related Questions