I.K.
I.K.

Reputation: 464

Heroku Deployment of NodeJS and ReactJS

I want to deploy 2 seperate projects on same Heroku machine. I have React application for frontend and nodejs server in the back.

They are connected over localhost in my machine with the following structure. In the react side, with following client structure, I can see the Connected to : localhost:5000 is printed. :

import openSocket from 'socket.io-client';
socket = openSocket("http://localhost:5000");    
socket.on("connect", () => {
    console.log("Connected to : http://localhost:5000");
});

Node Side is like following and Client connected is printed in my local machine:

const server = require('http').createServer();
const io = require('socket.io')(server);
server.listen(5000, function(err) {
    if (err) throw err;
    console.log('Server Listening on port:', 5000);
});
io.on('connection', (client) => {
    console.log("Client connected!");
}

After that I deployed my projects on 2 different clusters in Heroku. NodeJS works on https://<herokuname>.herokuapp.com/ So I wonder that to write in the openSocket method in React side in order to connect socketio connection on that domain. I tried followings but none of them worked :

https://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket

https://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket

ws://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket

ws://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket

Upvotes: 2

Views: 304

Answers (1)

dvlsg
dvlsg

Reputation: 5538

You have to bind your server to a specific process.env.PORT provided to you by Heroku for web dynos.

const server = require('http').createServer();
const io = require('socket.io')(server);
const PORT = process.env.PORT || 5000;
server.listen(PORT, function(err) {
    if (err) throw err;
    console.log('Server Listening on port:', PORT);
});
io.on('connection', (client) => {
    console.log("Client connected!");
}

Once that's working, you should be able to just hook up to the root heroku server URL from your client.

import openSocket from 'socket.io-client';
const url = "https://<herokuname>.herokuapp.com"
socket = openSocket(url);    
socket.on("connect", () => {
    console.log("Connected to:", url);
});

Here are some relevant docs on the subject, noting that you'll probably want session affinity turned on if you plan on using socket.io in heroku:

https://devcenter.heroku.com/articles/dynos#local-environment-variables https://devcenter.heroku.com/articles/session-affinity

Upvotes: 1

Related Questions