I am having a server hosted in Heroku. Also, the client side(React) is hosted in Vercel. This combination works perfectly ! But, out of my curiosity, I tried to host the server-side script in Vercel. Then, when I try to connect to the Vercel-hosted-server, the client side is returning this error Access to XMLHttpRequest at 'https://socketio-vercel.vercel.app/socket.io/?EIO=4&transport=polling&t=NVeP_Ax' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
(I am testing in localhost:3000 )
Server-side code (both are same in Heroku and Vercel) ->
"use strict";
const express = require("express");
const socketIO = require("socket.io");
const PORT = process.env.PORT || 3000;
const INDEX = "/index.html";
const server = express()
.use((req, res) => res.sendFile(INDEX, { root: __dirname }))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const io = socketIO(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("Client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
setInterval(() => io.emit("time", new Date().toTimeString()), 1000);
Client-side code (if server is hosted with Heroku) (Working) ->
useEffect(() => {
if (shouldStart) {
axios.get("api/sync").then((response) => {
setMessages(response.data);
const socket = io("wss://radiant-mountain-09008.herokuapp.com");
socket.on("connect", () => {
console.log("connected"); // "G5p5..."
});
socket.on("time", (msg) => {
console.log(msg);
});
});
}
}, [shouldStart]);
Client-side code (if server is hosted with Vercel) ->
useEffect(() => {
if (shouldStart) {
axios.get("api/sync").then((response) => {
setMessages(response.data);
const socket = io("wss://socketio-vercel.vercel.app");
socket.on("connect", () => {
console.log("connected"); // "G5p5..."
});
socket.on("time", (msg) => {
console.log(msg);
});
});
}
}, []);
Any idea why is this happening ? Thanks !
as far I know vercel supports serverless function only. You can't use any socket, websocket Libraries. You can learn more details in this official link from their github. I hope this will help. Good luck