Search code examples
node.jsreactjswebsocketsocket.iovercel

WebSocket connection to wss failed in production only(front end and back end on different domains)


i've successfully created a chat app on my own lol, my front end and back end are both deployed on vercel, everything is working fine locally except that the socket connection is not being established in production my backend api url is https://chat-app-bice-ten.vercel.app/ my frontend api url is https://chattin.vercel.app/

I get the following error, it keeps occuring periodically WebSocket connection to 'wss://chat-app-bice-ten.vercel.app/socket.io/?EIO=4&transport=websocket'

SERVER CODE

const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "https://chattin.vercel.app",
  },
});

CLIENT CODE

import { io } from "socket.io-client";
const socket = io("https://chat-app-bice-ten.vercel.app", {
  transports: ["websocket"],
});

export default socket;

Tried many things, searched alot but all in vain


Solution

  • I don't think you can deploy a websocket server on Vercel according to their doc:

    https://vercel.com/guides/do-vercel-serverless-functions-support-websocket-connections

    Serverless Functions on Vercel are stateless and have a maximum execution duration. As a result, it is not possible to maintain a WebSocket connection to a Serverless Function.

    There are a few option out there to make it work: Ably, Pusher, Shippr (disclaimer: I work for the last one, there is a free plan - happy to onboard you :))