+91 9404 340 614    gyaanibuddy@gmail.com

Like
3 Likes

Hosting node.js app on heroku in less than 5 mins.

Last updated on March 3, 2021, 6:21 a.m. by rugved

Image desc
This blog will explaing how to hosting node.js app on heroku in less than 5 mins.

Introduction

I still remember as a beginner i always wanted to host my website. I was just obsessed with the thought of building a website and having a url which i can visit from anywhere. Lets see how to do it for free.

Prerequisites

  • Basic understanding of node.js and github
  • Git installed
  • Heroku free account

What are we building

In this blog with minimum steps we will host node js website on heroku. Heroku docs are pretty good but i as a beginner found it difficult as it explains everything in detail providing unnecessary explanation which scared me away as a beginner. This blog is contains only necessary and easy to follow steps to host node.js app

Even though we are going to host simple node.js app but you can extend it for node apps containing multiple routers,controllers,database etc.

If you are need database in your app you can use mongodb atlas.

Setup

  • Open cmd 
  • Check if node is installed
node -v
  • Create a project directory and cd into it.
mkdir nodejs-heroku
cd nodejs-heroku
  • Initialise project. This command will create a package.json inside project root directory.
npm init -y
  • Install required npm packages 
npm i express
  • Create index.js file inside project directory. This is how your folder should look like.

  • Add the following code to index.js. Basically this is code will run a server which will display “Hello World” when we visit it in browser.
const express = require('express')
const app = express()
const port = process.env.PORT || 3000

/* 
    Incase you are using mongodb atlas database uncomment below line
    and replace "mongoAtlasUri" with your mongodb atlas uri.
*/
// mongoose.connect( mongoAtlasUri, {useNewUrlParser: true, useUnifiedTopology: true})

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})
  • cd to project directory and run the server by entering following in cmd
node index.js

  • Now think about it. You manually executed the “node index.js” command, but when we will host it on heroku, how will heroku know what script needs to be executed. Lets see how to do it.

Open “package.json” file and you will see “scripts” key. 

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

Replace it with:

"scripts": {
    "start": "node index.js"
},

To understand why we did this, read the following and you will see that to tell heroku what to execute we need to add either make Procfile or add command we want to execute into “start” tag in “package.json”.

  • One more thing we need to do is tell heroku which version of node js we want to use.

https://devcenter.heroku.com/articles/deploying-nodejs#prerequisites

  • Add the above “engines” tag and after completing it this is how “package.json” should look like.
{
  "name": "nodejs-heroku",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "engines": {
    "node": "10.x"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}

Initializing git

Here i am not explaining each command because i am assuming you know basics of git. Even if you don’t know just execute them for now.

git init
git add .
git commit -m "first commit"

Github

  • Visit https://github.com/ and login
  • Create a new repository. You will be shown a page like this. 

  • Copy the line i highlighted in the above image. It will be different for you based on username and project name. For me it was
git remote add origin git@github.com:RugvedB/Nodejs-Heroku-Deploy-Demo.git
  • Paste it cmd and press enter. 
    Doing this will tell git that whenever we perform any action like pushing,pulling the code we want it with respect to this repository which we just mentioned.
  • Now push the code to github.
git push origin master

  • After successfully executing above command refresh github page and you will see that you code has been pushed to github.

We did this so that we can later tell heroku to refer to this github repository for code.

https://github.com/RugvedB/Nodejs-Heroku-Deploy-Demo

Heroku

  • Login to heroku by executing the following in cmd.
    If you don’t have heroku cli installed visit here.
heroku login
  • After login is successful go to https://dashboard.heroku.com/apps you will list of apps created on this account. 
  • Click on “New” -> “Create new app” button at top right.
  • Give a name to you app and click “Create app”. Note that this needs to be a unique name. 

  • You will be redirected to a new page where find the “Deployment method” section and click on Github.
  • Enter the repository name -> click search -> Select correct repository -> Click connect.

  •  Click on “Enable automatic deploys” button which would mean that whenever you add any code to your github repository heroku will update your hosted app too.
  • And finally click on “Deploy branch ”. Wait for a couple of minutes and let the deploying process finish.
  • After successfully deploying the website you will get success message as shown.

  • Click on “View ” to visit the website hosted by you.

Even thought its a very simple app but the above steps can be followed to build apps with complex structure too. 

Yay! That’s all is needed to host a node.js app.

 

Setup config vars

Everything is done. You don’t need to follow this unless required.

Here is answer to one of the most frequently asked question.

If you have added some secrets like email,password, mongodb atlas uri etc then in the code you shouldn’t direct paste it, instead put the following in the code and set its value in heroku “config vars” section here.

Eg

// In the code
process.env.EMAIL_PASSWORD

Setting config vars on settings page

Thank you! Drop a like if you found it helpful!

Conclusion:

We successfully learnt how to deploy node.js app and how to set config vars on heroku.

For code you can visit https://github.com/RugvedB/Nodejs-Heroku-Deploy-Demo

 

...

by rugved
KJ Somaiya College of Engineering Mumbai

Avid learner
blog comments powered by Disqus