Deploying a Node.js server-side backend CRUD REST service to Heroku connected to a cloud-based MongoDB Atlas database

Ezani
8 min readSep 3, 2021

--

In an earlier article, I showed how to write a CRUD REST service backend on localhost and node.js using Express.js and mongoose to connect to MongoDB non-SQL database (see Creating a fullstack REST backend with node.js, Express and MongoDB (mongoose) and creating React frontends using React Data Grid and Material-UI DataGrid to access the service).

In this article, I will show you how to deploy this CRUD backend to Heroku where it can be accessible to the world. Heroku provides cloud hosting services for node.js and other apps such as React, Angular and is free for sites with low usage and for testing. It also allows for hosted apps to link to cloud databases such as MongoDB Atlas to provide database services. In this article, we will setup our cloud MongoDB Atlas database first and then we will deploy our node.js app to Heroku and also update its database connection parameters so that it can connect to its new cloud database instead of the one on local.

(In order to follow this article properly, you might need to jump back and forth between this article and the one above in order to see the coding of the node.js REST backend CRUD app which was created.)

Setting Up MongoDB Atlas On The Cloud

The first thing we need to do is to create the schema or migrate or copy our locally-based MongoDB to the cloud using MongoDB Atlas. We will first need to open an account at mongodb.com if you haven’t got one already. We will see the screenshot similar to Figure 1 below. The first thing we need to do is create our database cluster from the Database Deployments screen. If we are registered using a Free Account, then we are only allowed one database cluster. Also when using this cloud database, make sure you use a mirror server which has the best connectivity and probably the one closest to you.

Figure 1 : Database Deployments screen at cloud.mongodb.com (MongoDB Atlas)

After our cluster has been successfully created, we can connect to it by clicking the Connect button. We need to create a connection IP address as well as create our Database User as shown in Fig 2 below.

Figure 2 : Connect to Cluster() in cloud.mondodb.com (MongoDB Atlas)

To connect to our cluster, I would recomment using the MongoDB Compass UI which we will need to download and install first on our local machine.

Figure 3 : Choose a connection method to connect to our database cluster

You will need to provide your connection string or connection parameters to connect to the cloud database. Your connection string can be found in the Cluster view when you click the Connect button.

Figure 4 : Paste connection string to connect to the database
Figure 5 : …or connect using connection parameters

You will not be able to successfully connect to the database until you provide an IP to allow authorised access. You can do this in the Add IP Access List Entry dialog. This should be your next step. You can use the default IP address : 0.0.0.0/0

Figure 6 : Add IP Access List Entry before you can connect to DB

This IP address will be stored in a list in the Network Access screen together with other IP addresses you may have which is authorised to connect and access the database.

Figure 7 : Network Access lists all the authorised IP able to access the DB

Ok, now we connect to the database cluster and the first thing we will do is create our database. Click the green CREATE DATABASE button. You should already see the standard admin, config and local databases already available in the list of databases.

Figure 8 : Databases list in cloud.mongodb.com (MongoDB Atlas)

Now we need to follow the schema we have created in our previously created CRUD node.js REST backend app (click the link to open the article on how to create the node app being referred to) by looking at the coding of the database model in the app. We create the test database as defined in our REST backend app and we create a users collection. We can directly add a row of test or sample data by clicking the green ADD DATA button in accordance with our CRUD node.js backend app (Fig 9).

(Correction- in our other article creating the node.js CRUD app, we created the database called my-app instead of test here. Please use the correct database name when connecting with mongoose in your code.)

Figure 9 : Adding sample data to our DB

Modifying Our Local Node.js CRUD Backend for Heroku

Now that we have setup our cloud MongoDB Atlas database, we can start to deploy our node.js backend app to Heroku. Before we do that, we will just need to update a few portions of our code to now access the cloud database instead of the one previously on local.

If we go back and look at our original code for local we have:

//Connect to Mongo DB — localmongoose.connect(‘mongodb://localhost:27017/myapp’, {useNewUrlParser: true}, () => {console.log(‘Connected to MongoDB…’);});

We now have to modify the code as follows to connect to the cloud by using the cloud-provided database connection string earlier:

//Connect to Mongo DB — now with cloud accessmongoose.connect(process.env.MONGODB_URI || ‘mongodb://localhost:27017/myapp’ || ‘mongodb+srv://<account_name>:<your_password>@cluster0.95wjk.mongodb.net/test’, {useNewUrlParser: true}, () => {console.log(‘Connected to MongoDB…’);});

Note that I have used the connection string directly as the mongoose.connect parameter but you can also use the environment parameter such as MONGODB_URI after defining it: process.env.MONGODB_URI.

You also need to change the listening port. Previously the default listening port for local was Port 3000 :

app.listen(3000);

But when our app is deployed in Heroku, we modify the coding as follows to connect to the listening port of Heroku by using our environment PORT parameter:

app.listen(process.env.PORT || 3000);

Finally, you will need to create an additional file called Procfile (just a text file without any filename extension) in your node.js backend Visual Code project. Heroku uses this Procfile to see which file is the default startup file which it first runs for our app.

Figure 9.1 : Procfile required in project for Heroku

Add this coding to your Procfile file:

web: node app.js

This tells Heroku to run your file called app.js first when it runs your application. You can change the name as you wish.

These are the three places you need to modify the code for Heroku and other parts of the node.js application remains the same.

Deploying to Heroku with Heroku CLI

The first thing you need to do is to create your account on Heroku (you can choose the Free or Paid/Premium versions depending on your requirements).

Once you have created your Heroku account, you should be able to access your default personal dashboard page from your browser as shown below.

Figure 10 : Your Heroku Dashboard

Now click the Deploy menu option (the third menu choice at the top) to go to the Deploy screen (Fig 11).

Figure 11 : Heroku Deploy screen

From the Deploy screen, you can see that there are three (3) ways to deploy your app to Heroku — using Heroku Git, GitHub or from the Command Registry. For both the Heroku Git and Command Registry options you will need to download the Heroku CLI to your local machine. If you already have GitHub where you store your code, then you can auto-deploy directly from GitHub.

In this article, I will show you how to deploy your app from Visual Code Express code editor using Terminal and Heroku CLI.

First, download Heroku CLI to your local machine here.

Figure 12 : Downloading Heroku CLI

After Heroku CLI installation has been completed, check that it has been installed properly by displaying its version. You can do this by opening a terminal in your Visual Code editor from your node.js backend app project.

Figure 13 : Checking Heroku version from Visual Code editor
> heroku --version
heroku/7.0.0 (darwin-x64) node-v8.0.0

Next login to Heroku by typing:

> heroku login
heroku: Press any key to open up the browser to login or q to exit
› Warning: If browser does not open, visit
› https://cli-auth.heroku.com/auth/browser/***
heroku: Waiting for login...
Logging in... done
Logged in as me@example.com

and keyin your credentials and ENTER to login to your Heroku account from your Visual Code terminal.

Next, create a new Heroku project by typing:

> heroku create <your-project-name-in-Heroku>

This project will be saved in Heroku cloud server.

Now you will need to download and install Git in your local machine (if you have not already got one) in order to commit and push your local node.js CRUD backend app to your Heroku cloud server. If your project folder does not have a Git repository, type Git init to create a repository in that folder for your Git operations.

Using Git To Deploy our node.js App to Heroku

It is very easy to use Git from the command line to deploy (or push) your node.js app to the Heroku server. First make sure you have opened your node.js project in Visual Code and also open up a terminal window.

Simply type:

> git add . 
> git commit
> git push heroku master

The git add . (with a dot) adds all your files to the local repository ready to be pushed to the remote Heroku server. After you commit, the third command above pushes all your files to the Heroku server Git master branch (the default branch).

That’s it! Test that your newly-deployed Heroku CRUD REST backend can connect to the MongoDB Atlas cloud database you setup earlier above and display the sample row of record which you created manually on the cloud database by typing the following in your browser URL:

https://<your-heroku-project-name>.herokuapp.com/users

(You may wish to do further debugging of the other CRUD operations and also view the logs from the Heroku server which you can display in your terminal by typing the command: heroku logs --tail)

Figure 14: Test your newly-deployed node.js app — display users list (/users)

(Note on my other articles on medium.com, please feel free to read:

For a rundown on fullstack Java and REST backend development and React frontend development, please check out : Creating a fullstack React/Material-UI DataGrid frontend data grid connected to a Java SpringBoot REST GET API backend with axios.

This article is further extended with my other article, Creating a fullstack Java app with AJAX HTML frontend using jsGrid datagrid and Apex Charts chart component calculating monthly averages from uploaded Excel data files on a Spring Boot REST backend running Apache Tomcat.

For a Python-Django REST API stack implementing HTTP GET, check out my other article, Creating a Python Django REST Service backend with Postgres database.

An Android/Google Location API article, Creating a Realtime Handphones Locations Tracker For Android Devices with Google Location API and Google Maps).

--

--

Ezani

38+ years as a programmer. Started with VB, now doing Java, SpringBoot, Android, React, ASP and Python. Running my own software company at mysoftware2u.com