How to deploy HapiJS, Socket.IO in a single port on Heroku

In the previous article I showed you how to create a HapiJS and Socket.IO server and sharing data between them using the EventEmitter in NodeJS.

Now I want to share with you how to deploy the created application on Heroku and where is the trick in the deploy. Heroku does not allow you to use more than 1 port, so you cannot have the REST server running on port 8080 and the websockets server running on 8081 ports. That means either you have to run them on separate applications and make them connect through RabbitMQ or something else or you have to run them on the same port.

Socket.IO grabs all the requests first when given a port and if it sees that the request is not for it it forwards it to the next listener. That means you can run both HapiJS and Socket.IO on the same port. To achieve it our previous code requires just a little modification:

var server = new Hapi.Server();
var serverPort = process.env.PORT || 8080

server.connection({ port: serverPort, labels: ['api', 'ws'] });

var apiServer ='api');
var wsServer ='ws');

If you remember in the previous example we had two different connections like this:

server.connection({ port: 4000, labels: ['api'] });
server.connection({ port: 4001, labels: ['ws'] });

Now we need just one connection and both servers point to it. Now everything will be working and we get the available port from the ‘process.env.PORT’ variable from Heroku. So you can now test that both REST and Sockets are running on the same url address. You just connect to ‘’ for either REST or Websocket communication.

And it works on Heroku!

You may also like...