Deploying Node Server on Heroku

Deploying Node Server on Heroku

Hello, welcome to my blogpost.

Today, we would be deploying our node server on heroku and connect it to our postgres database on heroku.

Install Heroku CLI

If you haven't already, download and install Heroku CLI into your device. Click this link and follow their download instructions.

Next, Sign up for Heroku account here for free.

Once you're done with these, you can proceed to your terminal

STEP 1. Login on Heroku

Run the command:

$ heroku login

to login to your account.

Logging in... done
Logged in as t****@gmail.com

will be displayed to your terminal once you're logged in to Heroku.

STEP 2. Create the App on Heroku

Once you're logged in, Locate and Ensure you are in your project/app folder in your terminal. Make sure the project is pushed to your GitHub or other remote repo before you begin. Then run the command:

$ heroku create

This will create your app on Heroku (which prepares Heroku to receive your source code) and generates two links:

Creating app... done, ⬢ infinite-depths-43309
https://infinite-depths-43309.herokuapp.com/ | https://git.heroku.com/infinite-depths-43309.git

The first link is the URL where you’ll see your app live. The second link is the GitHub repo provided by Heroku you’ll need to push your app to in order to deploy it.

STEP 3. Set the Node Server Configuration

$ heroku config:set NPM_CONFIG_PRODUCTION=false

This command will tell Heroku to install the devDependencies like nodemon and so on. More precisely, this skips the pruning step and accesses the packages declared under devDependencies at runtime. This enables Heroku to launch npm run build.

STEP 4: Confirm a remote Named Heroku has been set for your App

Use git remote command to confirm that a remote named heroku has been set for your app:

$ git remote -v
heroku  https://git.heroku.com/thawing-inlet-61413.git (fetch)
heroku  https://git.heroku.com/thawing-inlet-61413.git (push)

STEP 5: Deploy your app to Heroku

Finally all that’s left to do is stage, commit, and push our configured app to Heroku. To deploy your app to Heroku, you typically use the git push command to push the code from your local repository’s master or main branch to your heroku remote, like so:

$ git push heroku master

You can use this same command whenever you want to deploy the latest committed version of your code to Heroku.

And now the app should be on Heroku, but it won't work yet because it is not connected to any MySQL database.

The one we have been using to test is only local. We need a service provider called Knex to help us connect to a PostgresQL database for our app.

Connecting to database

Provisioning Heroku Postgres

  • Before you provision Heroku Postgres, confirm that it isn’t already provisioned for your app (Heroku automatically provisions Postgres for apps that include certain libraries, such as the pg Ruby gem).

  • Use the heroku addons command to determine whether your app already has Heroku Postgres provisioned:

$ heroku addons

Add-on                                                      Plan       Price  State
──────────────────────────────────────────────────────────  ─────────  ─────  ───────
heroku-postgresql (postgresql-concave-52656)                hobby-dev  free   created

If heroku-postgresql doesn’t appear in your app’s list of add-ons, you can provision it with the following CLI command:

$ heroku addons:create heroku-postgresql:<PLAN_NAME>

For example, to provision a hobby-dev plan database:

$ heroku addons:create heroku-postgresql:hobby-dev
Creating heroku-postgresql:hobby-dev on ⬢ sushi... free
Database has been created and is available
 ! This database is empty. If upgrading, you can transfer
 ! data from another database with pg:copy
Created postgresql-concave-52656 as DATABASE_URL

To see all PostgreSQL databases provisioned by your application and the identifying characteristics of each (such as database size, status, number of tables, and PG version), use the heroku pg:info command:

$ heroku pg:info
=== DATABASE_URL
Plan:                  Hobby-dev
Status:                Available
Connections:           0/20
PG Version:            13.4
Created:               2021-10-04 07:57 UTC
Data Size:             7.9 MB/1.00 GB (In compliance)
Tables:                0
Rows:                  0/10000 (In compliance)
Fork/Follow:           Unsupported
Rollback:              Unsupported
Continuous Protection: Off
Add-on:                postgresql-silhouetted-34078

This shows your postgres status, here with 0 connections and 0 tables created.

Step 3: Establish psql sessions with your remote database. Run the command:

$ heroku pg:psql
--> Connecting to postgresql-silhouetted-34078
psql (12.2, server 13.4 (Ubuntu 13.4-1.pgdg20.04+1))
WARNING: psql major version 12, server major version 13.
         Some psql features might not work.
WARNING: Console code page (437) differs from Windows code page (1252)
         8-bit characters might not work correctly. See psql reference
         page "Notes for Windows users" for details.
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

secure-beach-13578::DATABASE=>

Now, we are in our database and we can carry out different database operations, Let's create a LOGIN table for example;

secure-beach-13578::DATABASE=> CREATE TABLE login(
secure-beach-13578::DATABASE(> id serial PRIMARY KEY,
secure-beach-13578::DATABASE(> hash varchar(100) NOT NULL,
secure-beach-13578::DATABASE(> email text UNIQUE NOT NULL
secure-beach-13578::DATABASE(> );


CREATE TABLE

and that would successfully create our login table.

If you have more than one database, specify the database to connect to (just the color works as a shorthand) as the first argument to the command (the database located at DATABASE_URL is used by default). Run:

$ heroku pg:psql gray

Connecting to HEROKU_POSTGRESQL_GRAY... done
...

Connecting the database in Node.js

In this case, the database would be connected to the server through the use of a tool called KNEX.JS. Knex is a query builder that allows us to create queries using Javascript syntax. It will then translate our syntax into the appropriate SQL for each supported database

Install the libraries:pg for PostgresQL and KNEX in your Node.js server. Run the commands:

$ npm install pg
$ npm install knex
  • Initialize the KNEX library and connect to process.nv.DATABASE_URL when your app initializes.
const knex = require("knex");

const database = knex({
  client: "pg",
  connection: {
    connectionString: process.env.DATABASE_URL,
    ssl: {
      rejectUnauthorized: false,
    },
  },
});

And you can easily query this database.

ooops. That has been quite a nice ride, right :). Let's wrap it up ugh 😉.

Finally all that’s left to do is deploy the latest committed version of your code on Heroku

  • Stage, commit, and push the configured app to Heroku following the same process discussed earlier. and Our Server is live!!!!.

Hooray! We have deployed our React Express app to Heroku, we have successfully set up our Postgres database, what else?

Well, if you go to deployed frontend app website or your local frontend app (in my case it is smart-brainimage.herokuapp.com), you will notice that the client cannot request anything from the server. The console sends a 404 error because the URL we fetch in our React app were all localhost:3000 initially, instead of stark-eyrie-75623.herokuapp.com (deployed server).

To fix this error, change all URLs in App.js and the other components that fetches that from the server.

And now our app should work perfectly!

Thanks for reading!

Cheers!