How to deploy Node.js projects to Heroku
Tags: node, expres, heroku, javascript
Published: 2022-07-16 15:02:00

If you have developed a Node.js project for your backend, you might have wondered where can I host it?

If you have developed something as a hobby or need to do some experimenting or PoC, then [heroku](https://www.heroku.com/) is the best place to start.

In this article, we will discuss 2 different ways to deploy your projects to heroku and how much does it cost to have your project hosted in heroku.

## Project Setup

First, let's create a sample Node.js project for this demonstration. Go to your terminal, navigate to the directory where you would like to create the project, and create a folder called `nodejs-using-heroku-cli`

Then run the following command to initialize an npm project with default settings:

```bash
npm init -y
```

Now open the folder in the code editor of your choice and you will see `package.json` created.
Update it with the start command as shown below:

```json
{
  "name": "nodejs-using-heroku-cli",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
```

Now open the terminal and install express.js to create the webserver using the following command:

```bash
npm i express
```

Now create a file named `index.js` in the root directory with the following content:

```js
const express = require("express")
const app = express()
const port = process.env.PORT || 3000

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

app.listen(port, () => {
  console.log(`Example app listening at Port: ${port}`)
})
```

Now start the application by running `npm start`
and open [http://localhost:3000/](http://localhost:3000) in your browser and you should be able to see the response as shown below:


 ![npm start response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oado38pvh2zqqifns07q.PNG) 

## Deploying to Node.js using Heroku CLI

First, go to [heroku.com](https://signup.heroku.com/) and register a free account for yourself.

Once you have registered, you will be able to see the [dashboard](https://dashboard.heroku.com/apps) as shown below
(of course you will not have any projects yet.):

![heroku dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/smvpupznfv2xomk1op07.png)

In the right top corner, click on New > Create New App.

You will be redirected to a page as shown below. Provide the project name and click on the 'Create App' button.

![Creating new Project Heroku cli](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4zx0h49tto9vhoa42s0.PNG)
 

Now your project will be ready. In the next section, we will see how to deploy it using heroku CLI.

### Installing the Heroku CLI

There are different ways to install the heroku CLI as mentioned in their [documentation](https://devcenter.heroku.com/articles/heroku-cli).
Since we are deploying a Node.js project, I will prefer installing via npm.

Run the following command so that the CLI gets installed globally:

```bash
npm install -g heroku
```

Once the installation completes, log in to heroku via the command prompt by running the following command:

```bash
heroku login
```

This will open a browser tab, something similar as shown below and you will have to click on the Login button:

![heroku CLI login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5i2chczuy1a69airy2wu.png)
 

Once you have logged in successfully, initialize a git repository in your project by running:

```bash
git init
```

> If you do not have git installed on your machine you can download it from [here](https://git-scm.com/downloads).

Once the git is initialized, create a file named `.gitignore` in the root directory of the project with the following content:

```.gitignore
node_modules/
```

In this way, we are telling git not to push `node_modules` to the repository.

Now link your repo to the heroku remote repo by running:

```bash
heroku git:remote -a nodejs-using-heroku-cli
```

Now add the files to the repo and commit it using:

```bash
git add .
git commit -am "first commit"
```

Finally, deploy the files to heroku by pushing the changes (if your branch name is `main`, then replace `master` with `main`):

```bash
git push heroku master
```

After a few minutes, the deployment should be complete and you will be able to see the following logs in the console:

![heroku cli deploy success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghe3p6jxbt32lfxr3ir3.png) 

Click on the link highlighted above and you should be able to see your application deployed.

![heroku cli browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ru343herzyqnpkng7fai.png)

 
### Deploying updates

When you want to deploy new changes, all you need to do is to run the following commands:

```bash
git add .
git commit -am "make it better"
git push heroku master
```

## Deploying Node.js to Heroku using GitHub

If you store your project in [GitHub](https://github.com/), then you can integrate it with heroku.

First create a Node.js project called `nodejs-using-github`, as we have done earlier.
Now create a [git repo](https://github.com/new) in the same name and push your changes to GitHub using the following command:

```
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/collegewap/nodejs-using-github.git
git push -u origin main

```

Now your code will be pushed to GitHub.
You may [fork this repo](https://github.com/collegewap/nodejs-using-github), in case you need to avoid the above steps.

Now create a new app in the heroku dashboard as we have [done before](#deploying-to-nodejs-using-heroku-cli).

Once the project is created, navigate to the deploy tab (if you have not already), and click on "Connect to GitHub"

 ![heroku connecting to github](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvipjm4phzufie7vwda3.png)

Once you have authenticated, search for the repo to be deployed and click on 'Connect'

![heroku connecting to github 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/487w29bjkhq2vc1f16qb.png)
 

Now you can click on 'Deploy Branch' and deploy your project to Heroku.

![deploy branch](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gm6dbywrs45gjqhjnomy.png)
 

### Enabling automatic deploys in Heroku from GitHub

You may enable automatic deploys by clicking on 'Enable Automatic Deploys'
so that whenever you push a change to GitHub, it will be automatically deployed to Heroku.

![enable automatic deploys from github heroku](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/piw118664xjjrqs3r5mv.png)

## Heroku Pricing

Heroku is free to start with, which can be used for non-commercial and personal projects.
If you want to scale you will have to pay monthly a fee.
Here is the snapshots of the pricing, you can see their latest pricing on their [pricing page](https://www.heroku.com/pricing#containers).

![heroku pricing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x4pkxt02pza5cawkhgh.png) 

### Dynos in Heroku

Heroku has a concept called Dynos. The free tier offers you 550 dyno hours per month.
That is, your app can run for 550 hours in a month.
However, we know that there are on average 720 hours in a month.
To increase this limit to 1000 dyno hours a month, you can add your credit card details in the [billing section](https://dashboard.heroku.com/account/billing).
You will not be charged as long as your monthly utilization is under 1000 dyno hours.

### Idling of dynos

If you are in the free plan, your server will go to sleep once it is idle for more than 15 minutes.
You can prevent this either by upgrading to hobby plan or by having addons like [new relic](https://newrelic.com/).

You could also set up a cron job to hit your endpoint every 15 minutes using services like [cron-job.org](https://cron-job.org/en/)
so that your app doesn't go to sleep.