DEV Community

Cover image for Deploy a Node.js and MongoDB Application to Heroku
Ekekenta Odionyenfe Clinton for AppSignal

Posted on • Originally published at blog.appsignal.com

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.

MONGODB_URI = "YOUR CONNECTION STRING"
Enter fullscreen mode Exit fullscreen mode

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:

npm install --save-dev dotenv
Enter fullscreen mode Exit fullscreen mode

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

if (process.env.NODE_ENV !== "production") {
  require("dotenv").config();
}
Enter fullscreen mode Exit fullscreen mode

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.

npm install -g heroku
Enter fullscreen mode Exit fullscreen mode

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

"scripts": {
  "start": "node app.js",
},
Enter fullscreen mode Exit fullscreen mode

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

...
"engines": {
  "node": "14.x"
}
Enter fullscreen mode Exit fullscreen mode

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

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

Run Your Node.js and MongoDB App Locally

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

heroku local web
Enter fullscreen mode Exit fullscreen mode

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.

heroku login
Enter fullscreen mode Exit fullscreen mode

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

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

git init
heroku git:remote -a crud-with-mongodb
Enter fullscreen mode Exit fullscreen mode

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

git add .
git commit -am "ready to deploy"
git push heroku main
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)