How to deploy Node.js app to Heroku using cli?

Puneet Billing
3 min readDec 20, 2020

Follow these steps to publish your Node app to Heroku in less than 10 mins.

Prerequisites: You have an account with Heroku, you have git cli and Heroku cli installed on your machine.

To install Heroku cli refer https://devcenter.heroku.com/articles/heroku-cli

Note: below cli commands are for Windows console. Commands for mac might differ.

Step 1: Create new folder using cli or however you prefer

mkdir <folder name>

mkdir HerokuNodeAppDemo

Step 2: Change your current directory to the new folder

cd HerokuNodeAppDemo

Step 3: Create package.json file

npm init

This will prompt you for some values, you can leave it blank and press enter. These properties can be modified from package.json file later on.

Step 4: Specify start command in your package.json file inside script object

"scripts": {
"start":"node index.js", // to be added manually
"test": "echo \"Error: no test specified\" && exit 1"
}
//Note: "node index.js" will run index.js file on start

Step 5: Create a file called index.js to create server and listen on a port

/*
index.js file content
creates a server listening on port that returns a 200 and text "Hello World"
*/
let http = require('http');
http.createServer((request, res)=>{
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
}).listen(process.env.PORT);

Step 6: To deploy app, first initialize the directory as github repo

git init

You will see a message similar to below:
Initialized empty Git repository in …./HerokuNodeAppDemo/.git/

Step 7: Add files to be included to run on Heroku and commit

git add . && git commit -m "First Commit"

Step 8: Create app in heroku

heroku create <appname>//You can leave app name blank and Heroku will use a random name to //deploy app

If you are not logged in , runheroku login to login to Heroku.

This will return the URL for the app that just got created

Example: https://git.heroku.com/still-hollows-33544.git

Step 9: Deploy app to Heroku

git push heroku master

Step 10: Open browser and run appname.herokuapp.com or use curl.

That’s it !

Extra:

You can below command to take a look at logs, in case your app is not working as expected

heroku logs --tail

You can also login to heroku.com and access logs or run your app.

Code Available at https://github.com/puneetpalkaur/HerokuNodeAppDemo

Reference: https://www.heroku.com/nodejs

--

--

Puneet Billing
Puneet Billing

Written by Puneet Billing

I’m a software engineer. I love programming and teaching CS and Maths.

No responses yet