27 March, 2021

Deploying a socket.io app

I was having trouble deploying a nodejs express web app that runs sockets in Heroku. The build kept logging

-----> Build failed

Without an explicit reason why. For this post, I'd like to document some mishaps I overlooked. Things you should keep in mind is that npm install looks for package.json in the root folder only. I had a git repo with both a root, frontend and server directory that each had its package.json. The solution is to build heroku from a subdirectory (the server) you can follow this tutorial

I was able to confirm the server was running using sh>heroku logs -a <app_name> --tail and seeing a console log I added on server start.

Another issue was the ports. Heroku dynos sets a new port with every build. So If your app is using socket.io, you want the connection URL to be set to port 80.

export const API_URL = hostName.includes("localhost") ? 'ws://localhost:3000' : `${host}:80/socket.io/?EIO=4&transport=websocket`;

your express server will then be opened using the current port like so:

const port = process.env.PORT || 3000;
http.listen(port, () => {
	console.log(`listening on ${process.env.API_URL}:${port}`);
})