Setup Socket.io Nodejs Server on Heroku

It’s all free

Terence Tsang
2 min readMay 9, 2019

Key Remarks

  • Install Heroku CLI
  • We have to use the environment port: Number(process.env.PORT || “80”). It will use 80 port to map into the internal port
  • Heroku will use Free Dyno to host the application. When there is no activity, the application will auto shutdown. Check Used Dyno Hours
  • heroku ps // check free dyno hours
  • You can deploy multiple process

Setup Project & Deployment

heroku login
npm init // create new node project
git init // init git
git add . // add files
git commit -m "Initial commit" // commit the files
heroku create // create app on heroku
// or
heroku git:remote -a heroku-testing // add by project name
// Deployment Belowgit add .
git commit -m "New commit"
git push heroku master // deploy
heroku logs -n 200

.gitignore

/node_modules
npm-debug.log
/*.env
.idea

Package.json

{
"name": "heroku-testing",
"version": "1.0.0",
"description": "",
"main": "build/App.js",
"dependencies": {
"socket.io": "^2.2.0",
"socket.io-client": "^2.2.0",
"debug": "^4.1.1"
},
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/mocha": "^5.2.6",
"@types/node": "^11.13.5",
"@types/socket.io": "^2.1.2",
"@types/socket.io-client": "^1.4.32",
"@types/debug": "^4.1.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"source-map-support": "^0.5.12",
"ts-node": "^8.1.0"
},
"scripts": {
"start": "set DEBUG=app* & node build/App.js",
"logs": "heroku logs -n 350",
"commit": "git add . & git commit -m 'auto' & git push heroku master",
"test local": "set DEBUG=app* & node build/TestLocal.js",
"test production": "set DEBUG=app* & node build/TestProduction.js"
}
}

Create Socket.io Server

Create Socket.io Client

Testing Script

Replace the host with the public domain of Heroku

import {SocketClient} from "./SocketClient";

const socketClient: SocketClient = new SocketClient("http://127.0.0.1:80", "userId=1");

--

--