Pushing to GitHub and Hosting on Heroku With Postgres for Free
Tags: todayilearned, github, heroku, tutorial
Published: 2020-06-15 23:17:36

I have decided to make this tutorial because even though there are a number of tutorials out there on hosting on [Heroku](https://heroku.com/), I couldn't find many that are so detailed like this one you are about to read.

After creating applications, it is our desire to share it and let people use it because our efforts might be a waste if no one uses it. To make this possible, [Github](https://github.com/) and [Heroku](https://heroku.com/) provides us with certain services to showcase our work/project for free.


**Jump to:**
[Uploading to GitHub](#1)
[Deploying to Heroku](#2)
[Adding Heroku Postgres](#3)
[Prepare our database connection to match that of Heroku](#4)
[Export Database and tables](#5)
[Let GitHub Know that we made some recent changes](#6)
[Finally deploying our App](#7)
[Fixing Heroku Application Error](#8)


In the course of this tutorial, I will be walking you through uploading our [node-posgres-cloudinary project](https://github.com/EBEREGIT/server-tutorial) from the [last article]() to [Github](https://github.com/) and deploying it to [Heroku](https://heroku.com/).

If you intend to use the project that I am using for this tutorial, please do the following:

1. Clone the project [here](https://github.com/EBEREGIT/server-tutorial).
2. Delete the ``.git`` file that may have come with it. Another ``.git`` file will be created for you in the process of you pushing to GitHub.

So without further ado, let's get our hands dirty.

![let's get our hands dirty](https://media.giphy.com/media/mCRJDo24UvJMA/giphy.gif)

<a name="1"></a>
## Uploading to GitHub
Uploading or pushing to GitHub is as easy as taking your favorite meal. Please checkout any of the following links to get directed on just how to push your project from you local machine to GitHub

1. [Adding an existing project to GitHub using the command line](https://help.github.com/en/github/importing-your-projects-to-github/adding-an-existing-project-to-github-using-the-command-line)

2. [Adding an existing project to GitHub using the command line](https://www.softwarelab.it/2018/10/12/adding-an-existing-project-to-github-using-the-command-line/)

3. You can jump to [Let GitHub Know that we made some recent changes](#6)

<a name="2"></a>
## Deploying to Heroku
I am going to make this process so easy that you will just smile throughout. 

As a prerequisite, please you may need to have taken the [last tutorial](https://dev.to/ebereplenty/nodejs-code-structure-optimization-with-express-routing-5fna). This will have helped you setup PostgreSQL and cloudinary. 

However, if you are just interested in seeing how a nodejs project is deployed on Heroku, let's proceed.

* Let's begin by creating an account on [Heroku](https://heroku.com/)


*If you have created an account, you may have been prompted to create an app (i.e. a folder where your app will be housed). You can choose to do that and continue [here](#7)*


> Since we are working with PostgreSQL and cloudinary, let's use our terminal.

* Please open your project in a terminal if you have not done so already. *I will be using the VS Code terminal*.

* Install Heroku CLI

```javascript
npm install heroku
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/716g1v0nnea93rdrhmk5.JPG)

* Login to Heroku CLI. This will open a browser window, which you can use to log in.

```javascript
heroku login
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bky4mywipzua8cj6d0kf.JPG)

* Create an app *(It can be any name. I am using ``node-postgres-cloudinary``)*

```javascript
heroku create node-postgres-cloudinary
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ibofc7xcyqgi165f5dz1.JPG)

* Go to your [Heroku dashboard](https://dashboard.heroku.com/apps) and you will find the newly created app. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d84emoge8pi9qt0a2qrb.JPG)

> Waalaah!!!

That is how mine looks in the image above. I have some apps there already but you can see the one I just created. 

**Let's now add PostgreSQL database to the app.**

<a name="3"></a>
### Adding Heroku Postgres
* Click on the app you just created. *(It will take you to the app's dashboard)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/g48iadulci1evt6j8ftf.JPG)

* Click on the ``Resources`` tab/menu

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e6bvzsv7cn6ebgwi0y65.JPG)

* In the ``Add-ons`` Section, search and select ``Heroku Postgres``

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/91nwppclfdkvitp56rrj.JPG)

* Make sure you select the ``Hobby Dev - Free`` plan in the pop-up window that follows

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hd7zj1qa2t4e051zn654.JPG)

* Click on the ``provision`` button to add it to the app like so:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8w2z6tok8plmp154ovuj.JPG)

* Click on the ``Heroku Postgres`` to take you to the ``Heroku Postgres`` dashboard.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nvrdf902ypuz2frqiu1q.JPG)

* Click on the ``settings``

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6k81alizfc5yzgtbzlcv.JPG)

<a name="10"></a>
* Click on ``View Credentials``

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/33p2ceyfkbmr590s1r6b.JPG)

<a name="9"></a>
* In the Credentials, we are interested in the Heroku CLI. We will be using it in a bit.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xzmtjtqrg8a5vqrfjkg3.JPG)

> Back to the terminal

* Let's confirm if the ``Heroku Postgres`` was added successfully. Enter the following in the terminal

```javascript
heroku addons
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7hhl70mw99b2mrji9i35.JPG)

Yeeeeaaaah!!! It was added successfully.

<a name="11"></a>
**Before we proceed, please ensure that your PostgreSQL ``path`` is set correctly if you are on windows. Follow this [link](https://www.computerhope.com/issues/ch000549.htm) to learn how to set a ``path``. The path should be like this: ``C:\Program Files\PostgreSQL\<VERSION>\bin``. The version will depend on the one installed in you machine. Mine is: ``C:\Program Files\PostgreSQL\12\bin`` since I am using the ``version 12``.**

*The following image might be helpful*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dl3wv0z1dtvyjvvusx26.JPG)

*You may have to navigate to the folder where PostgreSQL is installed on your machine to find out you own path*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bzf04c5827d4tri3ngrg.JPG)

* Login into the ``Heroku Postgres`` using the [Heroku CLI](#9) from our ``Heroku Postgres`` [credentials](#10). *This is mine. Yours will be different*

```javascript
heroku pg:psql postgresql-slippery-19135 --app node-postgres-cloudinary
```

**In case you got an error, it is most likely, that your [path](#11) is not set properly**

<a name="4"></a>
### Prepare our database connection to match that of Heroku

At the moment, my database looks like this:

```javascript

const pg = require("pg");

const config = {
  user: "tutorial",
  database: "tutorial",
  password: "tutorial",
  port: 5432,
  max: 10, // max number of clients in the pool
  idleTimeoutMillis: 30000,
};

const pool = new pg.Pool(config);

pool.on("connect", () => {
  console.log("connected to the Database");
});

```

If you try connecting Heroku to this, you are going to get an error. This is because Heroku has a ``connection string`` setup already. So we have to setup our connection such that Heroku can easily connect. I am going to refactor my database connection file (``dbConnect.js``) and ``.env`` file to make this happen.

* dbConnect.js
```javascript

const pg = require('pg');
require('dotenv').config();

// set production variable. This will be called when deployed to a live host
const isProduction = process.env.NODE_ENV === 'production';

// configuration details
const connectionString = `postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}`;

// if project has been deployed, connect with the host's DATABASE_URL
// else connect with the local DATABASE_URL
const pool = new pg.Pool({
  connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
  ssl: isProduction,
});

// display message on success message if successful
pool.on('connect', () => {
  console.log('Teamwork Database connected successfully!');
});

```

* .env file
```javascript

DB_USER="tutorial"
DB_PASSWORD="tutorial"
DB_HOST="localhost"
DB_PORT="5432"
DB_DATABASE="tutorial"

```

With the setup of the ``dbconnect`` and ``.env`` file, we are ready to export our database and tables from our local machine to ``heroku postgres``.

<a name="5"></a>
### Export Database and tables
> Go to your ``pgAdmin`` and locate the database for this tutorial. *Mine is tutorial*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m454dij54j7dghsxqa25.JPG)

* Right-Click on it and select ``Backup``. *(This will bring up a new window)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u57h6kpw5gtbhublc1la.JPG)

* Enter a name for the SQL file like I did
* Select ``plain`` format
* Click Backup. *(This will save the file to your documents folder)*
* Locate the file and move it into the project directory. *It can be anywhere in the directory but I choose to move mine into the ``services`` directory because it holds my database related files*

> Back in terminal, navigate to the folder containing the SQL file and run the following code to add the tables we just exported to the ``heroku postgres`` database

```html
cat <your-SQL-file> | <heroku-CLI-from-the-heroku-posgres-credentials>
```

This is what mine looks like:

```javascript
cat tutorial.sql | heroku pg:psql postgresql-slippery-19135 --app node-postgres-cloudinary
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/67x0f9521g5savkrafpc.JPG)

**Notice that I changed directory to services (``cd services``)? That is where my ``sql`` file is located**

> WOW!!! We have just successfully exported our database and tables to heroku.

**It is almost over**

<a name="6"></a>
### Let GitHub Know that we made some recent changes
* Add the files we have made changes to 

```javascript
$ git add .
```
*The period (`.`) adds all files*

* Commit your latest changes

```javascript
$ git commit -m "refactored the dbConnect and .env file to fit in to heroku; Added the database SQL file"
```

* Push the committed files
```javascript
$ git push origin -u master
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/u8kogsya1gt3uxnujz35.JPG)

<a name="7"></a>
### Finally deploying our App
* Go to you app's dashboard

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4j4bi64n0f0bp65j7pb7.JPG)

* Select the GitHub Deployment method

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5edwt90cpy75b3uyqgvy.JPG)

* Search and select a repo
* Click on ``connect``

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ifg4zh7jzab3edpaxvnf.JPG)

* Select the branch you want to deploy *(In my own case, it is the ``master`` branch)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4ka9c6781vft1gio7p0k.JPG)

* Enable automatic deployment by clicking ``Enable automatic deployment`` button as in the image above.

* Click on the ``Deploy`` button in the manual deploy 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ksrclnfyjzzvn2nr4gc.JPG)

*We will not have to do all these for subsequent deployment*

* Now you have a button telling you to "view site" after build is completed. Click it. *(This will open your app in a new tab)*

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9xi5vx6lx99z49uscre6.JPG)

**OHHH NOOOO!!!! A BUG? APPLICATION ERROR?**

![Tired](https://media.giphy.com/media/l1KVaj5UcbHwrBMqI/giphy.gif)

> Well, it just a small issue. Something you should never forget to do while making deployments. Most hosting service will require it

<a name="8"></a>
### Fixing Heroku Application Error
> Get back to the root directory of your project

* Create a file and name it `Procfile` *(It has no extension)*
* In the file, enter the following

```javascript
web: node index.js
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k3jb0rof1g6bs1zs2eh6.JPG)

*This directs Heroku to the server file (``index.js``) which is the entry point of the application. If your server is in a different file, please modify as required*

* Save the file
* Push the new changes to GitHub
* Wait 2 to 5 minutes for Heroku to automatically detect changes in your github repo and effect the changes on the app.
* You can now refresh that error page and see your hard work paying off

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n4t9yp4598wc5i7v8p82.JPG)

You can also test the ``retrieve image`` route and see it working.

Congratulations on reaching this milestone!!!

![Congratulations](https://media.giphy.com/media/KYElw07kzDspaBOwf9/giphy.gif)

Other routes **(persist-image, update-image and delete-image)** will not be working because we have not provisioned or added ``cloudinary`` add-on. It is as simple as the ``PostgreSQL`` one we just did.

We would look into it in a future tutorial.

We will also be documenting out APIs with postman soon.

### Conclusion
Starting from the onset till the end, it has been a juicy tutorial as we were tapping from the free gifts of Github and Heroku. 

It is important that your projects are showcase-able especially to employers and clients. That is another reason I have made this tutorial.

In a future tutorial, I will be diving into some other fun stuff. See you soon!

Meanwhile, drop your comments and/or questions in the comment section.