'socket.io in a mern app doesn't work when deployed to Heroku
I'm trying to implement a messaging system and I used socket.io to make it real time, with local host it works just fine, but when I deploy it to Heroku it doesn't send messages in real-time anymore.
Expressjs server code
const express = require('express')
const app = express()
const http = require('http')
const socketIo = require('socket.io')
const server = http.createServer(app)
const io = socketIo(server, {
cors: {
origin: "http://localhost:5000",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true,
}
}
React connection to socket code
useEffect(() => {
socket = io('http://localhost:3000')
}, [])
EDIT:
just use the url of your Heroku app instead of localhost in both the client and server, and no need for ports or anything just the link like so: https://app-name.herokuapp.com/
, and in your client, set the socket variable using useState
instead of simply assigning values to it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|