Deploy a Node.js and MongoDB Application to Heroku
Tags: node, mongodb, heroku
Published: 2022-10-20 09:51:57

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:

- [A MongoDB Atlas account](https://account.mongodb.com/account/register)
- [A Heroku account](https://signup.heroku.com/login)
- [A clone of the sample project in this tutorial](https://github.com/icode247/crud-with-mongodb)

## Create a New MongoDB Cluster

Let's start by creating a [MongoDB cluster](https://www.mongodb.com/basics/clusters) 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](https://blog.appsignal.com/images/blog/2022-10/build-database.png)

2. Choose your cluster type. We'll use the 'Shared' cluster.
   ![Shared cluster](https://blog.appsignal.com/images/blog/2022-10/shared-cluster.png)

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](https://blog.appsignal.com/images/blog/2022-10/cluster-name.png)

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

5. Select where you want to connect from and click the 'Finish and Close' button.
   ![Finish and close](https://blog.appsignal.com/images/blog/2022-10/finish.png)

## Get Connection String

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

1. Click on the 'Connect' button.
   ![Connect](https://blog.appsignal.com/images/blog/2022-10/connect.png)

2. Select the 'Connect your application' tab.
   ![Connect application](https://blog.appsignal.com/images/blog/2022-10/connect-application.png)

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](https://blog.appsignal.com/images/blog/2022-10/heroku-app.png)

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

![Create app](https://blog.appsignal.com/images/blog/2022-10/create-app.png)

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](https://blog.appsignal.com/images/blog/2022-10/uri.png)

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](https://blog.appsignal.com/images/blog/2022-10/ip-address.png)

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](https://www.mongodb.com/docs/atlas/getting-started/) and [Heroku's official docs](https://devcenter.heroku.com/categories/reference).

Happy coding!

**P.S. If you liked this post, [subscribe to our JavaScript Sorcery list](https://blog.appsignal.com/javascript-sorcery) 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](https://www.appsignal.com/nodejs).**