Deploy Angular App & Node.js API with PostgreSQL On Heroku

Vipasha Vaghela
8 min readJul 4, 2020

--

Software deployment is the process that make a software system available for use. Here we are going to deploy an Angular app with node.js API and also we are going to see how to set postgreSQL database on Heroku.

Prerequisite

Downloaded Heroku CLI on your computer system.

If you do not have downloaded yet then download it from https://devcenter.heroku.com/articles/heroku-cli

You must have Node.js and Angular CLI on your system.

Heroku Account Setting

At very first we have to create account to heroku.

Get signed up on heroku: https://signup.heroku.com/

If you have account then you can directly login .

After logged in successfully create a new app there..

First create an app for node.js API.

here we have to create both app separately for an Angular and node.js.

At first create for node.js API. before you do all these things you must have a server node.js app which works on localhost. Your all the connections are there in index.js file.

There are all the steps mention on Heroku App Dashboard.

After creating an app on heroku let’s go to cmd.

Then move into your project directory .

First we have to login again in heroku from command line.

c:ProjectFolder/projectName/heroku login

After successfully login we have to initialize git to our project.

c:ProjectFolder/projectName/git init

After initializing git add remote origin for app to heroku. here you have to mention the name of your app.

c:ProjectFolder/projectName/heroku git:remote -a projectName

We have successfully initialized git to our app. these all the steps are given in our heroku dashboard.

Now We will go to our editer and open our node.js project .

Prerequisite for node.js APP

In node.js app you must have installed express, body-parser , cors and nodemon. Here we are going to use postgres as database so that it’s necessary to install pg.

if you don’t have installed yet then do follow steps

npm i express

npm i cors

npm i body-parser

npm i nodemon

npm i pg express (if you will integrate postgre as database)

If you are using postgre database, then we will add our all the query logics in another file named query.js

In index.js we will make an instance of all the installed packages.

const express=require("express");
const bodyparser=require("body-parser");
const cors=require("cors");
const db=require('./query');
//our all the query connections are there in query.js
const path = require('path');
const app=express();

Here we can use all the functions of installed packages through these constant variables.

var distDir = __dirname + "/dist/";
app.use(express.static(__dirname + '/public'));
app.use(express.static(distDir));
const port = process.env.PORT || 3333; //add your port no. here

Now will are going to declare dist folder and use it through express variable.

dist/ stands for distribution, and is the minified/concatenated version - actually used on production sites.

We have to initialized our port number and assigned to port variable .

app.use(cors());
app.use(bodyparser.json());
app.use(
bodyparser.urlencoded({
extended:true,
})
);
app.get('/',(request,response)=>{response.json({info:'Node.js,Express, and Postgres API'});
});
app.listen(port,()=>{
console.log(`App running on port ${port}.`);
})

body-parser:body-parser is an incredibly important package as it allows us to “parse” the data we are sending to the database to a specific format such as “json” therefore creating a middleware between our software and the end of the request as body-parser knows how to correctly read the body of the request.

here we have declare all the essential properties in index.js.

Our Index.js is looking like this.

const express=require("express");
const bodyparser=require("body-parser");
const cors=require("cors");
const db=require('./query');
const path = require('path');
const app=express();
var distDir = __dirname + "/dist/";
app.use(express.static(__dirname + '/public'));
app.use(express.static(distDir));
const port = process.env.PORT || 3333;
app.use(cors());
app.use(bodyparser.json());
app.use(
bodyparser.urlencoded({
extended:true,
})
);
//database endpoints will be hereapp.get('/',(request,response)=>{
response.json({info:'Node.js,Express, and Postgres API'});
});
app.listen(port,()=>{
console.log(`App running on port ${port}.`);
})

So this is our index.js file.

Remote PostgreSQL Database setting on Heroku

Now we will set up our postgre database on heroku.

https://devcenter.heroku.com/articles/heroku-postgresql#local-setup

To configure postgre database to our app we have to add some heroku addons.

heroku addons:create heroku-postgresql:hobby-dev

Through this command we can create postgre database on heroku. after creating database we can check information of database through below command.

heroku pg:info

So, we have successfully created remote database on heroku. now we are going to set our data collections(tables) there.

To establish a psql session with your remote database, use heroku pg:psql.

After hitting this command on cmd you will connect with your remote database and create tables there. Here i have created a demo table through psql.

tacconnect-api::DATABASE=> create table contact(cid serial primary key,name varchar(50),email varchar(50),contact varchar(50),message text,date date);

So we have done with our database!!

Now We have to set our database credentials to our node.js app.

Connect Database with Node.js App

Go to your Heroku app dashboard.

Go to Resource tab.

Click on Heroku Postgre addons.

By clicking on it you will reach to Heroku datastore.

On that tab click on setting.

Go to DataBase Credentials and copy all the fields .

Copy all the credentials from here and paste into your database connection file of node.js app(query.js).

const Pool=require('pg').Pool 
const pool=new Pool({
user:'user name',
host:'hostname',
database:'your database',
password:'your password',
port:port no.,
});

Your remote database setup is done!!

Now add ‘engines’ to your package. json file.

"engines": {
"node": "12.14.1" //put your node.js version
},

also add start point to script in package. json

"scripts": {
"start": "node index.js",//your server connection file
"test": "echo \"Error: no test specified\" && exit 1"
},

After some modification your package.json file will look like this.

Now generate a Procfile in your root directory and write ..

web:index node.js

Now, Our Node.js API app is ready to deploy!!

Do follow below steps to deploy..

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

After push on heroku master you will get url for you api.

Hit that URL to chrome and you can see the output.

Our Node.js API is successfully deployed!! now we can use it with our Angular app.

Deploy Angular App On heroku

Before Deploy and an angular to heroku , first you have to change your API URL from localhost to our new URL. You have to change it in environment.ts

export const environment = {
production: false,
Base_Url:'new URL',
};

Now We have to create another app on Heroku.

Again we have to follow above steps and we have to login again in heroku from command line.

c:ProjectFolder/projectName/heroku login

After successfully login we have to initialize git to our project.

c:ProjectFolder/projectName/git init

After initializing git add remote origin for app to heroku.

c:ProjectFolder/projectName/heroku git:remote -a projectName

After Successful initialization ,we have to create server connection file for angular app.

Create Server to run Angular App

Locally we run ng serve from terminal to run our app on local browser. But we will need to setup an Express server that will run our production ready app (from dist folder created) only to ensure light-weight and fast loading.

So create server.js file in your root directory.

after creating server.js we have to install express and path in order to create connection with server.

npm i express path

Initialization of server variables.

const express = require('express');
const path = require('path');
const app = express();

Initialization of Dist Folder and declare starting point of application

app.use(express.static(__dirname + '/dist/demopr'));
app.get('/*', function(req,res) {res.sendFile(path.join(__dirname+'/dist/demopr/index.html'));
});

Declare Port number

// Start the app by listening on the default Heroku portapp.listen(process.env.PORT || 8080);

So, Our server.js File will look like this..

After creating server.js file. We have to modify package.json file, before that ensure you have latest angular version or not.

Install latest angular into your application by running this commands in your terminal:

npm install @angular/cli@latest @angular/compiler-cli --save-dev

In your package.json, copy from devDependencies to dependencies

"@angular/cli": "~9.1.7",
"@angular/compiler-cli": "~9.1.9",

Create postinstall script in package.json

In “scripts”, add heroku-postbuild. this is used to build our angular project and create dist folder.

"heroku-postbuild": "ng build --prod"

Copy typescript version from devDependencies to dependencies.

"typescript": "~3.8.3",

Add NPM and node engines

we have to declare latest version of NPM and node engines in package.json ,which we have used in an application.

"engines": {
"node": "12.14.1",
"npm": "6.14.5"
}

you have to put all the versions according to you project. if you arn’t aware of version , you can check with ‘npm -v’ and ‘node -v’ commands

Install Enhanced Resolve

Run the command npm install enhanced-resolve --save-dev

Change start command

In package.json, change the “start” command to node server.js so it becomes:

"start": "node server.js"

Now our Angular App is ready to deploy!!

now commit changes and push to heroku..

Do follow below steps to deploy..

git add .
git commit -am "my heroku angular app"
git push heroku master

You will get your new URL after pushing it on heroku .

Hit URL to browser and see the magic!!! Our Angular App is live..

So, This is how we can deploy an Angular app with Node.js API and postgre Database.

--

--

Vipasha Vaghela
Vipasha Vaghela

Responses (1)