javascript

Deploy a Node.js and MongoDB Application to Heroku

Ekekenta Odionyenfe

Ekekenta Odionyenfe on

Deploy a Node.js and MongoDB Application to Heroku

Do you have a Node.js project that you want to put into production but don't know how?

In this tutorial, you'll learn how to deploy a Node.js and MongoDB application to Heroku.

Before we get started, let's take a very quick look at Heroku and MongoDB.

What is Heroku?

Heroku is a cloud platform as a service (PaaS) that enables businesses to create, deliver, monitor, and scale applications.

Heroku was created to alleviate infrastructure concerns and eliminate the need for you to learn about network administration, server configuration, or database tuning.

Essentially, Heroku removes barriers so developers can concentrate on creating excellent apps.

Note: Heroku will pull their free plans on November 28th. Keep in mind that you’ll have to pay to use Heroku from this date onwards.

What is MongoDB Atlas?

MongoDB Atlas is a global cloud database that handles the complexities of deploying, managing, and healing your deployments on the cloud service provider of your choice (AWS, Azure, GCP). It lets you deploy, manage, and scale MongoDB in the cloud.

Prerequisites

Before you proceed, ensure you have the following set up:

Create a New MongoDB Cluster

Let's start by creating a MongoDB cluster for this project. Log in to Atlas and from your Atlas dashboard, follow these steps to create a new cluster:

  1. Click on the 'Build a Database' button.

    Build a Database

  2. Choose your cluster type. We'll use the 'Shared' cluster.

    Shared cluster

  3. Customize your cluster. Select 'Shared' > 'AWS' and click the 'Create Cluster' button.

To change the default cluster name, click on the 'Cluster Name' tab and enter your preferred name in the input field.

Cluster name
  1. Select the Authentication for your cluster. We'll use Username and Password. Enter Username and Password > Click 'Create User'.

  2. Select where you want to connect from and click the 'Finish and Close' button.

    Finish and close

Get Connection String

Now that your MongoDB Cluster has been created, let's get the connection string.

  1. Click on the 'Connect' button.

    Connect

  2. Select the 'Connect your application' tab.

    Connect application

  3. Copy the connection string.

Add Connection String

Now create a .env file in your project and add the connection string as shown below.

Note: It is always good practice to add your .env file to a .gitignore file, so as not to commit it to git.

text
MONGODB_URI = "YOUR CONNECTION STRING"

This way, you won't accidentally expose your credentials to the public.

To access the environment variables, we'll use the dotenv package. Install it with the command below:

shell
npm install --save-dev dotenv

Once the installation is complete, update app.js with the code snippet below.

javascript
if (process.env.NODE_ENV !== "production") { require("dotenv").config(); }

This code snippet loads the environment variables in the .env file if the environment isn't set to production. On Heroku process.env.NODE_ENV is set to production by default, so different environment variables will be used there. You can use this check to include code that should only run in production (or exclude code that shouldn't).

Now, if you run the application with the command npm start, the application will connect to the remote MongoDB Cluster.

Install Heroku CLI

Let's set up Heroku for the app deployment. First, install the Heroku CLI with the command below.

shell
npm install -g heroku

Once that's done, update the package.json to specify your start script.

json
"scripts": { "start": "node app.js", },

Then specify the Node.js version that you'll use to run your application.

json
... "engines": { "node": "14.x" }

Lastly, update your app listening port to listen to Heroku by default on production.

javascript
const PORT = process.env.PORT || 3001; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

Run Your Node.js and MongoDB App Locally

To test if everything works as expected, run the application locally before deploying it.

shell
heroku local web

For this demo application, you should see: Server is running on port 5000 and Connected to MongoDB.

Deploy Your Node.js and MongoDB App

Before we deploy our app, we need to create a Heroku app and add the environment variables that will be used in production. To do that, log into the Heroku dashboard and click on the 'New' button.

Heroku app

Select 'Create new app', enter the app name, select your region, and click the 'Create app' button.

Create app

Next, log in to the Heroku CLI with the command below.

shell
heroku login

The above command will prompt you for your credentials, and log you in.

Then initialize a git repository in a new or existing directory.

shell
git init heroku git:remote -a crud-with-mongodb

Next, commit your code to the repository and deploy it to Heroku using Git.

shell
git add . git commit -am "ready to deploy" git push heroku main

Wait some time for the application to deploy. Once the deployment is complete, the Heroku CLI will provide a remote URL for the application.

Now, back to your Heroku app! Click on 'Settings' > 'Reveal Config Vars', and add your MONGODB_URI.

MONGODB URI

Lastly, head over to MongoDB Cluster ('Network Access' > 'IP Access List' > 'ADD IP ADDRESS') and add your Host IP address to your Network Permission List. This gives your Host access to your cluster.

For this tutorial, we'll enable access from anywhere with the IP address 0.0.0.0/0.

IP address

Now you've deployed your Node.js application to Heroku!

Wrap Up

In this post, we went through the stages of deploying a Node.js and MongoDB app to Heroku. We first created a MongoDB cluster, then added the database connection string to an environment variable, before installing the Heroku CLI and finally deploying our application to Heroku.

You can learn more in MongoDB's official Atlas docs and Heroku's official docs.

Happy coding!

P.S. If you liked this post, subscribe to our JavaScript Sorcery list for a monthly deep dive into more magical JavaScript tips and tricks.

P.P.S. If you need an APM for your Node.js app, go and check out the AppSignal APM for Node.js.

Ekekenta Odionyenfe

Ekekenta Odionyenfe

Our guest author Ekekenta Odionyenfe is a Software Engineer and Technical Writer with over four years of experience in technology, software development and content creation.

All articles by Ekekenta Odionyenfe

Become our next author!

Find out more

AppSignal monitors your apps

AppSignal provides insights for Ruby, Rails, Elixir, Phoenix, Node.js, Express and many other frameworks and libraries. We are located in beautiful Amsterdam. We love stroopwafels. If you do too, let us know. We might send you some!

Discover AppSignal
AppSignal monitors your apps